Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,230 @@
# OpenSpec Change: enterprise-heightmap-tiles
- **Change ID**: enterprise-heightmap-tiles
- **Package**: `@suaveplan/heightmap-tiles`
- **Category**: universal
- **Target path**: `universal/geo/heightmap-tiles`
- **Status**: IN PROGRESS
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/heightmap-tiles.md`
---
## Summary
Deliver `@suaveplan/heightmap-tiles` on the genesis branch from scratch at enterprise quality. The package provides a delta-encoded heightmap tile pyramid with adaptive bit depth: tile encoding/decoding (raw float32, delta-encoded uint16, uint8 at configurable bit depths), tile coordinate arithmetic (XYZ → bounding box, lat/lng → tile XYZ, tile overlap detection), a tile pyramid builder that down-samples tiles level by level via bilinear interpolation, a `HeightmapTileStore` interface with in-memory and file-system adapters, elevation lookup at arbitrary lat/lng by trilinear interpolation across tiles, contour-line extraction at configurable intervals, and a streaming tile import from GeoTIFF-style input buffers. Genesis adds structured errors, Zod schemas, OTel instrumentation, and property-based tests.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | `HeightmapError`; `HEIGHTMAP.*` error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock` |
| `@suaveplan/geo` (`workspace:^`) | `LatLng`, `BoundingBox`, coordinate utilities |
| `@suaveplan/serialize` (`workspace:^`) | Binary tile serialization (MessagePack profile) |
| `zod` (`catalog:forms`) | Schema validation |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### Core types
```ts
type BitDepth = 8 | 16 | 32
interface TileCoord {
x: number
y: number
z: number // zoom level
}
interface HeightmapTile {
coord: TileCoord
width: number // pixels; must be a power of 2
height: number
bitDepth: BitDepth
minElevation: number // metres
maxElevation: number
data: Uint8Array | Uint16Array | Float32Array
encoding: 'raw' | 'delta'
}
interface ElevationResult {
lat: number
lng: number
elevation: number // metres; NaN if no tile data
confidence: 'exact' | 'interpolated' | 'extrapolated'
}
```
### Codec
```ts
function encodeTile(tile: HeightmapTile, options?: EncodeOptions): Uint8Array
function decodeTile(data: Uint8Array): HeightmapTile
function deltaDecode(tile: HeightmapTile): HeightmapTile // converts delta → raw in place
function deltaEncode(tile: HeightmapTile): HeightmapTile // converts raw → delta
```
### Tile coordinate utilities
```ts
function latLngToTileCoord(lat: number, lng: number, zoom: number): TileCoord
function tileCoordToBoundingBox(coord: TileCoord): BoundingBox
function tileCoordToLatLng(coord: TileCoord): LatLng // NW corner
function tilesInBoundingBox(box: BoundingBox, zoom: number): TileCoord[]
function tileParent(coord: TileCoord): TileCoord
function tileChildren(coord: TileCoord): TileCoord[]
```
### `HeightmapTileStore` and pyramid
```ts
interface HeightmapTileStore {
get(coord: TileCoord): Promise<HeightmapTile | undefined>
put(tile: HeightmapTile): Promise<void>
delete(coord: TileCoord): Promise<void>
list(zoom: number, box?: BoundingBox): AsyncGenerator<TileCoord>
}
function createMemoryTileStore(): HeightmapTileStore
class TilePyramidBuilder {
constructor(store: HeightmapTileStore, options?: PyramidBuilderOptions)
addSourceTile(tile: HeightmapTile): Promise<void>
buildLevel(zoom: number, options?: BuildLevelOptions): Promise<void>
buildAll(minZoom: number, maxZoom: number): Promise<void>
}
function lookupElevation(
store: HeightmapTileStore,
lat: number,
lng: number,
zoom?: number
): Promise<ElevationResult>
function extractContours(
tile: HeightmapTile,
intervalMetres: number
): ContourLine[]
interface ContourLine {
elevation: number
points: LatLng[]
closed: boolean
}
```
### Error codes
```ts
type HeightmapErrorCode =
| 'HEIGHTMAP_TILE_NOT_FOUND'
| 'HEIGHTMAP_DECODE_FAILED'
| 'HEIGHTMAP_ENCODE_FAILED'
| 'HEIGHTMAP_INVALID_COORD'
| 'HEIGHTMAP_PYRAMID_FAILED'
| 'HEIGHTMAP_CONTOUR_FAILED'
```
---
## Genesis additions
1. **`HeightmapError`** extends `SuaveplanError` with six stable codes.
2. **Zod schemas** for `TileCoord`, `HeightmapTile`, `ElevationResult`, `ContourLine`, `EncodeOptions`, `PyramidBuilderOptions`.
3. **Adaptive bit depth** — encoder selects the minimum bit depth that preserves the tile's elevation range to within 0.1 m precision; this is overridable via `EncodeOptions.bitDepth`.
4. **Delta encoding** — adjacent pixel differences are stored as integer deltas, compressing well via the built-in binary serializer; decode restores original values exactly (lossless for int16/int8, lossy for float32 at bit depth < 32).
5. **Bilinear interpolation** — `lookupElevation` fetches the surrounding tile grid and performs bilinear interpolation over the four nearest pixels.
6. **OTel instrumentation** — span `heightmap.pyramid_build` with attribute `heightmap.zoom`; counter `heightmap.tile_encode_total`; histogram `heightmap.encode_duration_ms`.
7. **Property-based tests** — delta encode/decode round-trip for arbitrary float32 tiles; tile coordinate arithmetic (lat/lng → coord → bbox → contains lat/lng); contour elevation values are within `[minElevation, maxElevation]`.
---
## File layout
```text
universal/geo/heightmap-tiles/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
codec/
tile-codec/
tile-codec.ts
tile-codec.md
tile-codec.test.ts
index.ts
delta-codec/
delta-codec.ts
delta-codec.md
delta-codec.test.ts
index.ts
coords/
tile-coords/
tile-coords.ts
tile-coords.md
tile-coords.test.ts
index.ts
store/
tile-store/
tile-store.ts
tile-store.md
tile-store.types.ts
tile-store.test.ts
index.ts
memory-store/
memory-store.ts
memory-store.md
memory-store.test.ts
index.ts
pyramid/
pyramid-builder/
pyramid-builder.ts
pyramid-builder.md
pyramid-builder.test.ts
index.ts
elevation/
elevation-lookup/
elevation-lookup.ts
elevation-lookup.md
elevation-lookup.test.ts
index.ts
contour-extractor/
contour-extractor.ts
contour-extractor.md
contour-extractor.test.ts
index.ts
__benchmarks__/
heightmap-tiles.bench.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Downstream consumers**: `@suaveplan/osm-buildings` (terrain elevation for 3D building placement), any 3D mapping/terrain rendering service.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/geo`, `@suaveplan/serialize`.

View File

@@ -0,0 +1,75 @@
# Tasks: enterprise-heightmap-tiles
**Change ID**: enterprise-heightmap-tiles
**Package**: `@suaveplan/heightmap-tiles`
**Target path**: `universal/geo/heightmap-tiles`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/geo`, `@suaveplan/serialize`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold
- [ ] Create `universal/geo/heightmap-tiles/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
---
## 2. Types + errors
- [ ] `src/types/common.ts` — `TileCoord`, `BitDepth`, `HeightmapTile`, `ElevationResult`, `EncodeOptions`, `PyramidBuilderOptions`, `BuildLevelOptions`, `HeightmapTileStore` (interface), `ContourLine`.
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
- [ ] `src/error-codes.ts` — `HeightmapErrorCode` (6 codes), metadata, register, eager call.
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas.
---
## 3. Core modules
- [ ] **`src/coords/tile-coords/`** — `latLngToTileCoord`, `tileCoordToBoundingBox`, `tileCoordToLatLng`, `tilesInBoundingBox`, `tileParent`, `tileChildren`. Tests: known lat/lng → tile at zoom 10, bounding box round-trip, parent/children consistency at multiple zoom levels, `tilesInBoundingBox` returns correct count for small area.
- [ ] **`src/codec/delta-codec/`** — `deltaEncode(tile): HeightmapTile`: converts raw int16/int8 tile to delta-encoded (each cell = cell - previous); first cell = cell value. `deltaDecode(tile): HeightmapTile`: inverse. Both are lossless for int16/int8. Tests: encode/decode round-trip for flat tile (all zeros), random int16 array, verify delta values are smaller in magnitude for smooth terrain.
- [ ] **`src/codec/tile-codec/`** — `encodeTile(tile, options?): Uint8Array`: serialises header (coord, dimensions, bitDepth, min/maxElevation, encoding) then data via `@suaveplan/serialize` MessagePack profile. `decodeTile(data): HeightmapTile`. Tests: encode/decode round-trip for 256×256 uint16 tile, float32 tile, bit depth selection.
- [ ] **`src/store/memory-store/`** — `createMemoryTileStore(): HeightmapTileStore`: `get`/`put`/`delete`/`list` backed by a `Map<string, HeightmapTile>` (key = `z/x/y`). Tests: CRUD, list by zoom, list with bounding box filter.
- [ ] **`src/pyramid/pyramid-builder/`** — `TilePyramidBuilder(store, options)`: `addSourceTile(tile)`: stores at natural zoom; `buildLevel(zoom)`: for each tile at `zoom+1`, generates parent by bilinear down-sampling the 4 children (or nearest available); `buildAll(minZoom, maxZoom)`. Tests: single source tile at zoom 12 → can build zoom 11 and 10; bilinear average matches expected value for flat 4-cell grid.
- [ ] **`src/elevation/elevation-lookup/`** — `lookupElevation(store, lat, lng, zoom?)`: fetches tile at computed coord + 3 neighbours; bilinear interpolation from 4 nearest pixels. Returns `ElevationResult`. Tests: exact pixel hit → `confidence: 'exact'`, between pixels → `confidence: 'interpolated'`, no tile → `elevation: NaN`.
- [ ] **`src/elevation/contour-extractor/`** — `extractContours(tile, intervalMetres): ContourLine[]`: marching-squares algorithm over tile grid; groups adjacent edge crossings into polylines; closes loops. Tests: flat tile → no contours, slope tile → contours at expected elevations, closed contour for circular hill shape.
---
## 4. OTel instrumentation
- [ ] Span `heightmap.pyramid_build` with attribute `heightmap.zoom`; counter `heightmap.tile_encode_total`; histogram `heightmap.encode_duration_ms`.
---
## 5. Property-based tests (`tests/property.test.ts`)
- [ ] Delta encode/decode round-trip: for arbitrary `Int16Array` of length 256, `deltaDecode(deltaEncode(tile)).data` equals original.
- [ ] Tile coordinate arithmetic: `latLngToTileCoord(tileCoordToLatLng(coord), coord.z)` returns same coord for arbitrary valid coords.
- [ ] Contour bounds: all elevation values in `ContourLine[]` from `extractContours(tile, interval)` lie within `[tile.minElevation, tile.maxElevation]`.
---
## 6. Benchmarks (`src/__benchmarks__/heightmap-tiles.bench.ts`)
- [ ] `encodeTile` for 256×256 float32 tile.
- [ ] `decodeTile` for same.
- [ ] `extractContours` for 256×256 tile with 10 m interval.
---
## 7. Docs + verify
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/heightmap-tiles` — green.
- [ ] `bunx turbo test:coverage --filter=@suaveplan/heightmap-tiles` — 100%.
- [ ] `bun scripts/publish.ts --package @suaveplan/heightmap-tiles`.
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-heightmap-tiles/`.