Prompt specification
Build or customize the Three.js 3D scene "Neighborhood repair-resource network" 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: Neighborhood repair-resource network
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/neighborhood-repair-resource-network-x0532
Scene Description Prompt:
Neighborhood repair-resource network. Create several small repair stations sharing a parts library; users transfer compatible components and track restored objects while finite spare-part inventory updates after every repair. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (neighborhood-repair-resource-network-x0532):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Neighborly Works — Repair Resource Network</title>
<style>
:root {
--ink: #23302c;
--muted: #728078;
--paper: #f7f4ec;
--panel: rgba(255, 253, 247, 0.93);
--line: rgba(35, 48, 44, 0.11);
--green: #326b58;
--green-dark: #244f40;
--orange: #e36c45;
--shadow: 0 18px 45px rgba(42, 51, 45, 0.13);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
background: #ece9df;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.topbar {
position: fixed;
z-index: 20;
top: 0;
left: 0;
right: 0;
height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid rgba(35, 48, 44, 0.09);
background: rgba(249, 247, 240, 0.88);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 235px;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
border-radius: 12px;
background: var(--green);
box-shadow: inset 0 -6px 0 rgba(0,0,0,.08);
}
.brand-mark::before {
content: "";
position: absolute;
width: 17px;
height: 8px;
left: 10px;
top: 14px;
border-radius: 8px;
background: #f8e6b4;
transform: rotate(-35deg);
}
.brand-mark::after {
content: "";
position: absolute;
width: 10px;
height: 10px;
left: 8px;
top: 9px;
border: 4px solid #f8e6b4;
border-right-color: transparent;
border-radius: 50%;
transform: rotate(22deg);
}
.brand-name {
font-size: 15px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.brand-sub {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
letter-spacing: .025em;
}
.header-stats {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.header-stat {
min-width: 112px;
padding: 8px 15px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,.45);
}
.header-stat strong {
display: block;
font-size: 17px;
line-height: 1.1;
}
.header-stat span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: .08em;
text-transform: uppercase;
}
.header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.icon-button,
.mobile-button {
height: 38px;
border: 1px solid var(--line);
border-radius: 11px;
padding: 0 13px;
color: var(--ink);
background: rgba(255,255,255,.62);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: .2s ease;
}
.icon-button:hover,
.mobile-button:hover {
background: white;
transform: translateY(-1px);
}
.mobile-button { display: none; }
.panel {
position: fixed;
z-index: 12;
top: 86px;
bottom: 18px;
width: 310px;
overflow: auto;
padding: 18px;
border: 1px solid rgba(255,255,255,.78);
border-radius: 19px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: #c9cec6 transparent;
}
#leftPanel { left: 18px; }
#rightPanel { right: 18px; width: 330px; }
.panel::-webkit-scrollbar { width: 5px; }
.panel::-webkit-scrollbar-thumb {
border-radius: 5px;
background: #c9cec6;
}
.section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.eyebrow {
color: var(--orange);
font-size: 10px;
font-weight: 850;
letter-spacing: .14em;
text-transform: uppercase;
}
h2 {
margin: 4px 0 0;
font-size: 18px;
letter-spacing: -.025em;
}
h3 {
margin: 0;
font-size: 13px;
}
.small-copy {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.count-pill {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 25px;
height: 25px;
padding: 0 8px;
border-radius: 999px;
background: #e9eee8;
color: var(--green-dark);
font-size: 11px;
font-weight: 800;
}
.station-list {
display: grid;
gap: 8px;
}
.station-card {
position: relative;
width: 100%;
display: grid;
grid-template-columns: 10px 1fr auto;
align-items: center;
gap: 11px;
padding: 12px;
text-align: left;
border: 1px solid var(--line);
border-radius: 13px;
color: var(--ink);
background: rgba(255,255,255,.56);
cursor: pointer;
transition: .2s ease;
}
.station-card:hover {
border-color: rgba(50,107,88,.35);
transform: translateY(-1px);
}
.station-card.active {
border-color: var(--green);
background: #f0f6f1;
box-shadow: inset 0 0 0 1px rgba(50,107,88,.12);
}
.station-dot {
width: 9px;
height: 9px;
border-radius: 50%;
box-shadow: 0 0 0 4px rgba(0,0,0,.035);
}
.station-name {
font-size: 12px;
font-weight: 800;
}
.station-status {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.station-number {
color: #a0a8a1;
font-size: 10px;
font-weight: 800;
}
.divider {
height: 1px;
margin: 17px 0;
background: var(--line);
}
.detail-card {
padding: 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.55);
}
.detail-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.detail-title {
font-size: 13px;
font-weight: 850;
}
.capacity {
color: var(--muted);
font-size: 10px;
font-weight: 750;
}
.job-list {
display: grid;
gap: 6px;
margin: 12px 0;
}
.job-row {
width: 100%;
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
align-items: center;
padding: 9px 10px;
border: 1px solid transparent;
border-radius: 10px;
background: #f3f2ec;
text-align: left;
color: var(--ink);
cursor: pointer;
}
.job-row:hover { border-color: #b9c8be; }
.job-object {
font-size: 11px;
font-weight: 800;
}
.job-part {
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.job-state {
padding: 4px 7px;
border-radius: 999px;
background: white;
color: var(--green);
font-size: 9px;
font-weight: 800;
white-space: nowrap;
}
.job-state.transit { color: #b06a28; }
.job-state.repairing { color: #7459a7; }
.job-state.restored { color: var(--green); }
.primary-button {
width: 100%;
min-height: 39px;
border: 0;
border-radius: 11px;
padding: 9px 13px;
color: white;
background: var(--green);
box-shadow: 0 8px 18px rgba(50,107,88,.17);
cursor: pointer;
font-size: 11px;
font-weight: 850;
transition: .2s ease;
}
.primary-button:hover:not(:disabled) {
background: var(--green-dark);
transform: translateY(-1px);
}
.primary-button:disabled {
color: #8f9892;
background: #dfe3dd;
box-shadow: none;
cursor: not-allowed;
}
.transfer-meta {
min-height: 30px;
margin: 9px 1px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.inventory-list {
display: grid;
gap: 8px;
}
.part-row {
position: relative;
width: 100%;
overflow: hidden;
display: grid;
grid-template-columns: 34px 1fr auto;
align-items: center;
gap: 10px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.58);
color: var(--ink);
text-align: left;
cursor: pointer;
transition: .2s ease;
}
.part-row:hover { transform: translateY(-1px); }
.part-row.selected {
border-color: var(--part-color);
background: color-mix(in srgb, var(--part-color) 11%, white);
}
.part-icon {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border-radius: 10px;
color: white;
background: var(--part-color);
font-size: 11px;
font-weight: 900;
letter-spacing: .02em;
}
.part-name {
font-size: 11px;
font-weight: 850;
}
.part-meta {
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.part-quantity {
min-width: 31px;
height: 31px;
display: grid;
place-items: center;
border-radius: 9px;
background: #ecefe9;
font-size: 13px;
font-weight: 900;
}
.stock-track {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 3px;
background: rgba(0,0,0,.04);
}
.stock-fill {
height: 100%;
background: var(--part-color);
transition: width .4s ease;
}
.library-note {
display: flex;
align-items: center;
gap: 8px;
margin-top: 11px;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
.library-note::before {
content: "";
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--orange);
}
.restored-list,
.activity-list {
display: grid;
gap: 7px;
}
.restored-item {
display: grid;
grid-template-columns: 31px 1fr auto;
align-items: center;
gap: 9px;
padding: 9px;
border-radius: 11px;
background: rgba(255,255,255,.56);
border: 1px solid var(--line);
}
.restored-check {
width: 31px;
height: 31px;
display: grid;
place-items: center;
border-radius: 9px;
color: var(--green);
background: #e3eee7;
font-size: 14px;
font-weight: 900;
}
.restored-name {
font-size: 10px;
font-weight: 850;
}
.restored-place {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.restored-time {
color: #9ba39d;
font-size: 8px;
}
.activity-item {
display: grid;
grid-template-columns: 7px 1fr;
gap: 9px;
align-items: start;
padding: 4px 0;
color: #647169;
font-size: 9px;
line-height: 1.45;
}
.activity-dot {
width: 7px;
height: 7px;
margin-top: 3px;
border-radius: 50%;
background: #8eb09f;
}
.empty-state {
padding: 16px 8px;
color: var(--muted);
text-align: center;
font-size: 10px;
line-height: 1.5;
}
#labels {
position: fixed;
inset: 0;
z-index: 7;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
min-width: 120px;
padding: 7px 10px;
border: 1px solid rgba(255,255,255,.9);
border-radius: 10px;
background: rgba(255,253,247,.9);
box-shadow: 0 7px 20px rgba(32,48,40,.13);
backdrop-filter: blur(10px);
pointer-events: auto;
cursor: pointer;
transform: translate(-50%, -100%);
transition: opacity .15s ease;
}
.world-label.selected {
border-color: var(--green);
box-shadow: 0 8px 24px rgba(50,107,88,.18);
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -6px;
width: 10px;
height: 10px;
background: inherit;
border-right: inherit;
border-bottom: inherit;
transform: translateX(-50%) rotate(45deg);
}
.label-name {
font-size: 9px;
font-weight: 850;
white-space: nowrap;
}
.label-status {
display: flex;
align-items: center;
gap: 5px;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
.label-status::before {
content: "";
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--label-color, var(--green));
}
.world-label.library {
pointer-events: none;
background: rgba(35,66,55,.9);
color: white;
border-color: rgba(255,255,255,.2);
}
.world-label.library .label-status { color: #cddbd4; }
.scene-hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
border: 1px solid rgba(255,255,255,.75);
border-radius: 999px;
background: rgba(255,253,247,.75);
color: #65716a;
box-shadow: 0 8px 25px rgba(35,48,44,.09);
backdrop-filter: blur(10px);
font-size: 9px;
pointer-events: none;
white-space: nowrap;
}
.scene-hint b {
color: var(--ink);
font-weight: 800;
}
.toast {
position: fixed;
z-index: 40;
left: 50%;
top: 86px;
max-width: min(430px, calc(100vw - 32px));
transform: translate(-50%, -12px);
padding: 11px 16px;
border-radius: 12px;
color: white;
background: rgba(35,48,44,.94);
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transition: .25s ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 1050px) {
.header-stat { min-width: 92px; padding-inline: 10px; }
.panel { width: 285px; }
#rightPanel { width: 300px; }
}
@media (max-width: 820px) {
.topbar { height: 66px; padding: 0 12px; }
.brand { min-width: auto; }
.brand-sub { display: none; }
.header-stats { display: none; }
.mobile-button { display: block; }
.icon-button { padding-inline: 10px; }
.panel {
top: 78px;
bottom: 12px;
left: 12px;
right: auto;
width: min(340px, calc(100vw - 24px));
display: none;
}
#rightPanel {
left: auto;
right: 12px;
width: min(350px, calc(100vw - 24px));
}
.panel.mobile-open { display: block; }
.scene-hint { display: none; }
.world-label { transform: translate(-50%, -100%) scale(.9); }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D neighborhood repair network"></canvas>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<div class="brand-name">Neighborly Works</div>
<div class="brand-sub">Shared repair-resource network</div>
</div>
</div>
<div class="header-stats">
<div class="header-stat">
<strong id="statStations">4</strong>
<span>Stations</span>
</div>
<div class="header-stat">
<strong id="statTransfers">0</strong>
<span>In transit</span>
</div>
<div class="header-stat">
<strong id="statStock">20</strong>
<span>Parts left</span>
</div>
<div class="header-stat">
<strong id="statRestored">0</strong>
<span>Restored</span>
</div>
</div>
<div class="header-actions">
<button class="mobile-button" id="toggleLeft">Stations</button>
<button class="mobile-button" id="toggleRight">Library</button>
<button class="icon-button" id="resetView">Overview</button>
</div>
</header>
<aside class="panel" id="leftPanel">
<div class="section-head">
<div>
<div class="eyebrow">Local network</div>
<h2>Repair stations</h2>
<p class="small-copy">Select a station, then transfer a compatible part from the shared library.</p>
</div>
<span class="count-pill" id="stationCount">4</span>
</div>
<div class="station-list" id="stationList"></div>
<div class="divider"></div>
<div class="section-head">
<div>
<div class="eyebrow">Selected station</div>
<h2 id="detailHeading">Station details</h2>
</div>
</div>
<div id="stationDetail"></div>
</aside>
<aside class="panel" id="rightPanel">
<div class="section-head">
<div>
<div class="eyebrow">Finite inventory</div>
<h2>Shared parts library</h2>
<p class="small-copy">Every transfer uses one shared spare. Counts decrease when a repair is completed.</p>
</div>
<span class="count-pill" id="totalParts">20</span>
</div>
<div class="inventory-list" id="inventoryList"></div>
<div class="library-note">All four stations draw from the same neighborhood inventory.</div>
<div class="divider"></div>
<div class="section-head">
<div>
<div class="eyebrow">Completed work</div>
<h2>Restored objects</h2>
</div>
<span class="count-pill" id="restoredCount">0</span>
</div>
<div class="restored-list" id="restoredList"></div>
<div class="divider"></div>
<div class="section-head">
<div>
<div class="eyebrow">Network log</div>
<h2>Recent activity</h2>
</div>
</div>
<div class="activity-list" id="activityList"></div>
</aside>
<div class="scene-hint">
<span><b>Drag</b> orbit</span>
<span>·</span>
<span><b>Right-drag</b> pan</span>
<span>·</span>
<span><b>Scroll</b> zoom</span>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Application data
// ------------------------------------------------------------
const partDefinitions = {
"cable-kit": {
name: "Cable kit",
code: "CK",
color: "#e29a46",
compatible: ["Reading lamp", "Field radio", "Bicycle bell"]
},
"valve-kit": {
name: "Valve kit",
code: "VK",
color: "#5b91a8",
compatible: ["Brass faucet", "Bike pump"]
},
"motor": {
name: "Brush motor",
code: "BM",
color: "#9b78b4",
compatible: ["Cordless drill", "Desk fan"]
},
"sensor": {
name: "Sensor board",
code: "SB",
color: "#4f9a77",
compatible: ["Inkjet printer"]
}
};
const inventory = {
"cable-kit": { total: 8, initial: 8, reserved: 0 },
"valve-kit": { total: 5, initial: 5, reserved: 0 },
"motor": { total: 4, initial: 4, reserved: 0 },
"sensor": { total: 3, initial: 3, reserved: 0 }
};
const stations = [
{
id: "corner",
name: "Corner Mender",
color: "#e16f4b",
position: new THREE.Vector3(-5.4, 0, 1.7),
restoredCount: 0,
activeJob: null,
jobs: [
{
id: "job-lamp",
object: "Reading lamp",
type: "lamp",
required: "cable-kit",
owner: "Maya R.",
status: "pending",
progress: 0
},
{
id: "job-tap",
object: "Brass faucet",
type: "tap",
required: "valve-kit",
owner: "Jon B.",
status: "pending",
progress: 0
}
]
},
{
id: "makers",
name: "Maker Bench",
color: "#d5a33d",
position: new THREE.Vector3(5.4, 0, 1.7),
restoredCount: 0,
activeJob: null,
jobs: [
{
id: "job-drill",
object: "Cordless drill",
type: "drill",
required: "motor",
owner: "Priya S.",
status: "pending",
progress: 0
},
{
id: "job-fan",
object: "Desk fan",
type: "fan",
required: "motor",
owner: "Leo M.",
status: "pending",
progress: 0
}
]
},
{
id: "bike",
name: "Bike & Yard",
color: "#4f9374",
position: new THREE.Vector3(-5.4, 0, -5.0),
restoredCount: 0,
activeJob: null,
jobs: [
{
id: "job-pump",
object: "Bike pump",
type: "pump",
required: "valve-kit",
owner: "Ari K.",
status: "pending",
progress: 0
},
{
id: "job-bell",
object: "Bicycle bell",
type: "bell",
required: "cable-kit",
owner: "Sam T.",
status: "pending",
progress: 0
}
]
},
{
id: "annex",
name: "Library Annex",
color: "#668ca7",
position: new THREE.Vector3(5.4, 0, -5.0),
restoredCount: 0,
activeJob: null,
jobs: [
{
id: "job-radio",
object: "Field radio",
type: "radio",
required: "cable-kit",
owner: "Nora D.",
status: "pending",
progress: 0
},
{
id: "job-printer",
object: "Inkjet printer",
type: "printer",
required: "sensor",
owner: "Owen P.",
status: "pending",
progress: 0
}
]
}
];
let selectedStationId = "corner";
let selectedPartId = "cable-kit";
let uiDirty = true;
let toastTimer;
const restoredObjects = [];
const activity = [
{ text: "Shared library opened for the neighborhood.", time: "Now" },
{ text: "Four repair stations joined the network.", time: "Now" }
];
// ------------------------------------------------------------
// Three.js renderer and scene
// ------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeae0);
scene.fog = new THREE.Fog(0xeeeae0, 22, 39);
const camera = new THREE.PerspectiveCamera(
37,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xfff8df, 0x8da298, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d4, 3.4);
sun.position.set(-8, 15, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0004;
scene.add(sun);
const standard = (color, options = {}) => new THREE.MeshStandardMaterial({
color,
roughness: 0.83,
metalness: 0.02,
flatShading: true,
...options
});
const materials = {
ground: standard(0xdfe1cd),
road: standard(0xb9bbb2),
roadEdge: standard(0xd5d3c7),
cream: standard(0xf0dfbd),
creamLight: standard(0xf5ead1),
dark: standard(0x34423e),
wood: standard(0xa97950),
woodLight: standard(0xc59868),
green: standard(0x537b61),
greenLight: standard(0x779b6f),
leaf: standard(0x67845b),
leafLight: standard(0x87a66c),
white: standard(0xf8f3e8),
blue: standard(0x547d91),
orange: standard(0xd66b46)
};
function addBox(parent, width, height, depth, material, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(parent, radiusTop, radiusBottom, height, segments, material, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCone(parent, radius, height, segments, material, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, segments),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addLowPolySphere(parent, radius, material, x, y, z, widthSegments = 8, heightSegments = 6) {
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(radius, widthSegments, heightSegments),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
parent.add(mesh);
return mesh;
}
// Ground, paths, plaza and road markings.
addBox(scene, 21, .32, 17, materials.ground, 0, -.2, 0);
addBox(scene, 20.5, .04, 3.2, materials.road, 0, -.015, 0);
addBox(scene, 3.2, .04, 16.5, materials.road, 0, -.01, 0);
const plaza = new THREE.Mesh(
new THREE.CylinderGeometry(2.7, 2.7, .08, 20),
materials.roadEdge
);
plaza.position.set(0, .015, -.15);
plaza.receiveShadow = true;
scene.add(plaza);
for (let x = -8; x <= 8; x += 2) {
addBox(scene, .7, .015, .08, materials.white, x, .025, 0);
}
for (let z = -7; z <= 7; z += 2) {
if (Math.abs(z) < 1) continue;
addBox(scene, .08, .015, .65, materials.white, 0, .03, z);
}
// Shared library building.
const library = new THREE.Group();
library.position.set(0, 0, -3.05);
scene.add(library);
addBox(library, 3.4, 2.25, 2.65, materials.blue, 0, 1.13, 0);
addBox(library, 3.75, .18, 2.95, materials.creamLight, 0, 2.32, 0);
addBox(library, 1.05, 1.55, .09, materials.dark, -.55, .8, 1.36);
addBox(library, 1.05, 1.55, .09, materials.dark, .55, .8, 1.36);
addBox(library, 1.45, .75, .08, materials.creamLight, 0, 1.55, 1.39);
addBox(library, 3.7, .18, 1.0, materials.orange, 0, 1.73, 1.68);
addBox(library, 3.7, .35, .10, materials.cream, 0, 1.5, 2.12);
addBox(library, .16, .95, .16, materials.wood, 0, 2.75, 0);
addBox(library, 1.3, .55, .08, materials.cream, .48, 2.85, .03);
// Library rack and color-coded bins.
const rackGroup = new THREE.Group();
rackGroup.position.set(0, 0, -1.22);
scene.add(rackGroup);
addBox(rackGroup, 3.35, .12, .75, materials.wood, 0, .12, 0);
addBox(rackGroup, 3.35, .12, .75, materials.wood, 0, 1.05, 0);
addBox(rackGroup, .12, 1.1, .72, materials.wood, -1.65, .56, 0);
addBox(rackGroup, .12, 1.1, .72, materials.wood, 1.65, .56, 0);
addBox(rackGroup, .12, 1.1, .72, materials.wood, -.55, .56, 0);
addBox(rackGroup, .12, 1.1, .72, materials.wood, .55, .56, 0);
addBox(rackGroup, .12, 1.1, .72, materials.wood, 1.1, .56, 0);
function rebuildLibraryCrates() {
rackGroup.clear();
const partIds = Object.keys(partDefinitions);
partIds.forEach((partId, partIndex) => {
const definition = partDefinitions[partId];
const stock = inventory[partId];
const visibleCubes = Math.max(0, Math.ceil(stock.total / stock.initial * 4));
const x = -1.1 + partIndex * .73;
for (let i = 0; i < visibleCubes; i++) {
const cube = addBox(
rackGroup,
.44,
.26,
.43,
standard(definition.color),
x,
.28 + i * .24,
.02
);
cube.rotation.y = (i % 2) * .08;
}
});
}
rebuildLibraryCrates();
// Trees and small neighborhood details.
function createTree(x, z, scale = 1, alternate = false) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
scene.add(tree);
addCylinder(tree, .12, .18, 1.4, 6, materials.wood, 0, .7, 0);
addCone(tree, .85, 1.8, 7, alternate ? materials.leafLight : materials.leaf, 0, 2.0, 0);
addCone(tree, .58, 1.35, 6, alternate ? materials.greenLight : materials.greenLight, 0, 2.65, -.05);
const ring = new THREE.Mesh(
new THREE.CylinderGeometry(.55, .65, .08, 8),
materials.roadEdge
);
ring.position.y = .03;
ring.receiveShadow = true;
tree.add(ring);
}
createTree(-8.7, 6.8, 1.05);
createTree(8.6, 6.9, .92, true);
createTree(-8.8, -6.9, .88, true);
createTree(8.8, -6.8, 1.08);
createTree(2.5, 6.9, .75);
createTree(-2.5, 6.8, .82, true);
function createBench(parent, x, z, rotation = 0) {
const bench = new THREE.Group();
bench.position.set(x, 0, z);
bench.rotation.y = rotation;
parent.add(bench);
addBox(bench, 1.35, .12, .42, materials.woodLight, 0, .48, 0);
addBox(bench, 1.35, .42, .09, materials.woodLight, 0, .73, -.17);
addBox(bench, .12, .45, .12, materials.dark, -.48, .23, 0);
addBox(bench, .12, .45, .12, materials.dark, .48, .23, 0);
return bench;
}
// ------------------------------------------------------------
// People and station models
// ------------------------------------------------------------
function createPerson(color, withBackpack = false) {
const person = new THREE.Group();
const shirt = standard(color);
const skin = standard(0xc88f68);
const trousers = standard(0x34424a);
addCylinder(person, .17, .22, .46, 6, shirt, 0, .55, 0);
addLowPolySphere(person, .18, skin, 0, .96, 0, 8, 6);
const leftLeg = addBox(person, .12, .38, .14, trousers, -.11, .19, 0);
const rightLeg = addBox(person, .12, .38, .14, trousers, .11, .19, 0);
addBox(person, .11, .36, .12, shirt, -.25, .55, 0);
addBox(person, .11, .36, .12, shirt, .25, .55, 0);
const hair = addLowPolySphere(person, .18, standard(0x493b32), 0, 1.04, -.015, 8, 5);
hair.scale.y = .55;
if (withBackpack) {
addBox(person, .30, .38, .14, standard(0xd99b4e), 0, .60, -.19);
}
person.userData.leftLeg = leftLeg;
person.userData.rightLeg = rightLeg;
return person;
}
function createStation(station) {
const group = new THREE.Group();
group.position.copy(station.position);
group.rotation.y = Math.atan2(
-station.position.x,
-station.position.z
);
scene.add(group);
const stationMaterial = standard(station.color);
const localRoofMaterial = standard(new THREE.Color(station.color).multiplyScalar(.72));
addCylinder(group, 1.78, 1.92, .12, 12, materials.roadEdge, 0, .02, .15);
addBox(group, 2.55, 1.65, 2.05, materials.cream, 0, .88, 0);
addBox(group, 2.73, .12, 2.18, stationMaterial, 0, 1.75, 0);
const roof = addCone(group, 1.92, .92, 4, localRoofMaterial, 0, 2.22, 0);
roof.rotation.y = Math.PI / 4;
roof.scale.z = .82;
addBox(group, .78, 1.18, .10, materials.dark, -.54, .65, 1.07);
addBox(group, .70, .61, .08, materials.creamLight, .62, 1.02, 1.08);
addBox(group, .055, .64, .10, materials.wood, .62, 1.02, 1.13);
addBox(group, 2.85, .14, .72, stationMaterial, 0, 1.27, 1.33);
addBox(group, 2.85, .30, .09, materials.creamLight, 0, 1.08, 1.64);
createBench(group, -1.7, 1.0, .12);
const waitingUser = createPerson(station.color);
waitingUser.scale.setScalar(.86);
waitingUser.position.set(1.18, .05, 1.7);
waitingUser.rotation.y = -.5;
group.add(waitingUser);
const secondUser = createPerson(0xc99161);
secondUser.scale.setScalar(.78);
secondUser.position.set(1.72, .05, 1.22);
secondUser.rotation.y = -1.2;
group.add(secondUser);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.83, .035, 6, 48),
new THREE.MeshBasicMaterial({ color: station.color })
);
ring.rotation.x = Math.PI / 2;
ring.position.set(0, .095, .15);
group.add(ring);
station.group = group;
station.ring = ring;
station.benchPosition = new THREE.Vector3(-1.7, .56, 1.05);
}
stations.forEach(createStation);
// ------------------------------------------------------------
// Restored-object miniatures
// ------------------------------------------------------------
function createRestoredModel(type, color) {
const group = new THREE.Group();
const accent = standard(color);
if (type === "lamp") {
addCylinder(group, .23, .27, .09, 8, materials.dark, 0, .05, 0);
addCylinder(group, .025, .025, .42, 6, materials.dark, 0, .3, 0);
addCone(group, .25, .22, 8, accent, 0, .58, 0);
} else if (type === "tap") {
addCylinder(group, .06, .06, .48, 8, materials.woodLight, 0, .25, 0);
const spout = addCylinder(group, .055, .055, .42, 8, materials.woodLight, .16, .47, 0);
spout.rotation.z = Math.PI / 2;
addBox(group, .35, .07, .08, materials.woodLight, 0, .09, 0);
} else if (type === "drill") {
addBox(group, .55, .20, .18, accent, 0, .28, 0);
addBox(group, .14, .27, .15, materials.dark, -.12, .10, 0);
addCylinder(group, .06, .06, .22, 8, materials.woodLight, .36, .28, 0).rotation.z = Math.PI / 2;
} else if (type === "fan") {
addCylinder(group, .24, .28, .08, 8, materials.dark, 0, .05, 0);
addCylinder(group, .025, .025, .38, 6, materials.dark, 0, .27, 0);
const ring = new THREE.Mesh(new THREE.TorusGeometry(.27, .025, 6, 16), accent);
ring.position.y = .52;
group.add(ring);
addBox(group, .45, .07, .07, accent, 0, .52, 0);
addBox(group, .07, .07, .45, accent, 0, .52, 0);
} else if (type === "pump") {
addCylinder(group, .09, .09, .62, 8, materials.dark, 0, .32, 0);
addBox(group, .28, .08, .09, accent, 0, .66, 0);
addBox(group, .10, .20, .09, accent, 0, .08, 0);
} else if (type === "bell") {
addCone(group, .21, .24, 8, accent, 0, .18, 0);
addCylinder(group, .24, .24, .035, 8, materials.dark, 0, .04, 0);
} else if (type === "radio") {
addBox(group, .48, .30, .17, accent, 0, .22, 0);
addBox(group, .23, .12, .025, materials.dark, -.10, .24, .10);
addCylinder(group, .012, .012, .46, 5, materials.dark, .17, .55, 0).rotation.z = -.2;
} else if (type === "printer") {
addBox(group, .58, .28, .42, materials.creamLight, 0, .17, 0);
addBox(group, .48, .04, .27, materials.dark, 0, .34, -.02);
addBox(group, .27, .04, .16, accent, 0, .38, .02);
}
group.scale.setScalar(.82);
return group;
}
function showRestoredObject(station, job) {
const model = createRestoredModel(job.type, station.color);
model.position.copy(station.benchPosition);
station.group.add(model);
const models = station.group.userData.restoredModels || [];
models.push(model);
station.group.userData.restoredModels = models;
if (models.length > 3) {
const old = models.shift();
station.group.remove(old);
}
}
// ------------------------------------------------------------
// Couriers
// ------------------------------------------------------------
const couriers = [];
const courierColors = [0x2f7762, 0xd9784e, 0x6e78a9];
courierColors.forEach((color, index) => {
const person = createPerson(color, true);
person.scale.setScalar(.9);
person.position.set((index - 1) * .75, .04, .55 + index * .13);
scene.add(person);
const partHolder = new THREE.Group();
partHolder.position.set(0, .62, .30);
person.add(partHolder);
const carryingPart = addBox(
partHolder,
.26,
.20,
.22,
materials.orange,
0,
0,
0
);
carryingPart.visible = false;
couriers.push({
group: person,
holder: partHolder,
partMesh: carryingPart,
state: "idle",
job: null,
target: new THREE.Vector3(),
repairTimer: 0,
repairDuration: 2,
startPosition: person.position.clone()
});
});
function moveCourierTowards(courier, target, speed, delta) {
const current = courier.group.position;
const direction = target.clone().sub(current);
direction.y = 0;
const distance = direction.length();
if (distance > 0.03) {
direction.normalize();
current.addScaledVector(direction, Math.min(distance, speed * delta));
const desiredAngle = Math.atan2(direction.x, direction.z);
const angleDifference = Math.atan2(
Math.sin(desiredAngle - courier.group.rotation.y),
Math.cos(desiredAngle - courier.group.rotation.y)
);
courier.group.rotation.y += angleDifference * Math.min(1, delta * 11);
const stride = Math.sin(performance.now() * .012) * .35;
courier.group.userData.leftLeg.rotation.x = stride;
courier.group.userData.rightLeg.rotation.x = -stride;
current.y = .05 + Math.abs(Math.sin(performance.now() * .012)) * .045;
} else {
courier.group.userData.leftLeg.rotation.x = 0;
courier.group.userData.rightLeg.rotation.x = 0;
current.y = .04;
}
return distance;
}
function dispatchPart(station, partId) {
const stock = inventory[partId];
const available = stock.total - stock.reserved;
if (available <= 0) {
showToast(`No ${partDefinitions[partId].name.toLowerCase()} remain in the shared library.`);
return;
}
if (station.activeJob) {
showToast(`${station.name} already has a repair in progress.`);
return;
}
const job = station.jobs.find(candidate =>
candidate.status === "pending" && candidate.required === partId
);
if (!job) {
showToast(`${partDefinitions[partId].name} is not compatible with a waiting repair at ${station.name}.`);
return;
}
const courier = couriers.find(candidate => candidate.state === "idle");
if (!courier) {
showToast("All community couriers are currently on the road.");
return;
}
stock.reserved++;
job.status = "transit";
job.progress = 0;
station.activeJob = job;
courier.state = "toStation";
courier.job = job;
courier.group.userData.leftLeg.rotation.x = 0;
courier.group.userData.rightLeg.rotation.x = 0;
const localTarget = new THREE.Vector3(0, .04, 1.95);
station.group.localToWorld(localTarget);
courier.target.copy(localTarget);
courier.partMesh.material.color.set(partDefinitions[partId].color);
courier.partMesh.visible = true;
activity.unshift({
text: `${partDefinitions[partId].name} dispatched to ${station.name}.`,
time: "Now"
});
uiDirty = true;
showToast(`${partDefinitions[partId].name} is on the way to ${station.name}.`);
}
function completeRepair(courier) {
const job = courier.job;
const station = stations.find(candidate => candidate.id === job.stationId) ||
stations.find(candidate => candidate.jobs.includes(job));
// The station id is assigned on dispatch if it was not already present.
const owningStation = station || stations.find(candidate => candidate.activeJob === job);
if (!owningStation) return;
const stock = inventory[job.required];
stock.total = Math.max(0, stock.total - 1);
stock.reserved = Math.max(0, stock.reserved - 1);
job.status = "restored";
job.progress = 1;
owningStation.activeJob = null;
owningStation.restoredCount++;
restoredObjects.unshift({
object: job.object,
station: owningStation.name,
color: owningStation.color,
time: "Now"
});
showRestoredObject(owningStation, job);
rebuildLibraryCrates();
activity.unshift({
text: `${job.object} restored at ${owningStation.name}; 1 ${partDefinitions[job.required].name.toLowerCase()} used.`,
time: "Now"
});
courier.state = "return";
courier.target.set((couriers.indexOf(courier) - 1) * .75, .04, .55 + couriers.indexOf(courier) * .13);
courier.partMesh.visible = false;
uiDirty = true;
showToast(`${job.object} restored! Shared inventory has been updated.`);
}
// Assign station IDs to jobs for easier lookup.
stations.forEach(station => {
station.jobs.forEach(job => job.stationId = station.id);
});
// ------------------------------------------------------------
// World labels
// ------------------------------------------------------------
const labelContainer = document.getElementById("labels");
const stationLabels = [];
stations.forEach(station => {
const label = document.createElement("div");
label.className = "world-label";
label.innerHTML = `
<div class="label-name">${station.name}</div>
<div class="label-status"></div>
`;
label.style.setProperty("--label-color", station.color);
label.addEventListener("click", () => selectStation(station.id, true));
labelContainer.appendChild(label);
stationLabels.push({ station, element: label, statusElement: label.querySelector(".label-status") });
});
const libraryLabel = document.createElement("div");
libraryLabel.className = "world-label library";
libraryLabel.innerHTML = `
<div class="label-name">Shared Parts Library</div>
<div class="label-status">Neighborhood inventory</div>
`;
labelContainer.appendChild(libraryLabel);
const libraryLabelPosition = new THREE.Vector3(0, 3.45, -3.05);
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
stationLabels.forEach(({ station, element }) => {
const position = station.group.position.clone();
position.y = 3.0;
position.project(camera);
const visible = position.z > -1 && position.z < 1 &&
Math.abs(position.x) < 1.12 && Math.abs(position.y) < 1.12;
element.style.display = visible ? "block" : "none";
if (visible) {
const x = (position.x * .5 + .5) * width;
const y = (-position.y * .5 + .5) * height;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.classList.toggle("selected", station.id === selectedStationId);
}
});
const projected = libraryLabelPosition.clone().project(camera);
libraryLabel.style.left = `${(projected.x * .5 + .5) * width}px`;
libraryLabel.style.top = `${(-projected.y * .5 + .5) * height}px`;
libraryLabel.style.display =
projected.z > -1 && projected.z < 1 &&
Math.abs(projected.x) < 1.1 && Math.abs(projected.y) < 1.1
? "block"
: "none";
}
// ------------------------------------------------------------
// UI rendering
// ------------------------------------------------------------
const stationListElement = document.getElementById("stationList");
const stationDetailElement = document.getElementById("stationDetail");
const inventoryListElement = document.getElementById("inventoryList");
const restoredListElement = document.getElementById("restoredList");
const activityListElement = document.getElementById("activityList");
function getSelectedStation() {
return stations.find(station => station.id === selectedStationId);
}
function stationStatus(station) {
if (station.activeJob) {
if (station.activeJob.status === "transit") return "Part in transit";
if (station.activeJob.status === "repairing") return "Repair in progress";
}
const pending = station.jobs.filter(job => job.status === "pending").length;
return pending ? `${pending} repair${pending === 1 ? "" : "s"} waiting` : "Available for repairs";
}
function selectStation(stationId, focus = false) {
selectedStationId = stationId;
const station = getSelectedStation();
const selectedJob = station.jobs.find(job =>
job.status === "pending" && job.required === selectedPartId
);
if (!selectedJob) {
const nextJob = station.jobs.find(job => job.status === "pending");
if (nextJob) selectedPartId = nextJob.required;
}
if (focus) focusStation(station);
uiDirty = true;
}
function selectPart(partId) {
selectedPartId = partId;
uiDirty = true;
}
function transferState(station, partId) {
const stock = inventory[partId];
const pendingJobs = station.jobs.filter(job =>
job.status === "pending" && job.required === partId
);
const available = stock.total - stock.reserved;
if (station.activeJob) {
return {
disabled: true,
text: `Transfer ${partDefinitions[partId].name}`,
meta: "This repair bay is occupied. The current repair must finish first."
};
}
if (!pendingJobs.length) {
return {
disabled: true,
text: `Transfer ${partDefinitions[partId].name}`,
meta: `No compatible waiting repair at ${station.name}. Choose another part or station.`
};
}
if (available <= 0) {
return {
disabled: true,
text: `Transfer ${partDefinitions[partId].name}`,
meta: "This shared component is exhausted."
};
}
return {
disabled: false,
text: `Transfer ${partDefinitions[partId].name}`,
meta: `Compatible with ${pendingJobs[0].object}. A community courier will collect it from the library.`
};
}
function renderUI() {
const selectedStation = getSelectedStation();
stationListElement.innerHTML = stations.map((station, index) => `
<button class="station-card ${station.id === selectedStationId ? "active" : ""}" data-station="${station.id}">
<span class="station-dot" style="background:${station.color}"></span>
<span>
<span class="station-name">${station.name}</span>
<span class="station-status">${stationStatus(station)}</span>
</span>
<span class="station-number">0${index + 1}</span>
</button>
`).join("");
const transfer = transferState(selectedStation, selectedPartId);
stationDetailElement.innerHTML = `
<div class="detail-card">
<div class="detail-top">
<div class="detail-title">${selectedStation.name}</div>
<div class="capacity">${selectedStation.restoredCount} restored</div>
</div>
<div class="job-list">
${selectedStation.jobs.length ? selectedStation.jobs.map(job => {
const stateText = {
pending: "Queued",
transit: "In transit",
repairing: `Repairing ${Math.round(job.progress * 100)}%`,
restored: "Restored"
}[job.status];
return `
<button class="job-row" data-job="${job.id}" data-part="${job.required}">
<span>
<span class="job-object">${job.object}</span>
<span class="job-part">${partDefinitions[job.required].name} · ${job.owner}</span>
</span>
<span class="job-state ${job.status}">${stateText}</span>
</button>
`;
}).join("") : `<div class="empty-state">No objects are waiting here.</div>`}
</div>
<button class="primary-button" id="transferButton" ${transfer.disabled ? "disabled" : ""}>
${transfer.text}
</button>
<div class="transfer-meta">${transfer.meta}</div>
</div>
`;
const totalParts = Object.values(inventory).reduce((sum, stock) => sum + stock.total, 0);
inventoryListElement.innerHTML = Object.entries(partDefinitions).map(([partId, definition]) => {
const stock = inventory[partId];
const matches = stations.reduce((count, station) => count +
station.jobs.filter(job => job.status === "pending" && job.required === partId).length, 0);
return `
<button class="part-row ${partId === selectedPartId ? "selected" : ""}" data-part="${partId}" style="--part-color:${definition.color}">
<span class="part-icon">${definition.code}</span>
<span>
<span class="part-name">${definition.name}</span>
<span class="part-meta">
${matches} compatible job${matches === 1 ? "" : "s"}${stock.reserved ? ` · ${stock.reserved} reserved` : ""}
</span>
</span>
<span class="part-quantity">${stock.total}</span>
<span class="stock-track">
<span class="stock-fill" style="width:${stock.total / stock.initial * 100}%"></span>
</span>
</button>
`;
}).join("");
restoredListElement.innerHTML = restoredObjects.length
? restoredObjects.slice(0, 7).map(item => `
<div class="restored-item">
<div class="restored-check">✓</div>
<div>
<div class="restored-name">${item.object}</div>
<div class="restored-place">${item.station}</div>
</div>
<div class="restored-time">${item.time}</div>
</div>
`).join("")
: `<div class="empty-state">Restored objects will appear here as repairs are completed.</div>`;
activityListElement.innerHTML = activity.slice(0, 8).map(item => `
<div class="activity-item">
<span class="activity-dot"></span>
<span>${item.text} <span style="color:#a2aaa4">· ${item.time}</span></span>
</div>
`).join("");
document.getElementById("stationCount").textContent = stations.length;
document.getElementById("totalParts").textContent = totalParts;
document.getElementById("restoredCount").textContent = restoredObjects.length;
document.getElementById("statStations").textContent = stations.length;
document.getElementById("statStock").textContent = totalParts;
document.getElementById("statRestored").textContent = restoredObjects.length;
document.getElementById("statTransfers").textContent =
couriers.filter(courier => courier.state !== "idle").length;
stationLabels.forEach(({ station, statusElement }) => {
statusElement.textContent = stationStatus(station);
});
}
stationListElement.addEventListener("click", event => {
const card = event.target.closest("[data-station]");
if (card) selectStation(card.dataset.station, true);
});
stationDetailElement.addEventListener("click", event => {
const job = event.target.closest("[data-job]");
if (job) {
selectedPartId = job.dataset.part;
uiDirty = true;
}
if (event.target.closest("#transferButton")) {
dispatchPart(getSelectedStation(), selectedPartId);
}
});
inventoryListElement.addEventListener("click", event => {
const row = event.target.closest("[data-part]");
if (row) selectPart(row.dataset.part);
});
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 3000);
}
// Mobile panel controls.
document.getElementById("toggleLeft").addEventListener("click", () => {
document.getElementById("leftPanel").classList.toggle("mobile-open");
document.getElementById("rightPanel").classList.remove("mobile-open");
});
document.getElementById("toggleRight").addEventListener("click", () => {
document.getElementById("rightPanel").classList.toggle("mobile-open");
document.getElementById("leftPanel").classList.remove("mobile-open");
});
// ------------------------------------------------------------
// Direct camera controls: orbit, pan and zoom
// ------------------------------------------------------------
const orbit = {
theta: .64,
phi: .93,
radius: 18.5,
target: new THREE.Vector3(0, .25, -.6)
};
function applyCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function focusStation(station) {
orbit.target.set(station.position.x, .35, station.position.z);
orbit.radius = 10.8;
orbit.phi = .95;
orbit.theta = Math.atan2(
camera.position.x - station.position.x,
camera.position.z - station.position.z
);
}
function resetCamera() {
orbit.theta = .64;
orbit.phi = .93;
orbit.radius = 18.5;
orbit.target.set(0, .25, -.6);
}
document.getElementById("resetView").addEventListener("click", resetCamera);
const pointerState = {
active: false,
pointerId: null,
mode: "orbit",
lastX: 0,
lastY: 0
};
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
pointerState.active = true;
pointerState.pointerId = event.pointerId;
pointerState.mode = event.button === 2 ? "pan" : "orbit";
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!pointerState.active || event.pointerId !== pointerState.pointerId) return;
const deltaX = event.clientX - pointerState.lastX;
const deltaY = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
if (pointerState.mode === "orbit") {
orbit.theta -= deltaX * .006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - deltaY * .005, .34, 1.35);
} else {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, camera.up).normalize();
const screenUp = new THREE.Vector3().crossVectors(right, forward).normalize();
const panScale = orbit.radius * .0014;
orbit.target.addScaledVector(right, -deltaX * panScale);
orbit.target.addScaledVector(screenUp, deltaY * panScale);
}
});
function endPointer(event) {
if (event.pointerId !== pointerState.pointerId) return;
pointerState.active = false;
pointerState.pointerId = null;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * .001),
7,
27
);
}, { passive: false });
canvas.addEventListener("dblclick", () => focusStation(getSelectedStation()));
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), .05);
const elapsed = clock.elapsedTime;
couriers.forEach(courier => {
if (courier.state === "toStation") {
const distance = moveCourierTowards(courier, courier.target, 3.15, delta);
if (distance < .13) {
courier.state = "repairing";
courier.repairTimer = 0;
courier.repairDuration = 1.8 + Math.random() * .8;
courier.group.rotation.y = Math.atan2(
courier.group.position.x - courier.job.stationId,
1
);
uiDirty = true;
}
} else if (courier.state === "repairing") {
courier.repairTimer += delta;
courier.job.progress = Math.min(1, courier.repairTimer / courier.repairDuration);
courier.partMesh.rotation.y = elapsed * 2.8;
if (courier.repairTimer >= courier.repairDuration) {
completeRepair(courier);
}
} else if (courier.state === "return") {
const distance = moveCourierTowards(courier, courier.target, 3.0, delta);
if (distance < .12) {
courier.state = "idle";
courier.job = null;
courier.group.rotation.y = 0;
uiDirty = true;
}
}
});
stations.forEach((station, index) => {
station.ring.material.opacity = station.id === selectedStationId ? 1 : .32;
station.ring.material.transparent = true;
station.ring.scale.setScalar(
station.id === selectedStationId
? 1 + Math.sin(elapsed * 2.7) * .025
: 1
);
});
applyCamera();
updateWorldLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
setInterval(() => {
if (uiDirty) {
renderUI();
uiDirty = false;
}
}, 180);
renderUI();
applyCamera();
animate();
</script>
</body>
</html>
```