Prompt specification
Build or customize the Three.js 3D scene "Redistribute housing without changing population" 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: Redistribute housing without changing population
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/redistribute-housing-without-changing-population-x1336
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts population density. Let users move household groups between fixed grid cells. Update local density and service distance while keeping total residents constant and avoiding claims about real migration behavior. Low-poly.
Working Three.js Starter (redistribute-housing-without-changing-population-x1336):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Resident Grid — Synthetic Density Sandbox</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(10, 21, 37, 0.84);
--panel-edge: rgba(160, 213, 255, 0.16);
--text: #edf6ff;
--muted: #9eb2c8;
--cyan: #63dcff;
--mint: #59e0ac;
--amber: #ffc85a;
--coral: #ff735f;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 36%, #172a43 0, #0b1626 45%, #050b14 100%);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 4;
top: 18px;
left: 18px;
right: 18px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
text-shadow: 0 2px 18px #000;
}
.logo {
position: relative;
width: 39px;
height: 39px;
border: 1px solid rgba(99, 220, 255, 0.48);
border-radius: 12px;
background:
linear-gradient(135deg, rgba(99, 220, 255, 0.2), rgba(89, 224, 172, 0.05));
box-shadow: inset 0 0 18px rgba(99, 220, 255, 0.08);
transform: rotate(-7deg);
}
.logo::before,
.logo::after {
content: "";
position: absolute;
border-radius: 3px;
background: var(--cyan);
opacity: 0.82;
}
.logo::before {
width: 8px;
height: 8px;
left: 8px;
top: 8px;
box-shadow: 12px 0 0 rgba(89, 224, 172, 0.9);
}
.logo::after {
width: 8px;
height: 8px;
left: 8px;
top: 22px;
box-shadow: 12px 0 0 rgba(255, 200, 90, 0.9);
}
.brand h1 {
margin: 0;
font-size: clamp(18px, 2vw, 26px);
line-height: 1;
letter-spacing: -0.03em;
}
.brand p {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stats {
display: flex;
align-items: stretch;
gap: 8px;
padding: 7px;
border: 1px solid var(--panel-edge);
border-radius: 15px;
background: rgba(7, 16, 29, 0.68);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(16px);
}
.stat {
min-width: 112px;
padding: 7px 11px;
border-right: 1px solid rgba(255, 255, 255, 0.08);
}
.stat:last-child {
border-right: 0;
}
.stat-label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat-value {
font-size: 17px;
font-weight: 720;
letter-spacing: -0.02em;
white-space: nowrap;
}
.stat-value.locked::after {
content: " · locked";
color: var(--mint);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--panel-edge);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 65px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(20px) saturate(125%);
}
#left-panel {
top: 98px;
left: 18px;
width: 278px;
max-height: calc(100vh - 154px);
padding: 18px;
overflow: auto;
}
#right-panel {
top: 98px;
right: 18px;
width: 302px;
max-height: calc(100vh - 154px);
padding: 18px;
overflow: auto;
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h2 {
margin: 0;
font-size: 20px;
line-height: 1.2;
letter-spacing: -0.025em;
}
.intro {
margin: 10px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section-title {
margin: 18px 0 9px;
color: #cfe0f0;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.legend {
padding: 11px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.legend-head {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 8px;
font-size: 11px;
font-weight: 700;
}
.legend-head span:last-child {
color: var(--muted);
font-weight: 500;
}
.legend-gradient {
height: 9px;
border-radius: 999px;
background: linear-gradient(90deg, #285a86, #28b6a6, #f6b94b, #ff675a);
}
.legend-scale {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: var(--muted);
font-size: 9px;
}
.service-list {
display: grid;
gap: 7px;
}
.service-row {
display: grid;
grid-template-columns: 11px 1fr auto;
align-items: center;
gap: 9px;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.service-dot {
width: 9px;
height: 9px;
border-radius: 50%;
box-shadow: 0 0 12px currentColor;
}
.service-row strong {
display: block;
font-size: 11px;
}
.service-row small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.service-distance {
color: #dcecff;
font-size: 11px;
font-weight: 750;
text-align: right;
}
details {
margin-top: 16px;
padding: 11px;
border: 1px solid rgba(255, 200, 90, 0.18);
border-radius: 11px;
background: rgba(255, 200, 90, 0.045);
}
summary {
cursor: pointer;
color: #ffdb82;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
details p {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.field {
display: block;
margin-top: 13px;
color: #cfe0f0;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
select {
width: 100%;
margin-top: 7px;
padding: 10px 11px;
border: 1px solid rgba(157, 207, 255, 0.18);
border-radius: 10px;
outline: none;
background: #101e31;
color: var(--text);
font-size: 12px;
letter-spacing: 0;
text-transform: none;
}
select:focus,
button:focus-visible {
border-color: var(--cyan);
outline: 2px solid rgba(99, 220, 255, 0.2);
}
.selection-card {
margin-top: 14px;
padding: 13px;
border: 1px solid rgba(99, 220, 255, 0.16);
border-radius: 13px;
background: linear-gradient(135deg, rgba(99, 220, 255, 0.08), rgba(89, 224, 172, 0.02));
}
.selection-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 11px;
}
.selection-title strong {
font-size: 17px;
}
.selection-title span {
color: var(--mint);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
padding: 9px;
border-radius: 9px;
background: rgba(0, 0, 0, 0.16);
}
.metric small {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric b {
font-size: 12px;
font-weight: 720;
}
.route {
display: flex;
align-items: center;
gap: 9px;
margin-top: 10px;
padding: 10px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
color: var(--muted);
font-size: 11px;
}
.route strong {
color: var(--text);
}
.route .arrow {
color: var(--cyan);
}
.primary-button {
width: 100%;
margin-top: 11px;
padding: 11px 13px;
border: 0;
border-radius: 10px;
background: linear-gradient(135deg, #63dcff, #59e0ac);
color: #07101d;
cursor: pointer;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.02em;
transition: transform 120ms ease, filter 120ms ease;
}
.primary-button:hover:not(:disabled) {
transform: translateY(-1px);
filter: brightness(1.08);
}
.primary-button:disabled {
cursor: not-allowed;
opacity: 0.36;
}
.secondary-button {
padding: 8px 10px;
border: 1px solid rgba(157, 207, 255, 0.17);
border-radius: 9px;
background: rgba(255, 255, 255, 0.04);
color: #dcecff;
cursor: pointer;
font-size: 11px;
}
.secondary-button:hover {
background: rgba(255, 255, 255, 0.08);
}
.button-row {
display: flex;
gap: 7px;
margin-top: 9px;
}
.button-row button {
flex: 1;
}
.divider {
height: 1px;
margin: 17px 0 2px;
background: rgba(255, 255, 255, 0.08);
}
.tooltip {
position: fixed;
z-index: 10;
display: none;
min-width: 170px;
padding: 10px 12px;
border: 1px solid rgba(99, 220, 255, 0.3);
border-radius: 10px;
background: rgba(6, 14, 26, 0.94);
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.35);
pointer-events: none;
backdrop-filter: blur(12px);
}
.tooltip strong,
.tooltip span {
display: block;
}
.tooltip strong {
margin-bottom: 5px;
color: var(--cyan);
font-size: 11px;
letter-spacing: 0.07em;
}
.tooltip span {
margin-top: 3px;
color: #b9cadc;
font-size: 10px;
}
.toast {
position: fixed;
z-index: 12;
left: 50%;
bottom: 66px;
max-width: min(540px, calc(100vw - 28px));
padding: 11px 16px;
border: 1px solid rgba(89, 224, 172, 0.28);
border-radius: 999px;
background: rgba(7, 19, 29, 0.94);
color: #dffcef;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.34);
font-size: 11px;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition: opacity 180ms ease, transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.bottom-hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 17px;
padding: 8px 13px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
background: rgba(7, 16, 29, 0.7);
color: #9eb2c8;
font-size: 10px;
white-space: nowrap;
pointer-events: none;
transform: translateX(-50%);
backdrop-filter: blur(10px);
}
@media (max-width: 1120px) {
#left-panel {
width: 246px;
}
#right-panel {
width: 274px;
}
.stat {
min-width: 98px;
}
}
@media (max-width: 860px) {
.topbar {
align-items: flex-start;
}
.brand p {
max-width: 270px;
font-size: 9px;
}
.stats {
position: absolute;
top: 57px;
right: 0;
left: 0;
justify-content: stretch;
}
.stat {
flex: 1;
min-width: 0;
padding: 6px 8px;
}
.stat-value {
font-size: 14px;
}
#left-panel {
display: none;
}
#right-panel {
top: 126px;
right: 12px;
width: 270px;
max-height: calc(100vh - 190px);
}
}
@media (max-width: 590px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.brand h1 {
font-size: 18px;
}
.brand p {
max-width: 230px;
line-height: 1.35;
}
.stats {
top: 52px;
gap: 3px;
padding: 4px;
}
.stat {
padding: 5px 6px;
}
.stat-label {
font-size: 7px;
}
.stat-value {
font-size: 12px;
}
.stat:nth-child(2) {
display: none;
}
#right-panel {
top: auto;
right: 10px;
bottom: 58px;
left: 10px;
width: auto;
max-height: 45vh;
padding: 14px;
}
.bottom-hint {
right: 10px;
bottom: 10px;
left: 10px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.toast {
bottom: 52vh;
}
}
</style>
</head>
<body>
<main id="viewport" aria-label="Interactive low-poly population density grid"></main>
<header class="topbar">
<div class="brand">
<div class="logo" aria-hidden="true"></div>
<div>
<h1>Resident Grid</h1>
<p>Synthetic allocation · no behavioral forecast</p>
</div>
</div>
<div class="stats" aria-label="Allocation statistics">
<div class="stat">
<span class="stat-label">Residents</span>
<span class="stat-value locked" id="total-residents">—</span>
</div>
<div class="stat">
<span class="stat-label">Occupied cells</span>
<span class="stat-value" id="occupied-cells">—</span>
</div>
<div class="stat">
<span class="stat-label">Mean density</span>
<span class="stat-value" id="mean-density">—</span>
</div>
<div class="stat">
<span class="stat-label">Nearest service</span>
<span class="stat-value" id="mean-service">—</span>
</div>
</div>
</header>
<aside class="panel" id="left-panel">
<div class="eyebrow">Allocation map</div>
<h2>One grid. Constant population.</h2>
<p class="intro">
Drag a low-poly household to another fixed cell. Its full resident group
moves together, local density changes, and service access is recalculated.
</p>
<div class="section-title">Cell color</div>
<div class="legend">
<div class="legend-head">
<span id="legend-title">Residents per km²</span>
<span id="legend-subtitle">synthetic cells</span>
</div>
<div class="legend-gradient" id="legend-gradient"></div>
<div class="legend-scale">
<span id="legend-min">0</span>
<span id="legend-max">12 / km²</span>
</div>
</div>
<div class="section-title">Fixed services</div>
<div class="service-list" id="service-list"></div>
<details>
<summary>Model and limits</summary>
<p>
This is an illustrative allocation sandbox with fixed 1 km² cells.
Service distance uses Manhattan cell distance, with one cell edge set to
0.8 synthetic km. Moves are entirely user-directed. The scene does not
estimate migration, preferences, policy effects, or real-world movement.
</p>
</details>
</aside>
<aside class="panel" id="right-panel">
<div class="eyebrow">Map and selection</div>
<h2>Inspect and reassign</h2>
<label class="field" for="layer-select">Color cells by</label>
<select id="layer-select">
<option value="density">Local population density</option>
<option value="service">Nearest-service distance</option>
</select>
<div class="selection-card">
<div class="selection-title">
<strong id="selected-cell-code">—</strong>
<span>Fixed cell</span>
</div>
<div class="metric-grid">
<div class="metric">
<small>Residents</small>
<b id="selected-cell-residents">—</b>
</div>
<div class="metric">
<small>Density</small>
<b id="selected-cell-density">—</b>
</div>
<div class="metric">
<small>Nearest service</small>
<b id="selected-cell-service">—</b>
</div>
<div class="metric">
<small>Service distance</small>
<b id="selected-cell-distance">—</b>
</div>
</div>
</div>
<div class="divider"></div>
<label class="field" for="household-select">Household group</label>
<select id="household-select"></select>
<div class="route">
<span>From</span>
<strong id="source-cell">—</strong>
<span class="arrow">→</span>
<strong>destination</strong>
</div>
<label class="field" for="destination-select">Destination cell</label>
<select id="destination-select"></select>
<button class="primary-button" id="move-button" type="button">
Move selected group
</button>
<div class="button-row">
<button class="secondary-button" id="reset-allocation" type="button">
Reset allocation
</button>
<button class="secondary-button" id="reset-view" type="button">
Reset view
</button>
</div>
<div class="button-row">
<button class="secondary-button" id="zoom-in" type="button" aria-label="Zoom in">
Zoom +
</button>
<button class="secondary-button" id="zoom-out" type="button" aria-label="Zoom out">
Zoom −
</button>
</div>
</aside>
<div class="tooltip" id="tooltip" role="status"></div>
<div class="toast" id="toast" role="status"></div>
<div class="bottom-hint">
Drag a house to a cell · drag empty space to orbit · scroll to zoom
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const GRID_SIZE = 7;
const CELL_COUNT = GRID_SIZE * GRID_SIZE;
const CELL_SIZE = 1;
const SPACING = 1.08;
const AREA_KM2 = 1;
const KM_PER_CELL = 0.8;
const DENSITY_SCALE_MAX = 12;
const SERVICES = [
{ name: "School", code: "SCH", color: 0x54d6ff, cell: 10 },
{ name: "Clinic", code: "CLN", color: 0x62e6a7, cell: 38 },
{ name: "Market", code: "MKT", color: 0xffc857, cell: 24 }
];
const INITIAL_HOUSEHOLDS = [
{ id: "H-01", residents: 4, cell: 24 },
{ id: "H-02", residents: 6, cell: 23 },
{ id: "H-03", residents: 3, cell: 25 },
{ id: "H-04", residents: 5, cell: 17 },
{ id: "H-05", residents: 2, cell: 31 },
{ id: "H-06", residents: 7, cell: 32 },
{ id: "H-07", residents: 4, cell: 10 },
{ id: "H-08", residents: 3, cell: 11 },
{ id: "H-09", residents: 2, cell: 12 },
{ id: "H-10", residents: 6, cell: 3 },
{ id: "H-11", residents: 4, cell: 4 },
{ id: "H-12", residents: 5, cell: 39 },
{ id: "H-13", residents: 3, cell: 40 },
{ id: "H-14", residents: 2, cell: 46 },
{ id: "H-15", residents: 4, cell: 38 },
{ id: "H-16", residents: 3, cell: 31 },
{ id: "H-17", residents: 2, cell: 17 },
{ id: "H-18", residents: 5, cell: 24 }
];
const TOTAL_RESIDENTS = INITIAL_HOUSEHOLDS.reduce(
(sum, household) => sum + household.residents,
0
);
const elements = {
totalResidents: document.getElementById("total-residents"),
occupiedCells: document.getElementById("occupied-cells"),
meanDensity: document.getElementById("mean-density"),
meanService: document.getElementById("mean-service"),
legendTitle: document.getElementById("legend-title"),
legendSubtitle: document.getElementById("legend-subtitle"),
legendGradient: document.getElementById("legend-gradient"),
legendMin: document.getElementById("legend-min"),
legendMax: document.getElementById("legend-max"),
serviceList: document.getElementById("service-list"),
layerSelect: document.getElementById("layer-select"),
selectedCellCode: document.getElementById("selected-cell-code"),
selectedCellResidents: document.getElementById("selected-cell-residents"),
selectedCellDensity: document.getElementById("selected-cell-density"),
selectedCellService: document.getElementById("selected-cell-service"),
selectedCellDistance: document.getElementById("selected-cell-distance"),
householdSelect: document.getElementById("household-select"),
destinationSelect: document.getElementById("destination-select"),
sourceCell: document.getElementById("source-cell"),
moveButton: document.getElementById("move-button"),
resetAllocation: document.getElementById("reset-allocation"),
resetView: document.getElementById("reset-view"),
zoomIn: document.getElementById("zoom-in"),
zoomOut: document.getElementById("zoom-out"),
tooltip: document.getElementById("tooltip"),
toast: document.getElementById("toast")
};
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x091321, 17, 35);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc5e8ff, 0x182235, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.1);
sun.position.set(7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x58cfff, 1.35);
rim.position.set(-8, 5, -7);
scene.add(rim);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
new THREE.MeshStandardMaterial({
color: 0x08111e,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.29;
ground.receiveShadow = true;
scene.add(ground);
const boardSpan = GRID_SIZE * SPACING + 0.72;
const board = new THREE.Mesh(
new THREE.BoxGeometry(boardSpan, 0.24, boardSpan),
new THREE.MeshStandardMaterial({
color: 0x101d2d,
roughness: 0.82,
metalness: 0.08,
flatShading: true
})
);
board.position.y = -0.16;
board.receiveShadow = true;
scene.add(board);
const cells = [];
const cellMeshes = [];
const cellGeometry = new THREE.BoxGeometry(CELL_SIZE, 1, CELL_SIZE);
const cellEdgesGeometry = new THREE.EdgesGeometry(cellGeometry);
function rowAndColumn(index) {
return {
row: Math.floor(index / GRID_SIZE),
column: index % GRID_SIZE
};
}
function cellCode(index) {
const { row, column } = rowAndColumn(index);
return `R${row + 1}·C${column + 1}`;
}
function cellPosition(index) {
const { row, column } = rowAndColumn(index);
return {
x: (column - (GRID_SIZE - 1) / 2) * SPACING,
z: (row - (GRID_SIZE - 1) / 2) * SPACING
};
}
for (let index = 0; index < CELL_COUNT; index++) {
const { x, z } = cellPosition(index);
const root = new THREE.Group();
root.position.set(x, 0, z);
scene.add(root);
const material = new THREE.MeshStandardMaterial({
color: 0x20334a,
roughness: 0.72,
metalness: 0.04,
emissive: 0x07111d,
emissiveIntensity: 0.8,
flatShading: true
});
const mesh = new THREE.Mesh(cellGeometry, material);
mesh.scale.y = 0.08;
mesh.position.y = 0.04;
mesh.receiveShadow = true;
mesh.castShadow = true;
mesh.userData.cellIndex = index;
root.add(mesh);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x8bdcff,
transparent: true,
opacity: 0.16
});
const edges = new THREE.LineSegments(cellEdgesGeometry, edgeMaterial);
edges.scale.y = 0.08;
edges.position.y = 0.04;
root.add(edges);
cells.push({
index,
root,
mesh,
edges,
count: 0,
height: 0.08,
x,
z
});
cellMeshes.push(mesh);
}
function drawRoundedRect(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function makeBadge(text, foreground = "#eaf8ff", background = "rgba(5,15,28,0.92)") {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
drawRoundedRect(context, 6, 10, 244, 108, 30);
context.fillStyle = background;
context.fill();
context.strokeStyle = "rgba(255,255,255,0.14)";
context.lineWidth = 3;
context.stroke();
context.fillStyle = foreground;
context.font = "800 54px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
const serviceObjects = [];
for (const service of SERVICES) {
const position = cellPosition(service.cell);
const root = new THREE.Group();
root.position.set(position.x, 0, position.z);
scene.add(root);
const color = new THREE.Color(service.color);
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.035, 0.42, 6),
new THREE.MeshStandardMaterial({
color: 0xdff7ff,
roughness: 0.55,
metalness: 0.18,
flatShading: true
})
);
pole.position.y = 0.21;
pole.castShadow = true;
root.add(pole);
const icon = new THREE.Mesh(
new THREE.OctahedronGeometry(0.115, 0),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.5,
roughness: 0.42,
flatShading: true
})
);
icon.position.y = 0.49;
icon.castShadow = true;
root.add(icon);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.16, 0.018, 6, 24),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.84
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.018;
root.add(ring);
const label = makeBadge(
service.name.toUpperCase(),
`#${color.getHexString()}`,
"rgba(5,15,28,0.92)"
);
label.scale.set(0.72, 0.25, 1);
label.position.y = 0.72;
root.add(label);
serviceObjects.push({ service, root, icon });
}
const roofColors = [
0xff806d,
0xffc857,
0x62dcff,
0x62e6a7,
0xb990ff,
0xff9fc8
];
const houseGeometry = new THREE.BoxGeometry(0.17, 0.15, 0.15);
const roofGeometry = new THREE.ConeGeometry(0.14, 0.11, 4);
const baseGeometry = new THREE.CylinderGeometry(0.115, 0.135, 0.03, 6);
const ringGeometry = new THREE.RingGeometry(0.14, 0.17, 24);
const households = [];
const householdRoots = [];
INITIAL_HOUSEHOLDS.forEach((initial, index) => {
const household = {
...initial,
root: null
};
const root = new THREE.Group();
const base = new THREE.Mesh(
baseGeometry,
new THREE.MeshStandardMaterial({
color: 0x18273b,
roughness: 0.8,
flatShading: true
})
);
base.position.y = 0.015;
base.receiveShadow = true;
root.add(base);
const house = new THREE.Mesh(
houseGeometry,
new THREE.MeshStandardMaterial({
color: 0xf0e7d6,
roughness: 0.82,
metalness: 0.02,
flatShading: true
})
);
house.position.y = 0.105;
house.castShadow = true;
house.receiveShadow = true;
root.add(house);
const roof = new THREE.Mesh(
roofGeometry,
new THREE.MeshStandardMaterial({
color: roofColors[index % roofColors.length],
roughness: 0.64,
metalness: 0.04,
flatShading: true
})
);
roof.position.y = 0.235;
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
root.add(roof);
const badge = makeBadge(String(household.residents));
badge.scale.set(0.25, 0.125, 1);
badge.position.y = 0.405;
root.add(badge);
const selectionRing = new THREE.Mesh(
ringGeometry,
new THREE.MeshBasicMaterial({
color: 0x78e8ff,
transparent: true,
opacity: 0.95,
side: THREE.DoubleSide,
depthWrite: false
})
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.position.y = 0.008;
selectionRing.visible = false;
root.add(selectionRing);
root.userData.household = household;
root.userData.selectionRing = selectionRing;
household.root = root;
households.push(household);
householdRoots.push(root);
scene.add(root);
});
const cameraState = {
theta: 0.56,
phi: 0.82,
radius: 15.8,
target: new THREE.Vector3(0, 0.25, 0)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.theta = 0.56;
cameraState.phi = 0.82;
cameraState.radius = 15.8;
updateCamera();
}
function serviceDistance(service, cellIndex) {
const origin = rowAndColumn(cellIndex);
const target = rowAndColumn(service.cell);
const steps =
Math.abs(origin.row - target.row) +
Math.abs(origin.column - target.column);
return {
steps,
distance: steps * KM_PER_CELL
};
}
function nearestService(cellIndex) {
let nearest = null;
for (const service of SERVICES) {
const result = serviceDistance(service, cellIndex);
if (!nearest || result.distance < nearest.distance) {
nearest = { service, ...result };
}
}
return nearest;
}
const maximumNearestDistance = Math.max(
...cells.map((cell) => nearestService(cell.index).distance)
);
const densityLow = new THREE.Color(0x285a86);
const densityMiddle = new THREE.Color(0x28b6a6);
const densityHigh = new THREE.Color(0xf6b94b);
const densityMaximum = new THREE.Color(0xff675a);
const emptyColor = new THREE.Color(0x20334a);
const serviceLow = new THREE.Color(0x55deb2);
const serviceMiddle = new THREE.Color(0x4d9fe4);
const serviceHigh = new THREE.Color(0xa164e9);
const workingColor = new THREE.Color();
function densityColor(count, target) {
if (count <= 0) {
return target.copy(emptyColor);
}
const t = Math.min(count / DENSITY_SCALE_MAX, 1);
if (t < 0.45) {
target.lerpColors(densityLow, densityMiddle, t / 0.45);
} else if (t < 0.78) {
target.lerpColors(densityMiddle, densityHigh, (t - 0.45) / 0.33);
} else {
target.lerpColors(
densityHigh,
densityMaximum,
(t - 0.78) / 0.22
);
}
return target;
}
function serviceColor(distance, target) {
const t = maximumNearestDistance
? Math.min(distance / maximumNearestDistance, 1)
: 0;
if (t < 0.5) {
target.lerpColors(serviceLow, serviceMiddle, t / 0.5);
} else {
target.lerpColors(
serviceMiddle,
serviceHigh,
(t - 0.5) / 0.5
);
}
return target;
}
let currentLayer = "density";
let selectedCell = 24;
let hoverCell = null;
let selectedHousehold = households[0];
let residentCounts = new Array(CELL_COUNT).fill(0);
let dragState = null;
let orbitState = null;
let toastTimer = null;
const animations = [];
function heightForCount(count) {
return 0.08 + Math.min(count, DENSITY_SCALE_MAX) * 0.065;
}
function refreshCellStyles() {
for (const cell of cells) {
const isSelected = cell.index === selectedCell;
const isHovered = cell.index === hoverCell;
if (currentLayer === "density") {
densityColor(cell.count, workingColor);
} else {
serviceColor(nearestService(cell.index).distance, workingColor);
}
cell.mesh.material.color.copy(workingColor);
cell.mesh.material.emissive.copy(workingColor).multiplyScalar(0.11);
cell.edges.material.color.set(
isSelected ? 0xa5efff : isHovered ? 0x62dcff : 0x8bdcff
);
cell.edges.material.opacity = isSelected
? 0.95
: isHovered
? 0.72
: 0.16;
}
for (const household of households) {
household.root.userData.selectionRing.visible =
household === selectedHousehold;
}
}
const layoutSlots = [
[0, 0],
[-0.25, -0.23],
[0.25, -0.23],
[-0.25, 0.23],
[0.25, 0.23],
[0, -0.27],
[0, 0.27],
[-0.28, 0],
[0.28, 0]
];
function updateAll() {
residentCounts.fill(0);
for (const household of households) {
residentCounts[household.cell] += household.residents;
}
for (const cell of cells) {
cell.count = residentCounts[cell.index];
cell.height = heightForCount(cell.count);
cell.mesh.scale.y = cell.height;
cell.mesh.position.y = cell.height / 2;
cell.edges.scale.y = cell.height;
cell.edges.position.y = cell.height / 2;
}
for (const { service, root } of serviceObjects) {
root.position.y = cells[service.cell].height;
}
const householdsByCell = Array.from(
{ length: CELL_COUNT },
() => []
);
for (const household of households) {
householdsByCell[household.cell].push(household);
}
for (let index = 0; index < CELL_COUNT; index++) {
const cell = cells[index];
const assigned = householdsByCell[index];
const containsService = SERVICES.some((service) => service.cell === index);
assigned.forEach((household, order) => {
let slot;
if (containsService) {
slot = layoutSlots[(order + 1) % layoutSlots.length];
if (assigned.length === 1) slot = [-0.28, -0.27];
} else {
slot = layoutSlots[order % layoutSlots.length];
}
household.root.position.set(
cell.x + slot[0],
cell.height + 0.004,
cell.z + slot[1]
);
household.root.scale.setScalar(1);
});
}
syncHouseholdOptions();
refreshCellStyles();
updateUI();
}
function syncHouseholdOptions() {
elements.householdSelect.innerHTML = households
.map(
(household) =>
`<option value="${household.id}">${household.id} · ${household.residents} residents · ${cellCode(household.cell)}</option>`
)
.join("");
if (selectedHousehold) {
elements.householdSelect.value = selectedHousehold.id;
}
}
function firstNeighbor(index) {
const { row, column } = rowAndColumn(index);
const candidates = [
[row - 1, column],
[row + 1, column],
[row, column - 1],
[row, column + 1]
];
for (const [r, c] of candidates) {
if (r >= 0 && r < GRID_SIZE && c >= 0 && c < GRID_SIZE) {
return r * GRID_SIZE + c;
}
}
return index;
}
function updateUI() {
const occupied = residentCounts.filter((count) => count > 0).length;
const meanDensity = TOTAL_RESIDENTS / (CELL_COUNT * AREA_KM2);
let weightedNearestDistance = 0;
for (const household of households) {
weightedNearestDistance +=
household.residents * nearestService(household.cell).distance;
}
const meanNearestDistance = weightedNearestDistance / TOTAL_RESIDENTS;
elements.totalResidents.textContent = TOTAL_RESIDENTS.toLocaleString();
elements.occupiedCells.textContent = `${occupied}/${CELL_COUNT}`;
elements.meanDensity.textContent = `${meanDensity.toFixed(1)}/km²`;
elements.meanService.textContent = `${meanNearestDistance.toFixed(1)} km`;
const selected = cells[selectedCell];
const nearest = nearestService(selectedCell);
elements.selectedCellCode.textContent = cellCode(selectedCell);
elements.selectedCellResidents.textContent = `${selected.count} residents`;
elements.selectedCellDensity.textContent =
`${(selected.count / AREA_KM2).toFixed(1)} res/km²`;
elements.selectedCellService.textContent = nearest.service.name;
elements.selectedCellDistance.textContent =
`${nearest.distance.toFixed(1)} km`;
elements.serviceList.innerHTML = SERVICES.map((service) => {
const color = `#${new THREE.Color(service.color).getHexString()}`;
let weightedDistance = 0;
let withinTwoCells = 0;
for (const household of households) {
const distance = serviceDistance(service, household.cell);
weightedDistance += distance.distance * household.residents;
if (distance.steps <= 2) {
withinTwoCells += household.residents;
}
}
const average = weightedDistance / TOTAL_RESIDENTS;
return `
<div class="service-row">
<span class="service-dot" style="color:${color};background:${color}"></span>
<div>
<strong>${service.name}</strong>
<small>${withinTwoCells} residents within 2 cells</small>
</div>
<span class="service-distance">${average.toFixed(1)} km</span>
</div>
`;
}).join("");
const currentDestination = elements.destinationSelect.value;
elements.destinationSelect.innerHTML = cells
.map(
(cell) =>
`<option value="${cell.index}">${cellCode(cell.index)} · ${cell.count} residents</option>`
)
.join("");
let destination = Number(currentDestination);
if (
!Number.isInteger(destination) ||
(selectedHousehold && destination === selectedHousehold.cell)
) {
destination = firstNeighbor(selectedHousehold.cell);
}
elements.destinationSelect.value = String(destination);
if (selectedHousehold) {
elements.sourceCell.textContent = cellCode(selectedHousehold.cell);
elements.moveButton.disabled =
destination === selectedHousehold.cell;
} else {
elements.sourceCell.textContent = "—";
elements.moveButton.disabled = true;
}
if (currentLayer === "density") {
elements.legendTitle.textContent = "Residents per km²";
elements.legendSubtitle.textContent = "synthetic cells";
elements.legendGradient.style.background =
"linear-gradient(90deg, #285a86, #28b6a6, #f6b94b, #ff675a)";
elements.legendMin.textContent = "0";
elements.legendMax.textContent = `${DENSITY_SCALE_MAX} / km²`;
} else {
elements.legendTitle.textContent = "Nearest-service distance";
elements.legendSubtitle.textContent = "synthetic km";
elements.legendGradient.style.background =
"linear-gradient(90deg, #55deb2, #4d9fe4, #a164e9)";
elements.legendMin.textContent = "0 km";
elements.legendMax.textContent = `${maximumNearestDistance.toFixed(1)} km`;
}
}
function showToast(message) {
clearTimeout(toastTimer);
elements.toast.textContent = message;
elements.toast.classList.add("show");
toastTimer = setTimeout(() => {
elements.toast.classList.remove("show");
}, 2600);
}
function assignHousehold(household, destination, animate = true) {
if (!household || destination < 0 || destination >= CELL_COUNT) {
return;
}
const start = household.root.position.clone();
household.cell = destination;
selectedCell = destination;
selectedHousehold = household;
updateAll();
const end = household.root.position.clone();
if (animate && start.distanceTo(end) > 0.01) {
household.root.position.copy(start);
animations.push({
household,
start,
end,
started: performance.now(),
duration: 430
});
} else {
household.root.position.copy(end);
}
showToast(
`${household.id} assigned to ${cellCode(destination)}. ` +
`${household.residents} residents moved as one group; total remains ${TOTAL_RESIDENTS}.`
);
}
function selectHousehold(household) {
selectedHousehold = household;
selectedCell = household.cell;
elements.householdSelect.value = household.id;
refreshCellStyles();
updateUI();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.9);
const dragPoint = new THREE.Vector3();
function setPointerFromEvent(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);
}
function pickHousehold(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(householdRoots, true);
for (const hit of hits) {
let object = hit.object;
while (object && !object.userData.household) {
object = object.parent;
}
if (object?.userData.household) {
return object.userData.household;
}
}
return null;
}
function pickCell(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(cellMeshes, false);
return hits.length ? hits[0].object.userData.cellIndex : null;
}
function positionTooltip(event) {
const tooltip = elements.tooltip;
const left = Math.min(
event.clientX + 14,
window.innerWidth - tooltip.offsetWidth - 8
);
const top = Math.min(
event.clientY + 14,
window.innerHeight - tooltip.offsetHeight - 8
);
tooltip.style.left = `${Math.max(8, left)}px`;
tooltip.style.top = `${Math.max(8, top)}px`;
}
function showCellTooltip(index, event, draggingHousehold = null) {
const count = residentCounts[index];
const density = count / AREA_KM2;
const nearest = nearestService(index);
let extra = `${count} residents · ${density.toFixed(1)} res/km²`;
if (draggingHousehold) {
const projectedDensity =
(count + draggingHousehold.residents) / AREA_KM2;
extra =
`Drop here · ${projectedDensity.toFixed(1)} res/km² after move`;
}
elements.tooltip.innerHTML = `
<strong>${cellCode(index)}</strong>
<span>${extra}</span>
<span>${nearest.service.name} · ${nearest.distance.toFixed(1)} km</span>
`;
elements.tooltip.style.display = "block";
positionTooltip(event);
}
function hideTooltip() {
elements.tooltip.style.display = "none";
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
event.preventDefault();
const household = pickHousehold(event);
if (household) {
selectHousehold(household);
dragState = {
household,
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
moved: false,
hoverCell: household.cell
};
hoverCell = household.cell;
refreshCellStyles();
renderer.domElement.setPointerCapture(event.pointerId);
return;
}
const cell = pickCell(event);
if (cell !== null) {
selectedCell = cell;
hoverCell = cell;
refreshCellStyles();
updateUI();
}
orbitState = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragState && event.pointerId === dragState.pointerId) {
const movement = Math.hypot(
event.clientX - dragState.startX,
event.clientY - dragState.startY
);
if (movement > 4) dragState.moved = true;
setPointerFromEvent(event);
const cell = pickCell(event);
dragState.hoverCell = cell;
if (cell !== null) {
hoverCell = cell;
refreshCellStyles();
showCellTooltip(cell, event, dragState.household);
} else {
hoverCell = null;
refreshCellStyles();
hideTooltip();
}
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
dragState.household.root.position.set(
dragPoint.x,
0.92,
dragPoint.z
);
dragState.household.root.scale.setScalar(1.12);
}
return;
}
if (orbitState && event.pointerId === orbitState.pointerId) {
const dx = event.clientX - orbitState.x;
const dy = event.clientY - orbitState.y;
orbitState.x = event.clientX;
orbitState.y = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.34,
1.36
);
updateCamera();
return;
}
const cell = pickCell(event);
if (cell !== null) {
if (hoverCell !== cell) {
hoverCell = cell;
refreshCellStyles();
}
showCellTooltip(cell, event);
} else {
hoverCell = null;
refreshCellStyles();
hideTooltip();
}
});
function finishPointer(event) {
if (dragState && event.pointerId === dragState.pointerId) {
const finishedDrag = dragState;
dragState = null;
finishedDrag.household.root.scale.setScalar(1);
hoverCell = null;
if (
finishedDrag.hoverCell !== null &&
finishedDrag.hoverCell !== finishedDrag.household.cell
) {
assignHousehold(
finishedDrag.household,
finishedDrag.hoverCell,
true
);
} else {
updateAll();
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
hideTooltip();
return;
}
if (orbitState && event.pointerId === orbitState.pointerId) {
orbitState = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", finishPointer);
renderer.domElement.addEventListener("pointercancel", finishPointer);
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragState && !orbitState) {
hoverCell = null;
refreshCellStyles();
hideTooltip();
}
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
9.5,
25
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
elements.householdSelect.addEventListener("change", (event) => {
const household = households.find(
(entry) => entry.id === event.target.value
);
if (household) selectHousehold(household);
});
elements.destinationSelect.addEventListener("change", updateUI);
elements.moveButton.addEventListener("click", () => {
const destination = Number(elements.destinationSelect.value);
assignHousehold(selectedHousehold, destination, true);
});
elements.layerSelect.addEventListener("change", (event) => {
currentLayer = event.target.value;
refreshCellStyles();
updateUI();
});
elements.resetAllocation.addEventListener("click", () => {
households.forEach((household, index) => {
household.cell = INITIAL_HOUSEHOLDS[index].cell;
});
animations.length = 0;
selectedHousehold = households[0];
selectedCell = households[0].cell;
hoverCell = null;
updateAll();
showToast(
`Allocation reset. Total residents remain locked at ${TOTAL_RESIDENTS}.`
);
});
elements.resetView.addEventListener("click", resetCamera);
elements.zoomIn.addEventListener("click", () => {
cameraState.radius = Math.max(9.5, cameraState.radius - 1.25);
updateCamera();
});
elements.zoomOut.addEventListener("click", () => {
cameraState.radius = Math.min(25, cameraState.radius + 1.25);
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
function animate(now) {
requestAnimationFrame(animate);
for (let index = animations.length - 1; index >= 0; index--) {
const animation = animations[index];
const t = Math.min(
(now - animation.started) / animation.duration,
1
);
const eased = 1 - Math.pow(1 - t, 3);
animation.household.root.position.lerpVectors(
animation.start,
animation.end,
eased
);
animation.household.root.position.y +=
Math.sin(Math.PI * t) * 0.24;
if (t >= 1) {
animation.household.root.position.copy(animation.end);
animations.splice(index, 1);
}
}
for (const service of serviceObjects) {
service.icon.rotation.y += 0.006;
service.icon.rotation.x += 0.002;
}
renderer.render(scene, camera);
}
updateCamera();
updateAll();
requestAnimationFrame(animate);
</script>
</body>
</html>
```