CiviSim

README.md at tip
Login

File README.md from the latest check-in


# Civisim — 3D Isometric Grid City Simulator

**Civisim** is a fully 3D isometric grid city simulation engine and tabletop sandbox that runs entirely in the modern web browser. Designed with a strict zero-dependency, zero-build philosophy, the entire game—simulation engine, procedural 2D canvas texture generator, procedural 3D mesh synthesizer, goal-directed AI city planner, Three.js tabletop renderer, and responsive UI—lives in a single standalone HTML file (`index.html`).

Civisim runs 100% offline as an installable Progressive Web App (PWA), requires no package manager or backend, and can be served from any static file server.

![](/raw/0ef0c3a9ad15518b)

---

## Table of Contents

- [Core Product Overview](#core-product-overview)
- [Simulation Capabilities](#simulation-capabilities)
  - [3D Tabletop Presentation & Atmosphere](#3d-tabletop-presentation--atmosphere)
  - [Labor Market & Economic Equilibrium](#labor-market--economic-equilibrium)
  - [Networks & 3-Manhattan-Tile Conduit Topology](#networks--3-manhattan-tile-conduit-topology)
  - [Utilities & Civic Infrastructure](#utilities--civic-infrastructure)
  - [Autonomous Arcology Evolution](#autonomous-arcology-evolution)
  - [Autonomous AI City Planner (`CityPlanner`)](#autonomous-ai-city-planner-cityplanner)
  - [Hazards & Adversarial Disasters](#hazards--adversarial-disasters)
  - [Data Overlays & Tile Inspection](#data-overlays--tile-inspection)
  - [Persistence & Progressive Web App (PWA)](#persistence--progressive-web-app-pwa)
- [Simulation Specifications & Statistics](#simulation-specifications--statistics)
  - [Grid & Spatial Scale](#grid--spatial-scale)
  - [Temporal Cadence](#temporal-cadence)
  - [Demographics & Building Densities](#demographics--building-densities)
  - [Utility & Service Capacity Registry](#utility--service-capacity-registry)
  - [Fiscal & Policy Parameters](#fiscal--policy-parameters)
- [Codebase Architecture & File Structure](#codebase-architecture--file-structure)
  - [Repository Layout](#repository-layout)
  - [Anatomy of `index.html`](#anatomy-of-indexhtml)
  - [Unidirectional Data Flow](#unidirectional-data-flow)
- [Contributor Guide (Humans & AI Agents)](#contributor-guide-humans--ai-agents)
  - [Quick Start](#quick-start)
  - [Verification & Headless Testing](#verification--headless-testing)
  - [Critical Invariants & Sharp Edges](#critical-invariants--sharp-edges)
  - [Design Documents & Further Reading](#design-documents--further-reading)

---

## Core Product Overview

### The Gameplay Loop

You begin with a virgin landscape featuring a meandering river, an expansive lake, and wild old-growth woodlands. As mayor and city planner:

1. **Pave the Way**: Lay streets, wide avenues, and multi-span bridges over water.
2. **Zone for Growth**: Paint low- and high-density zones for Residential, Commercial, and Industrial expansion.
3. **Power & Connect**: Build coal, solar, or nuclear power plants, water pumping and treatment facilities, sewage systems, and gigabit fiber Internet Points of Presence (POPs).
4. **Deploy Municipal Services**: Provide fire protection, police coverage, tiered education (elementary, high school, university), 5G cellular arrays, rapid-transit subway networks, entertainment, and regional airports.
5. **Watch the City Evolve**: Buildings spontaneously construct and upgrade across 4 architectural stages, eventually evolving into monumental self-contained mega-arcologies.

### Key Simulation Principles

- **No Abandonment, No Decay**: Buildings never downgrade stages or turn into abandoned blighted husks. Growth is throttled or halted when power, water, sewage, internet, or road connectivity are missing, but established structures remain intact.
- **The Economy Gates Construction, Never Growth**: When the optional economy is enabled, insolvency halts new construction—it never destroys or closes existing buildings. Insolvency is a temporary moratorium on spending, not a death spiral.
- **Deterministic Procedural Generation**: Map topography, river bends, lake shores, wild forests, building facades, and arcology architectural variants are deterministically derived using procedural PRNG streams and 2D coordinate hashing.

---

## Simulation Capabilities

### 3D Tabletop Presentation & Atmosphere

- **True Isometric Camera**: Rendered using a Three.js `OrthographicCamera` set to an oblique isometric angle (atan(1/√2) ≈ 35.264°), with 4-way 90° azimuth rotations (`Q`/`E`), smooth interpolation, and clamped pan/zoom limits.
- **Dynamic Day/Night Lighting Cycle**: Continuous transitions between bright daylight, golden dusk, and deep night, complete with rotating directional sunlight, soft ambient illumination, and realistic shadow mapping.
- **Animated Traffic Fleet**: Procedural passenger cars, transit vehicles, and commercial trucks spawn on road networks, traversing intersections and projecting real-time headlight beams across the pavement after dark.
- **Dynamic Skylines & Shaders**:
  - **Lit Windows Shader**: Wall materials use custom injected vertex/fragment shader blocks (`onBeforeCompile`) calculating per-window illumination patterns staggered across sim time.
  - **Obstruction Beacons**: Emissive rooftop warning beacons pulse with out-of-phase flashes atop high-rises, cell towers, and power plants during dusk and nighttime.
  - **Procedural Water**: Dynamic vertex and normal wave displacement driven by multi-frequency sine wave shaders, reflecting specular sunlight and ambient sky colors.
  - **Seasonal Palettes**: Dynamic leaf, grass, and shoreline tint shifting across Spring, Summer, Autumn, and Winter (either synced to the real-world calendar or manually pinned).

### Labor Market & Economic Equilibrium

- **Dynamic Labor-Market Model**: Regional demand for R/C/I is calculated in continuous equilibrium:
  - Labor force is derived as 60% of total population.
  - Base commercial and industrial job targets require balanced staffing.
  - Higher city education levels raise office/commercial job demand (`1 + 0.25 × eduIndex`), demanding high-wage professional workers.
- **Tax Policy Reaction**: Tax rates above the 10% benchmark dampen demand up to 50% at 20% tax rates and slightly reduce land desirability, but never cause population flight.

### Networks & 3-Manhattan-Tile Conduit Topology

- **Graph BFS Road Analysis**: Road tiles are grouped into connected graph components via Breadth-First Search (BFS).
- **The 3-Tile Rule**: Non-road tiles within ≤ 3 Manhattan tiles (|dx| + |dz| ≤ 3) of a road component inherit network connectivity and utility transmission. Road conduits carry power, water, sewage, and fiber optic data directly to adjacent properties without separate pipe/wire dragging.
- **Per-Network Utility Isolation**: Utility production and consumption are computed per road component. Isolated road segments cannot draw utility capacity from disjoint networks.

### Utilities & Civic Infrastructure

- **Three Energy Tiers**: Dirty fossil-fuel thermal plants (1,000 MW, high pollution), clean solar & battery storage arrays (600 MW, zero emissions), and high-output nuclear baseload facilities (2,400 MW).
- **Water & Shoreline Mechanics**: Shoreline-adjacent pumping stations produce 2.5× the output of inland wells. Industrial water treatment plants scale up municipal throughput.
- **Environmental Management**: Sewage plants and water reclamation facilities eliminate effluent backflow and mitigate urban ground contamination.
- **Multi-Tier Telecommunications**: Central POP fiber hubs distribute bandwidth, while standard 5G towers and Metro 6G micro-arrays boost commercial growth velocity and taxable revenue.
- **Education Ladder**: Three tiered institutions—Elementary Schools, High Schools, and Universities—expand city-wide literacy and technical training, multiplying worker wages up to 2.26×.
- **Rapid Transit & Regional Aviation**:
  - **Subways**: High-capacity underground stations slash local surface traffic congestion by up to 75% and grant a Transit-Oriented Development (TOD) desirability bonus.
  - **Metropolitan Airports**: Large 2×2 airport complexes increase commercial demand by +22%, unlock external trade income (+20%), and spawn autonomous airliners that fly scenic holding patterns and point-to-point transit loops across the map.

### Autonomous Arcology Evolution

- **Landmark Monuments**: Homogeneous 2×2 clusters of mature Stage 4 high-density buildings (`R_HIGH`, `C_HIGH`, `I_HIGH`) that meet strict prosperity, desirability, fire protection, and education/connectivity gates autonomously evolve into futuristic mega-arcologies:
  - **Solcosit Biosphere Arcology** (`ARCO_RES`): Stepped eco-ziggurats with sky-arboretums housing 2,000 citizens.
  - **Darco Cyber-Monolith Arcology** (`ARCO_COM`): Twin megatowers joined by sky-lobbies providing 2,500 corporate jobs.
  - **Eco-Forge Automated Arcology** (`ARCO_IND`): Concentric robotic synthesis foundries providing 2,400 clean industrial positions.
  - **Stellar Citadel Launch Arcology** (`ARCO_CIVIC`): A massive 50,000-citizen civic wonder replica complete with rocket gantries and orbital telemetry arrays.
- **Combinatorial 3×3×3 Architectural Flair**: Arcologies generate 27 distinct structural permutations (108 factoring 4-way orientations) combining summit crowns, chasm pods/gondolas, and decorative facades.

### Autonomous AI City Planner (`CityPlanner`)

- **A Player, Not a Simulation**: The built-in AI city builder is a deterministic, goal-directed heuristic planner. It cannot cheat: it reads only the state visible to the player and acts exclusively through `sim.applyTool()`.
- **Endless Expansion**: The AI automatically surveys city bottlenecks (road deficits, power brownouts, water shortages, coverage gaps, zoning imbalances, and economic headroom), methodically expanding the metropolis toward progressive population milestones.
- **Respect for Player Creations**: The AI strictly tracks its own construction footprint (`this.owned`) and will never bulldoze or alter player-placed structures.

### Hazards & Adversarial Disasters

- **Dynamic Fire Propagation**: Fires ignite randomly on zoned structures, spreading to adjacent buildings if unprotected. Active fire stations douse blazes on protected tiles (`fireCov >= FIRE_PROTECT_COV`), saving buildings before they collapse into rubble.
- **Disasters**: Manual or optional automated natural disasters:
  - **Tornado**: A destructive 3D vortex that sweeps across the landscape carving a path of rubble.
  - **Earthquake**: High-intensity tectonic tremors causing structural damage across vulnerable districts.
  - **River Flood**: Seasonal storm surges causing river and lake waters to spill onto adjacent shorelines.
- **Rubble Recovery**: Rubble slowly clears and rebuilds over time, accelerated when covered by civic emergency services.

### Data Overlays & Tile Inspection

- **8 Diagnostic Heatmaps**:
  1. **Utilities**: Grid-wide power and water transmission status and brownout indicators.
  2. **Cell & Data**: 5G/6G wireless network signal distribution.
  3. **Safety**: Combined fire protection thresholds and police patrol coverage.
  4. **Education**: Aggregated elementary, secondary, and tertiary school coverage.
  5. **Pollution**: Ground and atmospheric pollution gradients from industry and traffic.
  6. **Traffic**: Roadway congestion densities and subway transit relief.
  7. **Tax Base**: Per-tile weekly revenue generation tiers.
  8. **Desirability**: Residential and commercial land-value desirability.
- **Deep Tile Inspector**: Inspect any tile on the map to view real-time zoning, stage, population, land value, weekly tax yield, pollution, noise, road access, and utility connections.

### Persistence & Progressive Web App (PWA)

- **100% Offline Capable**: A dedicated Service Worker (`sw.js`) precaches the HTML shell, icons, and the CDN-hosted Three.js library.
- **Deterministic Save Format**: Saves store only the initial random map seed and a compact delta list of modified tiles (`SAVE_FORMAT_VERSION = 3`), regenerating terrain and recomputing all derived coverage on load.
- **Local & Exportable Storage**: Automated background autosaves every 30 seconds, 3 manual local storage save slots, and full JSON file export/import capabilities.

---

## Simulation Specifications & Statistics

### Grid & Spatial Scale

| Parameter | Value | Description |
| :--- | :--- | :--- |
| **Grid Dimensions** | 64 × 64 tiles | Total of 4,096 addressable grid tiles |
| **Tile Size** | 2.0 × 2.0 world units | Total world footprint: 128.0 × 128.0 units |
| **Coordinate System** | `grid[z][x]` | Row-major: 0 ≤ z < 64 (rows), 0 ≤ x < 64 (columns) |
| **World Bounds** | ±64.0 units | Origin (0, 0, 0) is centered at the grid midpoint |
| **Conduit Reach** | ≤ 3 Manhattan tiles | Maximum distance from a road tile to receive utility access |
| **Camera View** | Oblique Orthographic | Azimuth: π/4 + k·π/2; Elevation: atan(1/√2) ≈ 35.264° |

### Temporal Cadence

| Metric | Equivalent Time | Description |
| :--- | :--- | :--- |
| **1 Sim Tick** | **1 Sim Week** | 1.25 seconds in real time at standard 1× simulation speed |
| **4 Sim Ticks** | **1 Sim Month** | ~5.0 seconds in real time |
| **48 Sim Ticks** | **1 Sim Year** | 12 sim months; ~60.0 seconds in real time |
| **Sim Speeds** | 0×, 1×, 2×, 5× | Pause (0×), Normal (1.25s), Fast (0.625s), Ultra (0.25s) |
| **Autosave Cadence** | Every 30 seconds | Also triggers on `pagehide` and visibility loss |
| **AI Planner Beat** | Every 2 sim ticks | Up to 4 atomic tool placement actions evaluated per beat |

### Demographics & Building Densities

| Zone / Structure | Footprint | Density | Max Population / Capacity | Notes |
| :--- | :---: | :---: | :---: | :--- |
| **Residential Low (`R_LOW`)** | 1 × 1 | Low (1) | 40 residents | Detached single-family suburban homes |
| **Residential High (`R_HIGH`)** | 1 × 1 | High (2) | 240 residents | High-density multi-story apartment towers |
| **Commercial Low (`C_LOW`)** | 1 × 1 | Low (1) | 50 jobs | Neighborhood retail shops & diners |
| **Commercial High (`C_HIGH`)** | 1 × 1 | High (2) | 300 jobs | Glass corporate office skyscrapers |
| **Industrial Low (`I_LOW`)** | 1 × 1 | Low (1) | 50 jobs | Light workshops & storage warehouses |
| **Industrial High (`I_HIGH`)** | 1 × 1 | High (2) | 300 jobs | Heavy manufacturing plants & factories |
| **Residential Arcology (`ARCO_RES`)** | 2 × 2 | Mega (2) | 2,000 residents | Self-contained Solcosit biosphere |
| **Commercial Arcology (`ARCO_COM`)** | 2 × 2 | Mega (2) | 2,500 jobs | Darco cyber-monolith corporate complex |
| **Industrial Arcology (`ARCO_IND`)** | 2 × 2 | Mega (2) | 2,400 jobs | Eco-Forge automated bio-foundry |
| **Civic Arcology (`ARCO_CIVIC`)** | 2 × 2 | Wonder | 50,000 capacity | Stellar Citadel launch arcology (2,500 staff) |

### Utility & Service Capacity Registry

| Structure ID | Name | Size | Radius | Capacity | Upkeep | Capital Cost | Primary Function |
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
| `ROAD_STREET` | Street | 1 × 1 | — | 100 cap | §1 / wk | §10 | Local low-density access |
| `ROAD_AVENUE` | 4-Lane Avenue | 1 × 1 | — | 300 cap | §3 / wk | §25 | Arterial high-capacity thoroughfare |
| `UTIL_POWER` | Thermal Power Plant | 2 × 2 | Grid | 1,000 MW | §80 / wk | §1,500 | Coal/Gas generator (heavy smog) |
| `UTIL_SOLAR` | Solar & BESS Array | 2 × 2 | Grid | 600 MW | §45 / wk | §2,200 | Clean renewable energy |
| `UTIL_NUCLEAR` | Nuclear Power Plant | 2 × 2 | Grid | 2,400 MW | §220 / wk | §6,500 | Clean high-output baseload basestation |
| `UTIL_WATER` | Water Tower / Well | 1 × 1 | Grid | 300 / 750* | §15 / wk | §350 | Inland well (300) / Shore pump (750) |
| `UTIL_WATER_PLANT` | Water Treatment Plant | 2 × 2 | Grid | 2,400 / 5,000*| §65 / wk | §1,800 | Industrial municipal filtration |
| `UTIL_SEWAGE` | Sewage Treatment | 1 × 1 | Grid | 650 / 800* | §20 / wk | §450 | Inland (650) / Shore discharge (800) |
| `UTIL_SEWAGE_RECYCLE`| Water Reclamation | 2 × 2 | Grid | 4,000 / 5,500*| §75 / wk | §2,400 | Advanced closed-loop bio-digesters |
| `UTIL_INTERNET` | Gigabit POP Hub | 1 × 1 | Grid | 1,000 Gbps | §30 / wk | §600 | High-speed fiber network backbone |
| `SERVICE_CELL` | 5G Cell Tower | 1 × 1 | 9 | 8,000 | §25 / wk | §500 | Mobile coverage & office growth speed |
| `SERVICE_CELL_METRO`| Metro 6G Micro-Array | 1 × 1 | 10 | 28,000 | §60 / wk | §1,200 | Ultra-dense high-capacity connectivity |
| `SERVICE_FIRE` | Fire Station | 1 × 1 | 9 | 2,200 | §35 / wk | §600 | Local fire dousing & protection |
| `SERVICE_FIRE_HQ` | Metro Fire HQ | 2 × 2 | 14 | 16,000 | §120 / wk | §2,400 | Regional multi-apparatus station |
| `SERVICE_POLICE` | Police Station | 1 × 1 | 9 | 3,000 | §30 / wk | §550 | Crime reduction & desirability boost |
| `SERVICE_POLICE_HQ` | Metro Police HQ | 2 × 2 | 14 | 18,000 | §110 / wk | §2,200 | Centralized tactical headquarters |
| `EDU_ELEM` | Elementary School | 1 × 1 | 8 | 1,200 | §30 / wk | §500 | Tier 1 education (residents only) |
| `EDU_HIGH` | High School | 1 × 1 | 11 | 1,600 | §55 / wk | §900 | Tier 2 secondary education |
| `EDU_COLLEGE` | University Campus | 1 × 1 | 15 | 2,400 | §110 / wk | §2,000 | Tier 3 higher education & research |
| `SERVICE_SUBWAY` | Subway Station | 1 × 1 | 8 | 14,000 | §45 / wk | §1,200 | -75% road traffic, +12% TOD desirability |
| `SERVICE_AIRPORT` | Metropolitan Airport | 2 × 2 | 18 | 32,000 | §160 / wk | §7,500 | +22% comm demand, +20% trade revenue |
| `ENT_CONCERT` | Concert Hall | 1 × 1 | 10 | 5,000 | §40 / wk | §850 | Cultural venue & entertainment coverage |
| `ENT_STADIUM` | Grand Stadium | 2 × 2 | 16 | 20,000 | §140 / wk | §3,500 | Major civic sports arena |
| `PARK` | Urban Public Park | 1 × 1 | 3 | — | §5 / wk | §100 | Buffers noise and mitigates pollution |

*\*Note: Water and sewage utilities yield significantly boosted capacities when situated along shorelines.*

### Fiscal & Policy Parameters

- **Tax Rate**: Adjustable between **4% and 20%** (default: **10%**).
  - Calculated as: `Tax Revenue = sum(Tile Taxable Income) × Tax Rate`.
  - Taxable income per tile incorporates population, base per-capita income, education wage multipliers (up to 2.26×), connectivity multipliers (up to 1.30×), and land value.
- **Service Funding**: Municipal budget slider adjustable between **50% and 150%** (default: **100%**). Funding scales utility and service capacities and balances operational expenses.
- **Bulldoze Refund**: Demolishing any structure refunds **50%** of its original construction cost, providing an emergency fiscal recovery mechanism.

---

## Codebase Architecture & File Structure

### Repository Layout

```
.
├── index.html        # Complete application: HTML markup, CSS styling, and JavaScript engine (~13,900 lines)
├── AGENTS.md         # Exhaustive architectural invariants and engineering instructions for human & AI agents
├── ECONOMICS.md      # Detailed mathematical specification for the optional city economic engine
├── AIBUILDER.md      # Algorithmic design and goal heuristics for the deterministic AI city planner
├── manifest.json     # PWA manifest declaring standalone display, themes, and screen orientations
├── sw.js             # Service Worker: precaching app shell, icons, and CDN Three.js library
├── icons/            # High-resolution application and PWA maskable icons
└── .fslckout         # Fossil checkout state database (version control repository at ../civisim.fossil)
```

> **Version Control Notice**: Civisim is tracked using **Fossil**, not Git. Avoid assuming `git` commands will function in this repository.

### Anatomy of `index.html`

The entire simulation is contained within `index.html`, structured into clear, self-contained sections marked by section banners:

```
index.html
├── Lines 1–43: Head & PWA metadata (viewport, icon links, theme declarations)
├── Lines 22–1650: CSS Stylesheet (theme tokens, HUD layout, responsive tool docks, popovers, mobile sheets)
├── Lines 1651–2325: HTML DOM Shell (top HUD, left tool dock, right inspector dock, budget & save modals)
└── Lines 2326–13911: ES Module (<script type="module">)
    ├── // 1. CONSTANTS & DEFINITIONS (~L2330)
    │   Registry of ZONE_DEFS, TOOL_ZONE_MAP, overlay configs, colorways, audio frequencies, and simulation constants.
    ├── // 2. PROCEDURAL 2D CANVAS TEXTURE FACTORY (~L2849)
    │   ProceduralTextureFactory: Generates dynamic canvas textures for building facades, road asphalt, curbs, and lot status badges.
    ├── // 3. PROCEDURAL 3D BUILDING, UTILITY & PROP GENERATOR (~L3380)
    │   ProceduralBuildingBuilder: Procedural 3D Three.js geometry synthesizer for residential/commercial skyscrapers,
    │   factories, power stations, airports, stadiums, subways, and modular 2x2 arcologies.
    ├── // 4. SIMULATION ENGINE (~L6023)
    │   CitySimulation: Grid management, map seeding, graph BFS road networks, utility stamping, service coverage,
    │   demographic labor equilibrium, growth evaluation, and fiscal accounting.
    ├── // 4b. AI CITY PLANNER (~L8001)
    │   CityPlanner: Goal-directed heuristic agent that surveys city deficits, optimizes road grids, resolves utility
    │   shortages, and places zones via applyTool().
    ├── // 5. THREE.JS 3D TABLETOP RENDERER (~L9893)
    │   CityRenderer: Orthographic camera controls, day/night lighting, shadow rendering, water shaders, vehicle
    │   traffic animations, airplane flight loops, and disaster particle visualizers.
    └── // 6. APPLICATION CONTROLLER & UI BINDINGS (~L12053)
        Event loop, mouse/touch raycasting, tool selection state, modal sheet controllers, HUD updating, and autosave management.
```

### Unidirectional Data Flow

Civisim enforces a strict unidirectional data flow to prevent desynchronization between state and graphics:

```
     ┌────────────────────────────────────────────────────────┐
     │              Player Input & UI Events                   │
     │     (Mouse Clicks, Touch Gestures, Keyboard, HUD)      │
     └──────────────────────────┬─────────────────────────────┘
                                │
                                ▼
     ┌────────────────────────────────────────────────────────┐
     │            Simulation Engine (CitySimulation)          │
     │      - BFS Road & Conduit Topology                     │
     │      - Power, Water, Sewage & Internet Grids           │
     │      - Regional RCI Labor Equilibrium & Growth         │
     │      - Municipal Treasury & Economic Ledger            │
     └──────────────────────────┬─────────────────────────────┘
                                │ Callbacks:
                                │  • onTileVisualChanged(tile)
                                │  • onHazardEvent(msg, tile)
                                │  • onEconomyEvent(msg)
                                │  • onPlannerEvent(event)
                                ▼
     ┌────────────────────────────────────────────────────────┐
     │             Tabletop Renderer (CityRenderer)           │
     │      - Updates Three.js Meshes & Shaders               │
     │      - Animates Traffic Fleets & Airplane Loops        │
     │      - Re-renders Modified Tile Groups Only            │
     │      (Renderer NEVER mutates Simulation State)         │
     └────────────────────────────────────────────────────────┘
```

- **Simulation Isolation**: `CitySimulation` never references Three.js objects or accesses the DOM.
- **Renderer Isolation**: `CityRenderer` reads state to draw visual geometry, but never mutates simulation models directly.
- **AI Planner Boundary**: `CityPlanner` is an external client to the simulation. It observes only what the player sees and performs actions exclusively through `sim.applyTool()`.

---

## Contributor Guide (Humans & AI Agents)

Whether you are a human developer or an autonomous coding agent, follow these principles when contributing to Civisim:

### Quick Start

Because there are no build steps, compiling, or package installations, you only need a simple static HTTP server:

```bash
# Serve the repository root over HTTP on port 8123
python3 -m http.server 8123 --bind 127.0.0.1

# Navigate in your browser:
# http://127.0.0.1:8123/index.html
```

*(Serving over HTTP/HTTPS is required for the Service Worker to register and manage offline caching; opening directly via `file://` works for basic testing but skips offline PWA registration).*

### Verification & Headless Testing

Civisim contains no external test runner (like Jest or Mocha). Verification is done by executing the application in a headless browser or inspecting model states via the debug hook:

```bash
# Smoke test with headless Chromium (dumping the post-JS execution DOM)
chromium --headless=new --no-sandbox --disable-gpu --enable-unsafe-swiftshader \
  --virtual-time-budget=6000 --dump-dom "http://127.0.0.1:8123/index.html"
```

#### The `?debug=1` Diagnostic Interface

For rigorous model inspection, appending `?debug=1` to the URL exposes the core simulation, renderer, and AI planner instances globally:

```javascript
// Available in developer tools when URL has ?debug=1:
window.__civisim = { sim, renderer, planner };

// Verify headless planner determinism:
window.__civisim.sim.initGrid(42);
const results = window.__civisim.planner.runHeadless('successful', { seed: 100 });
console.log(results); // { goal, reason, ok, score, ticks, actions, population, funds, checks }
```

### Critical Invariants & Sharp Edges

When writing code or refactoring, you must preserve these architectural invariants:

1. **Row-Major Grid Indexing**: Always access the grid as `grid[z][x]`. Never index as `grid[x][z]`.
2. **2×2 Zone Footprints**: For multi-tile structures (Power Plants, Water Treatment Plants, Sewage Reclamation, Stadiums, HQs, Airports, Arcologies), the **top-left tile is the authoritative anchor** (`anchorX`, `anchorZ`). Accumulation loops for capacity, upkeep, tax income, or pollution **must skip non-anchor sub-tiles**, or the structure will quadruple-count.
3. **The Economy Invariant**: The economy gates *construction*, never *growth*. Insolvency may refuse a new tool placement, but it must **never** downgrade, destroy, darken, or shrink existing buildings.
4. **Tick Pipeline Order**: The sequence within `CitySimulation.stepTick()` is delicate:
   1. Fire spread and flood recession dousing.
   2. Labor-market demand equilibrium calculation.
   3. Tile growth progression.
   4. Network and utility recalculation.
   5. Totals recalculation (including weekly economic ledger settlement).
5. **Tile Rebuilding Discipline**: Whenever a tile's visual state changes, `sim.onTileVisualChanged(tile)` must be invoked so `CityRenderer.updateSingleTileVisual(tile)` disposes the old Three.js `Group` before mounting new meshes, preventing GPU memory leaks.
6. **No Phantom Utilities**: Utilities require a road within 3 Manhattan tiles on a connected road network to distribute power, water, sewage, or internet. An unlinked utility produces zero output.
7. **Cache & Save File Versioning**:
   - If you modify `index.html` or assets, bump `CACHE_VERSION` in `sw.js`.
   - If you add or modify persisted tile attributes, update `SAVED_TILE_FIELDS` in `index.html` and bump `SAVE_FORMAT_VERSION`.

### Design Documents & Further Reading

For in-depth explanations of specific subsystems, consult the companion documents:

- [AGENTS.md](file:///home/rpdillon/Sync/code/civisim/AGENTS.md) — Comprehensive technical reference, design invariants, coordinate math, rendering shader details, and failure modes.
- [ECONOMICS.md](file:///home/rpdillon/Sync/code/civisim/ECONOMICS.md) — Complete financial model, tax formulas, wage ladders, operating expenditure balances, and bootstrap grant logic.
- [AIBUILDER.md](file:///home/rpdillon/Sync/code/civisim/AIBUILDER.md) — Architectural design, goal checklist, bottleneck heuristics, and survey pipeline for `CityPlanner`.