# helix city buildings

Procedural buildings from a `helix.city-source/1` folder (design lane 3.7, `SCENE-PIPELINE-DESIGN` §3.5). One deterministic
pass writes every building as content-addressed cells on a fixed 256 m grid, plus a whole-map far layer of box masses that
is already shaped like the scene HLOD v2 "complete" layer.

```bash
helix city buildings build  <city-source-dir> --out <dir>      # cells, colliders, sidecar index, far layer, buildings.json
helix city buildings check  <city-source-dir> <dir>            # read it back and hold it against the source (exit 1 below 99%)
helix city buildings gallery <dir>                              # the building gallery as a city-source folder
```

`build` options: `--cell 128|256|512|1024` (default 256), `--far-cell` (a multiple of `--cell`, default 1024),
`--ground-filter auto|none|min3`, `--limit <n>` (first n buildings by id), `--dry-run`, `--json`.

## What it reads

`footprints` (outer ring, holes, parts, `heightM`, `levels`, `use`, `roof`, `style`, optional `mesh` pointer), `roads`
(street-facing faces), `pois` (shops), the terrain (flat height or DEM) and the overrides. Plan metres, x east, z south.
It never reads or writes anything outside `--out`.

## Output layout

```
<out>/buildings.json                          helix.city-buildings/1: cells, far clusters, mesh buildings, totals, stats
<out>/chunks/building/<sha256>.glb            near level (LOD0) of a cell
<out>/chunks/building-box/<sha256>.glb        box level (LOD1) of a cell, <= 12 triangles per part
<out>/chunks/building-collider/<sha256>.bin   HBC1 colliders, one per part
<out>/chunks/building-index/<sha256>.json     id -> triangle ranges, levels, height, use, representation, family
<out>/chunks/building-far/<sha256>.glb        HLOD v2 "complete" far layer, one per 1,024 m cluster
```

A chunk's bytes are a pure function of the generator version, the cell and the source features the cell owns (plus the
roads and shop POIs near them). A building belongs to the cell holding its outline centroid; cells are globally aligned
(`floor(x / 256)`), so a one-building edit changes one cell and its far cluster and nothing else. Chunk names are their
SHA-256. A rebuild into an existing folder adds new names and never deletes old ones (the manifest says which are live).
`BUILDINGS_GENERATOR_VERSION` (`src/city/buildings/build.ts`) is bumped whenever a change moves any output byte;
`src/city/buildings/digest.spec.ts` pins every chunk of the committed gallery and fails on any difference
(`HELIX_UPDATE_FIXTURES=1 npx jest src/city/buildings/digest.spec.ts` re-commits it).

## Two representations of the mass

For each part the box is the minimum-area oriented rectangle that contains the footprint. `IoU = footprintArea / boxArea`
is exact (the box contains the footprint). The near level draws the oriented box when `IoU >= 0.96` and the extruded
footprint (walls plus a triangulated cap, holes included) otherwise. The box level is always the box, flat top at full
height, no parapet, 12 triangles per part at most. The far layer is the box level of every cell of a 1,024 m cluster,
quantised and concatenated, with `_HELIX_HLOD_SOURCE` naming the source cell of each triangle.

## Roofs

Source `roof.shape` is honoured and falls back to flat when it cannot be drawn closed; every fallback is counted in the
manifest `stats` (`roof:too-small-for-pitch`, `footprint-over-16-vertices`, and so on).

| Shape | Box | Polygon |
| --- | --- | --- |
| flat | deck with a 0.6 m parapet (rim and deck both triangulate complete, else a plain deck) | same |
| gable, hip, pyramid | closed form, rise from the pitch (30, 30, 40 degrees), capped | straight skeleton, footprints of at most 16 vertices and no courtyard; a gable on a polygon is drawn as a hip; above 16 vertices: flat |
| skillion | one slope across the short span (10 degrees, capped) | flat |
| dome | the largest centred ellipse inside the footprint, a lathe on a flat deck; flat when none fits | same |

Footprints under 1 m2 after cleaning (duplicate points, collinear points, winding) are refused and counted; a ring that
crosses itself is refused. Everything else gets a mass, so a plan check against the source finds >= 99% of the
buildings (the SF and Granit builds find 100%).

## `_FACADE` and the material contract

Every facade and roof triangle carries `_FACADE`, four normalised u16 lanes constant over the triangle, plus
`TEXCOORD_0 = (u, v)` in metres (u along the face's perimeter, v up from the building base), and `COLOR_0` with the
portable fallback colour (also written as the material `baseColorFactor`). The glTF extension
`HELIX_materials_city {kind: "facade", version: 1}` is listed in `extensionsUsed`, never in `extensionsRequired`, so a
runtime that ignores it draws a coloured mass.

```
x = family(6) << 10 | seed(10)
y = groundType(2) << 14 | floorHeightCm(10) << 4 | groundExtra(4, quarter metres)
z = bayWidthCm(10) << 6 | windowRatio(6, of 63)
w = heightM(8) << 8 | tint(8)
```

Status: the contract belongs to the engine lane `city-materials` (engine PR #736, `systems/scene/src/materials/city/params.ts`,
published as `@helix/scene/city-materials`). It had not merged to the engine's helix3 when this landed, so
`src/city/buildings/facade.ts` carries a local replica of exactly `packFacade`/`unpackFacade`, the 20 base family names
and their wall, roof and glass looks, `GROUND_TYPE`, the tint palette and `facadeFallbackColor`. It was diffed against
PR #736 at `092f5759`: the packing, the family order, the attribute and extension names and the fallback colours agree
exactly over 11,440 sampled inputs. When the engine contract merges, it wins; replace the replica with the import.

Style per building: `style.family` (a base family name) wins, else `style.material` picks the family set, else height and
use do (offices of 30 m and up and any 60 m tower lean to glass and ribbon; residential brick and render; industrial
warehouse; civic limestone). A deterministic hash of the building id then picks the family within the set, the seed, tint,
bay width and window ratio. `style.facadeColour` (hex) is honoured as the fallback colour.

Ground floors: a face gets `groundType = STOREFRONT` when a shop POI sits within 15 m on its outward side, or when the
face looks onto a road (within 45 m) and the use is commercial or retail. On other street-facing faces an office, civic,
education or religious building gets a lobby and a residential one a residential ground floor; every other face is blank.

## Seating on the ground

Flat terrain uses its height. A DEM is seated on the minimum over the footprint (vertices, centroid, an interior grid). A
Copernicus-style DEM is a surface model (rooftops included), so `--ground-filter auto` applies a 3x3 minimum filter first
(a bare-earth proxy); `none` and `min3` force it. Walls go 0.4 m below the seat, so a building on a slope has no gap.
A CS2 mesh building takes `mesh.transform.position[1]` as its base.

## Mesh buildings

A building with a `mesh` pointer (a CS2 prefab, a vault package) keeps its model: the near level does not draw it, the
manifest lists it under `meshBuildings` (`id`, `cell`, `kind`, `ref`, `baseY`, `heightM`), and its box is always generated
as the box level and the far layer. The scene assembler mounts the model; this lane never touches it.

## Colliders

`HBC1`, little-endian, cell-local x and z: `'HBC1' | u32 count | records`. Box: `u8 0 | f32 cx cy cz | f32 hx hy hz |
f32 yawRad`. Hull prism (a polygon part whose box explains less than 90% of it): `u8 1 | u16 n | f32 y0 y1 | n x (f32 x z)`,
convex, counter-clockwise from above. `decodeColliders` (`src/city/buildings/colliders.ts`) reads both.

## Check

`helix city buildings check` decodes the GLBs it wrote and reports: buildings in source vs planned vs present at the box
level (the plan check; below `--min-pct`, default 99, exits 1 and lists the missing ids), hollow surfaces (an open edge
that is not closed by a coplanar deck or a crack under 12 cm), inverted faces (a triangle whose normal opposes the winding;
slivers under 2% of their longest edge are counted as degenerate, not inverted), and the far layer (every cell covered,
triangle sums equal the box level, per-triangle source index valid, bounds equal).

## Measured

| Source | Buildings | Time | Cells | Near (tri, bytes) | Box (tri, bytes) | Far (tri, bytes) |
| --- | --- | --- | --- | --- | --- | --- |
| SF core (OSM + Copernicus) | 14,580 | 3.4 s | 231, 16 far | 967,963, 22.99 MiB | 152,328, 5.89 MiB | 152,328, 5.07 MiB |
| Granit (CS2) | 13,985 (13,374 mesh) | 2.9 s | 470, 56 far | 6,110, 0.97 MiB | 143,030, 6.15 MiB | 143,030, 4.73 MiB |

Apple M-series, warm disk. Both `check` runs report 100.00% present, 0 hollow, 0 inverted.
