Prompt specification
Build or customize the Three.js 3D scene "Coastal settlement density transect" 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: Coastal settlement density transect
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/coastal-settlement-density-transect-x1335
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows population density. Build a fictional coast-to-inland transect with equal-area cells and population stacks. Separate water cells from habitable land and expose how denominator choice changes density values. Low-poly.
Working Three.js Starter (coastal-settlement-density-transect-x1335):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Coastal Population Density</title>
<style>
:root {
--ink: #18343b;
--muted: #62777b;
--paper: rgba(250, 249, 243, 0.94);
--paper-solid: #faf9f3;
--line: rgba(24, 52, 59, 0.14);
--accent: #e76243;
--teal: #258c8e;
--yellow: #e9bd4f;
--orange: #e88955;
--red: #ce4e4e;
--water: #398fa3;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8eee8;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--line);
background: var(--paper);
box-shadow:
0 18px 55px rgba(31, 57, 61, 0.10),
0 2px 8px rgba(31, 57, 61, 0.05);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.intro {
top: 26px;
left: 28px;
width: min(500px, calc(100vw - 56px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
content: "";
box-shadow: 0 0 0 4px rgba(231, 98, 67, 0.13);
}
h1 {
max-width: 480px;
margin: 0;
font-size: clamp(34px, 4.6vw, 62px);
font-weight: 760;
letter-spacing: -0.055em;
line-height: 0.98;
}
.intro p {
max-width: 465px;
margin: 16px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
.denominator-panel {
top: 24px;
right: 24px;
width: 370px;
padding: 18px;
border-radius: 18px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.panel-heading h2,
.inspector h2 {
margin: 0;
font-size: 13px;
font-weight: 800;
letter-spacing: -0.01em;
}
.constant-badge {
padding: 5px 8px;
border: 1px solid rgba(37, 140, 142, 0.22);
border-radius: 999px;
background: rgba(37, 140, 142, 0.08);
color: var(--teal);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.mode-tabs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 15px;
}
.mode-button {
min-height: 64px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.48);
color: var(--ink);
cursor: pointer;
text-align: left;
transition:
background 160ms ease,
border-color 160ms ease,
transform 160ms ease,
box-shadow 160ms ease;
}
.mode-button:hover {
transform: translateY(-1px);
border-color: rgba(24, 52, 59, 0.28);
}
.mode-button[aria-pressed="true"] {
border-color: var(--ink);
background: var(--ink);
color: #fffdf6;
box-shadow: 0 8px 18px rgba(24, 52, 59, 0.16);
}
.mode-button span {
display: block;
margin-bottom: 5px;
font-size: 12px;
font-weight: 780;
}
.mode-button small {
display: block;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.mode-button[aria-pressed="true"] small {
color: rgba(255, 255, 255, 0.67);
}
.metric {
padding: 15px 0 13px;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.metric-label {
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.metric-value-row {
display: flex;
align-items: baseline;
gap: 8px;
}
#density-value {
font-size: clamp(36px, 4vw, 48px);
font-weight: 790;
letter-spacing: -0.055em;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.metric-unit {
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.formula {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 5px;
margin-top: 10px;
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.formula strong {
color: var(--ink);
font-weight: 780;
}
.comparison {
margin-top: 13px;
}
.compare-row {
display: grid;
grid-template-columns: 82px 1fr 66px;
align-items: center;
gap: 8px;
margin: 8px 0;
color: var(--muted);
font-size: 10px;
}
.compare-row.active {
color: var(--ink);
font-weight: 800;
}
.compare-track {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(24, 52, 59, 0.08);
}
.compare-fill {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
transition: width 500ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
#all-fill {
background: var(--water);
}
#land-fill {
background: var(--accent);
}
.compare-value {
text-align: right;
font-variant-numeric: tabular-nums;
}
.insight {
min-height: 39px;
margin: 11px 0 0;
padding: 9px 10px;
border-radius: 9px;
background: rgba(231, 98, 67, 0.08);
color: #785044;
font-size: 10px;
line-height: 1.45;
}
.area-accounting {
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.area-strip {
display: flex;
height: 9px;
overflow: hidden;
border-radius: 99px;
background: #dce4df;
}
#water-segment {
background: var(--water);
}
#land-segment {
background: #8eae7a;
}
.area-key {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.legend-panel {
bottom: 24px;
left: 24px;
width: 310px;
padding: 15px 16px;
border-radius: 15px;
}
.legend-grid {
display: grid;
grid-template-columns: 53px 1fr;
gap: 12px;
align-items: center;
}
.stack-icon {
position: relative;
width: 42px;
height: 43px;
}
.stack-icon i {
position: absolute;
left: 5px;
width: 32px;
height: 10px;
border: 1px solid rgba(24, 52, 59, 0.12);
border-radius: 3px;
background: var(--yellow);
transform: skewY(-8deg);
}
.stack-icon i:nth-child(1) {
bottom: 0;
}
.stack-icon i:nth-child(2) {
bottom: 11px;
background: var(--orange);
}
.stack-icon i:nth-child(3) {
bottom: 22px;
background: var(--red);
}
.legend-title {
margin-bottom: 3px;
font-size: 11px;
font-weight: 800;
}
.legend-copy {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.density-scale {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 3px;
margin-top: 12px;
}
.density-scale div {
position: relative;
height: 7px;
border-radius: 2px;
}
.density-scale div:nth-child(1) {
background: #49aaa3;
}
.density-scale div:nth-child(2) {
background: #d8c956;
}
.density-scale div:nth-child(3) {
background: #e58a56;
}
.density-scale div:nth-child(4) {
background: #ca4b4b;
}
.scale-labels {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
}
.map-note {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.map-note kbd {
padding: 2px 5px;
border: 1px solid var(--line);
border-bottom-width: 2px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.7);
color: var(--ink);
font: inherit;
font-weight: 800;
}
.inspector {
right: 24px;
bottom: 24px;
width: 320px;
padding: 17px;
border-radius: 16px;
}
.inspector-status {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 14px;
}
.cell-type {
padding: 5px 8px;
border-radius: 99px;
background: rgba(37, 140, 142, 0.10);
color: var(--teal);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.cell-type.water {
background: rgba(57, 143, 163, 0.12);
color: var(--water);
}
.cell-title {
margin: 0 0 4px;
font-size: 23px;
font-weight: 780;
letter-spacing: -0.035em;
}
.cell-subtitle {
margin: 0 0 13px;
color: var(--muted);
font-size: 10px;
}
.cell-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.cell-stat {
min-height: 67px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.42);
}
.cell-stat span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.cell-stat strong {
display: block;
font-size: 17px;
font-weight: 790;
letter-spacing: -0.025em;
font-variant-numeric: tabular-nums;
}
.cell-stat small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
}
.cell-footnote {
margin: 11px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.reset-button {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.55);
color: var(--ink);
cursor: pointer;
font-size: 9px;
font-weight: 800;
}
.reset-button:hover {
background: #fff;
}
.reset-button svg {
width: 12px;
height: 12px;
}
#world-labels {
position: fixed;
inset: 0;
z-index: 2;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.42);
border-radius: 7px;
background: rgba(24, 52, 59, 0.72);
color: #f9f7ed;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-50%, -50%);
box-shadow: 0 6px 18px rgba(24, 52, 59, 0.14);
}
.world-label.water {
background: rgba(57, 143, 163, 0.83);
}
.world-label.land {
background: rgba(84, 113, 73, 0.82);
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
min-width: 165px;
padding: 10px 11px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 10px;
background: rgba(18, 42, 48, 0.94);
color: #fffdf5;
box-shadow: 0 12px 30px rgba(16, 37, 42, 0.25);
pointer-events: none;
}
#tooltip.visible {
display: block;
}
.tooltip-head {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 5px;
color: rgba(255, 255, 255, 0.62);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.tooltip-value {
font-size: 17px;
font-weight: 780;
letter-spacing: -0.02em;
}
.tooltip-sub {
margin-top: 3px;
color: rgba(255, 255, 255, 0.67);
font-size: 9px;
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
background: #e8eee8;
color: var(--ink);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 1000px) {
.intro {
width: 390px;
}
h1 {
font-size: 42px;
}
.denominator-panel {
width: 335px;
}
.legend-panel {
width: 275px;
}
.inspector {
width: 285px;
}
}
@media (max-width: 760px) {
.intro {
top: 16px;
left: 16px;
width: calc(100vw - 32px);
}
h1 {
max-width: 390px;
font-size: clamp(31px, 9vw, 45px);
}
.intro p {
max-width: 390px;
margin-top: 10px;
font-size: 11px;
}
.denominator-panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
padding: 13px;
border-radius: 14px;
}
.panel-heading {
margin-bottom: 8px;
}
.mode-tabs {
margin-bottom: 9px;
}
.mode-button {
min-height: 52px;
padding: 8px;
}
.metric {
padding: 10px 0;
}
#density-value {
font-size: 35px;
}
.comparison,
.area-accounting {
display: none;
}
.legend-panel,
.inspector,
.world-label {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="world-labels" aria-hidden="true">
<div id="label-water" class="world-label water">Water cells</div>
<div id="label-coast" class="world-label">Coastline</div>
<div id="label-land" class="world-label land">Habitable inland</div>
</div>
<header class="intro">
<div class="eyebrow">Fictional coastal transect · 01</div>
<h1>Population density, with the water in view.</h1>
<p>
A fictional 2.0 × 1.2 km coast-to-inland transect. Every square is the
same 1-hectare cell. Population stacks stay constant; only the density
denominator changes.
</p>
</header>
<section class="panel denominator-panel" aria-label="Density denominator controls">
<div class="panel-heading">
<h2>Choose the denominator</h2>
<span class="constant-badge">Same population</span>
</div>
<div class="mode-tabs" role="group" aria-label="Density denominator">
<button
class="mode-button"
type="button"
data-mode="all"
aria-pressed="true"
>
<span>All transect cells</span>
<small id="all-area-button">2.40 km² · includes water</small>
</button>
<button
class="mode-button"
type="button"
data-mode="land"
aria-pressed="false"
>
<span>Habitable land only</span>
<small id="land-area-button">1.88 km² · excludes water</small>
</button>
</div>
<div class="metric" aria-live="polite">
<div class="metric-label">Aggregate population density</div>
<div class="metric-value-row">
<strong id="density-value">0</strong>
<span class="metric-unit">people / km²</span>
</div>
<div class="formula">
<strong id="formula-population">0 people</strong>
<span>÷</span>
<strong id="formula-area">2.40 km²</strong>
</div>
</div>
<div class="comparison" aria-label="Density comparison">
<div id="row-all" class="compare-row active">
<span>All cells</span>
<div class="compare-track"><i id="all-fill" class="compare-fill"></i></div>
<b id="all-density" class="compare-value">0</b>
</div>
<div id="row-land" class="compare-row">
<span>Land only</span>
<div class="compare-track"><i id="land-fill" class="compare-fill"></i></div>
<b id="land-density" class="compare-value">0</b>
</div>
<p id="mode-insight" class="insight"></p>
</div>
<div class="area-accounting">
<div class="area-strip" aria-hidden="true">
<span id="water-segment"></span>
<span id="land-segment"></span>
</div>
<div class="area-key">
<span id="water-area-label">Water: 0 ha</span>
<span id="land-area-label">Habitable: 0 ha</span>
</div>
</div>
</section>
<section class="panel legend-panel" aria-label="Map legend">
<div class="legend-grid">
<div class="stack-icon" aria-hidden="true"><i></i><i></i><i></i></div>
<div>
<div class="legend-title">One block = 50 people</div>
<div class="legend-copy">
A partial block represents the remaining residents. All tiles have
identical area.
</div>
</div>
</div>
<div class="density-scale" aria-hidden="true">
<div></div><div></div><div></div><div></div>
</div>
<div class="scale-labels">
<span><10k</span><span>25k</span><span>45k</span><span>60k+ / km²</span>
</div>
<div class="map-note">
<kbd>Drag</kbd> to orbit · <kbd>Scroll</kbd> to zoom ·
<kbd>1</kbd>/<kbd>2</kbd> to change denominator · <kbd>R</kbd> resets.
Hover or tap a cell to inspect it.
</div>
</section>
<aside class="panel inspector" aria-label="Cell inspector">
<div class="inspector-status">
<h2>Cell inspector</h2>
<button class="reset-button" id="reset-view" type="button">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path
d="M4 4v6h6M20 20v-6h-6M5.6 15a7 7 0 0 0 11.7 2.6L20 14M4 10l2.7-3.6A7 7 0 0 1 18.4 9"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
Reset view
</button>
</div>
<div id="cell-type" class="cell-type">Habitable land</div>
<h3 id="cell-title" class="cell-title">Cell L-01-01</h3>
<p id="cell-subtitle" class="cell-subtitle">Inspecting a cell</p>
<div class="cell-stats">
<div class="cell-stat">
<span>Cell area</span>
<strong>1.00 ha</strong>
<small>0.01 km²</small>
</div>
<div class="cell-stat">
<span>Population</span>
<strong id="cell-population">—</strong>
<small id="cell-stack">—</small>
</div>
<div class="cell-stat">
<span>Cell density</span>
<strong id="cell-density">—</strong>
<small>people / km²</small>
</div>
<div class="cell-stat">
<span>Position</span>
<strong id="cell-position">—</strong>
<small id="cell-coordinate">—</small>
</div>
</div>
<p id="cell-footnote" class="cell-footnote"></p>
</aside>
<div id="tooltip" role="status"></div>
<div id="loading">Building coastal transect…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const COLS = 20;
const ROWS = 12;
const CELL_AREA_KM2 = 0.01;
const PEOPLE_PER_BLOCK = 50;
const CELL_WIDTH_METERS = 100;
const $ = (id) => document.getElementById(id);
const numberFormat = new Intl.NumberFormat("en-US", {
maximumFractionDigits: 0
});
const oneDecimalFormat = new Intl.NumberFormat("en-US", {
minimumFractionDigits: 1,
maximumFractionDigits: 1
});
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e8eee8");
scene.fog = new THREE.Fog("#e8eee8", 42, 78);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-15, 15, 10, -10, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.8, 0);
const controls = {
theta: 0.28,
phi: 0.91,
zoom: 1,
desiredTheta: 0.28,
desiredPhi: 0.91,
desiredZoom: 1,
radius: 32
};
const hemi = new THREE.HemisphereLight(0xfff8e8, 0x527078, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffedcf, 3.1);
sun.position.set(-9, 18, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -17;
sun.shadow.camera.right = 17;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9e4e5, 0.75);
fill.position.set(12, 8, -12);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshStandardMaterial({
color: "#e8eee8",
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.59;
ground.receiveShadow = true;
scene.add(ground);
const slab = new THREE.Mesh(
new THREE.BoxGeometry(COLS + 0.55, 0.4, ROWS + 0.55),
new THREE.MeshStandardMaterial({
color: "#29474d",
roughness: 0.92,
metalness: 0.02,
flatShading: true
})
);
slab.position.y = -0.38;
slab.castShadow = true;
slab.receiveShadow = true;
scene.add(slab);
const slabEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(slab.geometry),
new THREE.LineBasicMaterial({
color: "#18343b",
transparent: true,
opacity: 0.55
})
);
slabEdges.position.copy(slab.position);
scene.add(slabEdges);
// Deterministic random generator keeps the fictional transect reproducible.
let seed = 81729;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
const cells = [];
const landCells = [];
const waterCells = [];
const coastByRow = [];
for (let row = 0; row < ROWS; row++) {
const wave = 1.4 + Math.sin(row * 0.72 + 0.35) * 1.35;
const waterColumns = clamp(
2 + Math.floor(wave + random() * 2.4),
1,
7
);
coastByRow.push(waterColumns);
for (let col = 0; col < COLS; col++) {
const isWater = col < waterColumns;
const x = col - (COLS - 1) / 2;
const z = row - (ROWS - 1) / 2;
const inlandDistance = Math.max(0, col - waterColumns);
let population = 0;
if (!isWater) {
const coastalWeight = Math.exp(-inlandDistance / 4.3);
const alongShoreWeight =
Math.exp(-Math.pow(row - 5.25, 2) / 17) * 0.75 +
Math.exp(-Math.pow(row - 9.5, 2) / 10) * 0.45;
population =
80 +
520 * coastalWeight * (0.55 + random() * 0.75) +
225 * alongShoreWeight * Math.exp(-inlandDistance / 7.2) +
random() * 48;
const hubs = [
{ d: 1, r: 5, amount: 780 },
{ d: 4, r: 9, amount: 520 },
{ d: 8, r: 3, amount: 280 }
];
for (const hub of hubs) {
const distance =
Math.pow(inlandDistance - hub.d, 2) / 8 +
Math.pow(row - hub.r, 2) / 12;
population += hub.amount * Math.exp(-distance);
}
population = Math.min(1450, Math.round(population / 10) * 10);
}
const cell = {
id: isWater
? `W-${String(col + 1).padStart(2, "0")}-${String(row + 1).padStart(2, "0")}`
: `L-${String(col + 1).padStart(2, "0")}-${String(row + 1).padStart(2, "0")}`,
col,
row,
x,
z,
isWater,
population,
density: population / CELL_AREA_KM2,
waterColumns,
inlandDistance
};
cells.push(cell);
(isWater ? waterCells : landCells).push(cell);
}
}
const totalPopulation = landCells.reduce(
(sum, cell) => sum + cell.population,
0
);
const totalArea = cells.length * CELL_AREA_KM2;
const landArea = landCells.length * CELL_AREA_KM2;
const waterArea = waterCells.length * CELL_AREA_KM2;
const allDensity = totalPopulation / totalArea;
const landDensity = totalPopulation / landArea;
const densityDifference = landDensity - allDensity;
const densityPercent = (densityDifference / allDensity) * 100;
const tileGeometry = new THREE.BoxGeometry(0.92, 0.2, 0.92);
const landMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95,
metalness: 0,
flatShading: true
});
const landMesh = new THREE.InstancedMesh(
tileGeometry,
landMaterial,
landCells.length
);
landMesh.castShadow = true;
landMesh.receiveShadow = true;
landMesh.userData.cells = landCells;
scene.add(landMesh);
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.36,
metalness: 0.02,
transparent: true,
opacity: 0.86,
flatShading: true
});
const waterGeometry = new THREE.BoxGeometry(0.92, 0.12, 0.92);
const waterMesh = new THREE.InstancedMesh(
waterGeometry,
waterMaterial,
waterCells.length
);
waterMesh.receiveShadow = true;
waterMesh.userData.cells = waterCells;
scene.add(waterMesh);
const dummy = new THREE.Object3D();
const greenNear = new THREE.Color("#789c72");
const greenFar = new THREE.Color("#b8bd82");
const waterDark = new THREE.Color("#2f8299");
const waterLight = new THREE.Color("#61b6c2");
landCells.forEach((cell, index) => {
dummy.position.set(cell.x, -0.08, cell.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
landMesh.setMatrixAt(index, dummy.matrix);
const inlandMix = clamp(
0.22 + cell.inlandDistance / 21 + random() * 0.16,
0,
1
);
const color = greenNear.clone().lerp(greenFar, inlandMix);
landMesh.setColorAt(index, color);
});
landMesh.instanceMatrix.needsUpdate = true;
if (landMesh.instanceColor) landMesh.instanceColor.needsUpdate = true;
landMesh.computeBoundingSphere();
landMesh.computeBoundingBox();
waterCells.forEach((cell, index) => {
dummy.position.set(cell.x, -0.12, cell.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
waterMesh.setMatrixAt(index, dummy.matrix);
const waterMix = clamp(
0.18 + random() * 0.7 + Math.sin(cell.row) * 0.06,
0,
1
);
const color = waterDark.clone().lerp(waterLight, waterMix);
waterMesh.setColorAt(index, color);
});
waterMesh.instanceMatrix.needsUpdate = true;
if (waterMesh.instanceColor) waterMesh.instanceColor.needsUpdate = true;
waterMesh.computeBoundingSphere();
waterMesh.computeBoundingBox();
// Each population block has equal volume. A partial block is shortened.
const blockRecords = [];
for (const cell of landCells) {
let remaining = cell.population;
let blockIndex = 0;
let accumulatedHeight = 0;
while (remaining > 0) {
const amount = Math.min(PEOPLE_PER_BLOCK, remaining);
const height = 0.18 * (amount / PEOPLE_PER_BLOCK);
blockRecords.push({
x: cell.x,
z: cell.z,
y: 0.035 + accumulatedHeight + height / 2,
height,
density: cell.density,
blockIndex
});
accumulatedHeight += height;
remaining -= amount;
blockIndex++;
}
}
const blockGeometry = new THREE.BoxGeometry(0.48, 1, 0.48);
const blockMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.72,
metalness: 0,
flatShading: true
});
const blockMesh = new THREE.InstancedMesh(
blockGeometry,
blockMaterial,
blockRecords.length
);
blockMesh.castShadow = true;
blockMesh.receiveShadow = true;
scene.add(blockMesh);
const densityColors = {
low: new THREE.Color("#49aaa3"),
medium: new THREE.Color("#d8c956"),
high: new THREE.Color("#e58a56"),
extreme: new THREE.Color("#ca4b4b")
};
function densityColor(density) {
if (density < 10000) return densityColors.low;
if (density < 25000) return densityColors.medium;
if (density < 45000) return densityColors.high;
return densityColors.extreme;
}
const blockHighlight = new THREE.Color("#fff5d4");
blockRecords.forEach((block, index) => {
dummy.position.set(block.x, block.y, block.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, block.height, 1);
dummy.updateMatrix();
blockMesh.setMatrixAt(index, dummy.matrix);
const color = densityColor(block.density).clone();
color.lerp(blockHighlight, Math.min(block.blockIndex * 0.018, 0.16));
blockMesh.setColorAt(index, color);
});
blockMesh.instanceMatrix.needsUpdate = true;
if (blockMesh.instanceColor) blockMesh.instanceColor.needsUpdate = true;
blockMesh.computeBoundingSphere();
blockMesh.computeBoundingBox();
// Jagged, low-poly coastline along the stepped water boundary.
const coastlinePoints = [];
const firstBoundary = -COLS / 2 + coastByRow[0];
coastlinePoints.push(
new THREE.Vector3(firstBoundary, 0.045, -ROWS / 2)
);
for (let row = 0; row < ROWS; row++) {
const boundary = -COLS / 2 + coastByRow[row];
const z = row - (ROWS - 1) / 2;
coastlinePoints.push(new THREE.Vector3(boundary, 0.045, z));
if (row < ROWS - 1) {
const nextBoundary = -COLS / 2 + coastByRow[row + 1];
coastlinePoints.push(
new THREE.Vector3(nextBoundary, 0.045, z)
);
coastlinePoints.push(
new THREE.Vector3(nextBoundary, 0.045, z + 1)
);
}
}
const coastline = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(coastlinePoints),
new THREE.LineBasicMaterial({
color: "#fff4d7",
transparent: true,
opacity: 0.92
})
);
scene.add(coastline);
const selectedOutline = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(0.97, 0.28, 0.97)
),
new THREE.LineBasicMaterial({
color: "#e76243",
depthTest: false,
transparent: true,
opacity: 0.95
})
);
selectedOutline.renderOrder = 30;
scene.add(selectedOutline);
const hoverOutline = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(0.98, 0.3, 0.98)
),
new THREE.LineBasicMaterial({
color: "#fffdf0",
depthTest: false,
transparent: true,
opacity: 0.9
})
);
hoverOutline.renderOrder = 31;
hoverOutline.visible = false;
scene.add(hoverOutline);
let selectedCell = landCells.reduce((best, cell) =>
cell.population > best.population ? cell : best
);
let hoveredCell = null;
let mode = "all";
let densityAnimation = 0;
function formatPeople(value) {
return numberFormat.format(value);
}
function formatArea(value) {
return `${value.toFixed(2)} km²`;
}
function positionOutline(outline, cell) {
outline.position.set(
cell.x,
cell.isWater ? -0.02 : 0.1,
cell.z
);
}
function updateInspector(cell, source = "Selected cell") {
if (!cell) return;
const type = $("cell-type");
type.textContent = cell.isWater ? "Water cell" : "Habitable land";
type.classList.toggle("water", cell.isWater);
$("cell-title").textContent = `Cell ${cell.id}`;
const seawardDistance =
(cell.waterColumns - cell.col) * CELL_WIDTH_METERS;
const positionText = cell.isWater
? `${(seawardDistance / 1000).toFixed(1)} km seaward`
: `${((cell.inlandDistance + 0.5) * 0.1).toFixed(1)} km inland`;
$("cell-subtitle").textContent =
`${source} · ${cell.isWater ? "excluded from land-only area" : "included in habitable area"}`;
if (cell.isWater) {
$("cell-population").textContent = "—";
$("cell-stack").textContent = "No stack";
$("cell-density").textContent = "—";
$("cell-footnote").textContent =
"Water cells remain visible in both denominator modes. They contribute area to the transect total, but never population.";
} else {
const fullBlocks = Math.floor(
cell.population / PEOPLE_PER_BLOCK
);
const remainder = cell.population % PEOPLE_PER_BLOCK;
$("cell-population").textContent =
formatPeople(cell.population);
$("cell-stack").textContent =
remainder > 0
? `${fullBlocks} full + ${remainder}`
: `${fullBlocks} full blocks`;
$("cell-density").textContent =
formatPeople(cell.density);
$("cell-footnote").textContent =
"Cell density always uses this one-hectare cell as its denominator. The map-wide metric uses the selected total area.";
}
$("cell-position").textContent = positionText;
$("cell-coordinate").textContent =
`column ${String(cell.col + 1).padStart(2, "0")} · row ${String(cell.row + 1).padStart(2, "0")}`;
}
function selectCell(cell) {
selectedCell = cell;
positionOutline(selectedOutline, selectedCell);
updateInspector(selectedCell, "Selected cell");
}
function animateDensity(target) {
cancelAnimationFrame(densityAnimation);
const start = performance.now();
const from = Number($("density-value").dataset.value || 0);
const duration = 520;
function step(now) {
const t = clamp((now - start) / duration, 0, 1);
const eased = 1 - Math.pow(1 - t, 3);
const value = from + (target - from) * eased;
$("density-value").textContent = formatPeople(value);
$("density-value").dataset.value = String(value);
if (t < 1) {
densityAnimation = requestAnimationFrame(step);
}
}
densityAnimation = requestAnimationFrame(step);
}
function setMode(nextMode) {
mode = nextMode;
const density = mode === "all" ? allDensity : landDensity;
document.querySelectorAll(".mode-button").forEach((button) => {
button.setAttribute(
"aria-pressed",
String(button.dataset.mode === mode)
);
});
$("row-all").classList.toggle("active", mode === "all");
$("row-land").classList.toggle("active", mode === "land");
$("formula-area").textContent = formatArea(
mode === "all" ? totalArea : landArea
);
$("mode-insight").textContent =
mode === "all"
? `Keeping water in the denominator gives ${formatPeople(density)} people/km². Land-only would be ${densityPercent.toFixed(1)}% higher.`
: `Removing water raises the density by ${formatPeople(densityDifference)} people/km², or ${densityPercent.toFixed(1)}%, without changing the population.`;
waterMaterial.opacity = mode === "land" ? 0.61 : 0.86;
animateDensity(density);
}
$("all-area-button").textContent =
`${totalArea.toFixed(2)} km² · includes water`;
$("land-area-button").textContent =
`${landArea.toFixed(2)} km² · excludes water`;
$("formula-population").textContent =
`${formatPeople(totalPopulation)} people`;
$("all-density").textContent = formatPeople(allDensity);
$("land-density").textContent = formatPeople(landDensity);
const maxComparisonDensity = Math.max(allDensity, landDensity);
$("all-fill").style.width =
`${(allDensity / maxComparisonDensity) * 100}%`;
$("land-fill").style.width =
`${(landDensity / maxComparisonDensity) * 100}%`;
$("water-segment").style.width =
`${(waterCells.length / cells.length) * 100}%`;
$("land-segment").style.width =
`${(landCells.length / cells.length) * 100}%`;
$("water-area-label").textContent =
`Water: ${numberFormat.format(waterCells.length)} cells · ${numberFormat.format(waterArea * 100)} ha`;
$("land-area-label").textContent =
`Habitable: ${numberFormat.format(landCells.length)} cells · ${numberFormat.format(landArea * 100)} ha`;
document.querySelectorAll(".mode-button").forEach((button) => {
button.addEventListener("click", () => {
setMode(button.dataset.mode);
});
});
selectCell(selectedCell);
setMode("all");
// Raycasting against the tile meshes intentionally ignores the blocks,
// so clicking anywhere in a cell still selects that cell.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const tooltip = $("tooltip");
function getCellAtEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
[landMesh, waterMesh],
false
);
if (!hits.length) return null;
const hit = hits[0];
const meshCells = hit.object.userData.cells;
return meshCells[hit.instanceId] || null;
}
function showTooltip(cell, event) {
const rect = renderer.domElement.getBoundingClientRect();
const left = clamp(
event.clientX + 15,
8,
window.innerWidth - 190
);
const top = clamp(
event.clientY - 15,
8,
window.innerHeight - 95
);
tooltip.innerHTML = cell.isWater
? `
<div class="tooltip-head">
<span>${cell.id}</span><span>Water</span>
</div>
<div class="tooltip-value">No residents</div>
<div class="tooltip-sub">1.00 ha · excluded in land-only mode</div>
`
: `
<div class="tooltip-head">
<span>${cell.id}</span><span>Habitable</span>
</div>
<div class="tooltip-value">${formatPeople(cell.population)} people</div>
<div class="tooltip-sub">
${formatPeople(cell.density)} people/km² ·
${oneDecimalFormat.format(cell.population / PEOPLE_PER_BLOCK)} blocks
</div>
`;
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
tooltip.classList.add("visible");
}
function hideTooltip() {
tooltip.classList.remove("visible");
}
function updateHover(event) {
const cell = getCellAtEvent(event);
hoveredCell = cell;
renderer.domElement.style.cursor = cell ? "pointer" : "grab";
if (!cell) {
hoverOutline.visible = false;
hideTooltip();
updateInspector(selectedCell, "Selected cell");
return;
}
positionOutline(hoverOutline, cell);
hoverOutline.visible = true;
showTooltip(cell, event);
updateInspector(cell, "Hover preview");
}
let pointerDown = false;
let dragging = false;
let moved = false;
let lastX = 0;
let lastY = 0;
let startX = 0;
let startY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
dragging = false;
moved = false;
lastX = startX = event.clientX;
lastY = startY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
hideTooltip();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (
Math.hypot(
event.clientX - startX,
event.clientY - startY
) > 4
) {
moved = true;
dragging = true;
}
if (dragging) {
controls.desiredTheta -= dx * 0.006;
controls.desiredPhi = clamp(
controls.desiredPhi - dy * 0.005,
0.42,
1.25
);
}
lastX = event.clientX;
lastY = event.clientY;
return;
}
updateHover(event);
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointerDown = false;
if (!moved) {
const cell = getCellAtEvent(event);
if (cell) selectCell(cell);
}
dragging = false;
renderer.domElement.style.cursor = hoveredCell ? "pointer" : "grab";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
dragging = false;
hoverOutline.visible = false;
hideTooltip();
updateInspector(selectedCell, "Selected cell");
});
renderer.domElement.addEventListener("pointerleave", () => {
if (pointerDown) return;
hoveredCell = null;
hoverOutline.visible = false;
hideTooltip();
updateInspector(selectedCell, "Selected cell");
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.desiredZoom = clamp(
controls.desiredZoom * Math.exp(-event.deltaY * 0.0011),
0.72,
2.5
);
},
{ passive: false }
);
function resetView() {
controls.desiredTheta = 0.28;
controls.desiredPhi = 0.91;
controls.desiredZoom = 1;
}
$("reset-view").addEventListener("click", resetView);
renderer.domElement.addEventListener("dblclick", resetView);
window.addEventListener("keydown", (event) => {
if (event.key === "1") setMode("all");
if (event.key === "2") setMode("land");
if (event.key.toLowerCase() === "r") resetView();
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(18, 25 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
window.addEventListener("resize", resize);
resize();
const labelDefinitions = [
{
element: $("label-water"),
position: new THREE.Vector3(-8.3, 0.25, -1.6)
},
{
element: $("label-coast"),
position: new THREE.Vector3(-5.7, 0.3, 4.25)
},
{
element: $("label-land"),
position: new THREE.Vector3(6.3, 0.3, -3.7)
}
];
function updateWorldLabels() {
const width = renderer.domElement.clientWidth;
const height = renderer.domElement.clientHeight;
for (const definition of labelDefinitions) {
const projected = definition.position.clone().project(camera);
const visible =
projected.z >= -1 &&
projected.z <= 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
definition.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
definition.element.style.left = `${x}px`;
definition.element.style.top = `${y}px`;
}
}
function updateCamera() {
controls.theta +=
(controls.desiredTheta - controls.theta) * 0.09;
controls.phi +=
(controls.desiredPhi - controls.phi) * 0.09;
controls.zoom +=
(controls.desiredZoom - controls.zoom) * 0.1;
const sinPhi = Math.sin(controls.phi);
const cosPhi = Math.cos(controls.phi);
camera.position.set(
cameraTarget.x +
controls.radius * sinPhi * Math.sin(controls.theta),
cameraTarget.y + controls.radius * cosPhi,
cameraTarget.z +
controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(cameraTarget);
camera.zoom = controls.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
let firstFrame = true;
renderer.setAnimationLoop(() => {
updateCamera();
updateWorldLabels();
renderer.render(scene, camera);
if (firstFrame) {
firstFrame = false;
$("loading").classList.add("hidden");
}
});
</script>
</body>
</html>
```