From 0e7b7b33d2bb1e1d40c15e30755b6e05343aaca4 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 16 Nov 2026 21:07:02 +0100 Subject: [PATCH 01/11] core: terrain tiles, terrain breaks and ramps as node kinds, and the ground they make For discussion, not for merge: the lab's terrain work cut onto main, first layer. Three node kinds join AnyNode, each a stored-scene format to agree on: - terrain-tile: a 32 m tile of 65 x 65 quantized height samples (base64 Int16), child of the site; authored ground is written as tiles, not into site.terrain. - terrain-break: a vertical boundary in site XZ metres (cliff, retaining or soil), open straight line or convex CCW ring, numeric or 'ground' sides; strict mutations, relation checks refuse crossing or touching breaks. - ramp: a site-owned centreline ramp with endpoint heights and a cut-and-fill receipt (terrainEffect) the ground can be restored from. Slab gains an optional terrainMode ('flat' | 'draped'): a draped outdoor surface follows the ground, its elevation read as clearance. The terrain authority reads one ground from the legacy field, the tiles, the breaks, the ramps' cuts and a continuation past the field; previews are made once per edit. The spatial grid, stair rise and floor-placed elevation read a draped slab's height at the point. A floor plate put back under its own underside moves whole and is never stored thinner than a slab. Taken from the lab line because terrain needs them: createSceneSpatialGrid (a 5-line helper over createSnapshotSpatialGrid), getWallTopLowest in services/storey, and live-previews moved from store/ to lib/ so the terrain source reads it without loading the store. Co-Authored-By: Claude Opus 5.5 --- .../core/src/contracts/reference-inventory.ts | 18 + .../spatial-grid/floor-placed-elevation.ts | 18 +- .../spatial-grid/spatial-grid-manager.ts | 215 ++++- .../hooks/spatial-grid/spatial-grid-sync.ts | 82 +- packages/core/src/index.ts | 65 +- .../terrain-lag-golden-sides.json | 1 + .../lib/__fixtures__/terrain-lag-golden.json | 1 + .../lib/__fixtures__/terrain-lag-scenes.ts | 206 +++++ packages/core/src/lib/cutter-host.ts | 6 +- .../core/src/lib/floor-construction-lift.ts | 9 + .../core/src/lib/floor-foundation-datum.ts | 22 +- packages/core/src/lib/floor-intent-changes.ts | 4 +- .../src/lib/floor-plate-thickness.test.ts | 82 ++ packages/core/src/lib/grade-standing.test.ts | 70 +- packages/core/src/lib/grade-standing.ts | 42 +- packages/core/src/lib/item-slab-support.ts | 21 +- .../core/src/{store => lib}/live-previews.ts | 0 packages/core/src/lib/ramp-facts.ts | 320 +++++++ packages/core/src/lib/ramp-terrain.ts | 338 +++++++ packages/core/src/lib/ramp.ts | 412 +++++++++ packages/core/src/lib/slab-terrain.test.ts | 273 ++++++ packages/core/src/lib/slab-terrain.ts | 59 ++ packages/core/src/lib/terrain-authority.ts | 831 ++++++++++++++++++ packages/core/src/lib/terrain-bounds.test.ts | 76 ++ .../core/src/lib/terrain-break-validation.ts | 40 + packages/core/src/lib/terrain-breaks.test.ts | 623 +++++++++++++ packages/core/src/lib/terrain-breaks.ts | 537 +++++++++++ packages/core/src/lib/terrain-brush.test.ts | 27 + packages/core/src/lib/terrain-brush.ts | 15 +- packages/core/src/lib/terrain-codec.ts | 2 + .../core/src/lib/terrain-contours.test.ts | 58 ++ packages/core/src/lib/terrain-contours.ts | 76 +- .../core/src/lib/terrain-field-extent.test.ts | 109 +++ packages/core/src/lib/terrain-field-extent.ts | 65 ++ packages/core/src/lib/terrain-field.ts | 195 +++- packages/core/src/lib/terrain-hollows.ts | 167 ++++ .../core/src/lib/terrain-lag-equality.test.ts | 65 ++ .../core/src/lib/terrain-ramp-cut.test.ts | 235 +++++ packages/core/src/lib/terrain-ramp-cut.ts | 97 ++ packages/core/src/lib/terrain-raycast.ts | 94 +- .../core/src/lib/terrain-source-cache.test.ts | 88 ++ .../core/src/lib/terrain-source-persisted.ts | 111 ++- packages/core/src/lib/terrain-source.test.ts | 9 +- packages/core/src/lib/terrain-source.ts | 46 +- .../core/src/lib/terrain-support-query.ts | 45 +- packages/core/src/lib/terrain-support.test.ts | 18 + packages/core/src/lib/terrain-support.ts | 14 +- packages/core/src/lib/terrain-tile-changes.ts | 18 + packages/core/src/lib/terrain-tile-write.ts | 174 ++++ packages/core/src/lib/terrain-tiles.test.ts | 302 +++++++ packages/core/src/lib/terrain-tiles.ts | 52 ++ packages/core/src/procedural-items/query.ts | 11 +- .../core/src/registry/validate-relations.ts | 2 + packages/core/src/runtime/scene-runtime.ts | 2 +- .../src/schema/__fixtures__/node-fixtures.ts | 19 + .../core/src/schema/host-children.test.ts | 5 +- packages/core/src/schema/index.ts | 10 + packages/core/src/schema/nodes/ramp.ts | 43 + packages/core/src/schema/nodes/slab.ts | 9 +- .../core/src/schema/nodes/terrain-break.ts | 45 + .../core/src/schema/nodes/terrain-tile.ts | 23 + packages/core/src/schema/types.ts | 6 + packages/core/src/services/storey.ts | 16 + .../actions/node-update-children.test.ts | 13 + packages/core/src/store/derived-node-guard.ts | 8 +- .../src/store/terrain-break-mutations.test.ts | 201 +++++ .../core/src/store/use-live-node-overrides.ts | 2 +- packages/core/src/store/use-live-terrain.ts | 26 +- .../core/src/systems/document-reconcile.ts | 2 +- .../src/systems/stair/stair-base-elevation.ts | 7 +- .../src/systems/stair/stair-rise-query.ts | 26 +- 71 files changed, 6759 insertions(+), 170 deletions(-) create mode 100644 packages/core/src/lib/__fixtures__/terrain-lag-golden-sides.json create mode 100644 packages/core/src/lib/__fixtures__/terrain-lag-golden.json create mode 100644 packages/core/src/lib/__fixtures__/terrain-lag-scenes.ts create mode 100644 packages/core/src/lib/floor-plate-thickness.test.ts rename packages/core/src/{store => lib}/live-previews.ts (100%) create mode 100644 packages/core/src/lib/ramp-facts.ts create mode 100644 packages/core/src/lib/ramp-terrain.ts create mode 100644 packages/core/src/lib/ramp.ts create mode 100644 packages/core/src/lib/slab-terrain.test.ts create mode 100644 packages/core/src/lib/slab-terrain.ts create mode 100644 packages/core/src/lib/terrain-authority.ts create mode 100644 packages/core/src/lib/terrain-bounds.test.ts create mode 100644 packages/core/src/lib/terrain-break-validation.ts create mode 100644 packages/core/src/lib/terrain-breaks.test.ts create mode 100644 packages/core/src/lib/terrain-breaks.ts create mode 100644 packages/core/src/lib/terrain-contours.test.ts create mode 100644 packages/core/src/lib/terrain-field-extent.test.ts create mode 100644 packages/core/src/lib/terrain-field-extent.ts create mode 100644 packages/core/src/lib/terrain-hollows.ts create mode 100644 packages/core/src/lib/terrain-lag-equality.test.ts create mode 100644 packages/core/src/lib/terrain-ramp-cut.test.ts create mode 100644 packages/core/src/lib/terrain-ramp-cut.ts create mode 100644 packages/core/src/lib/terrain-source-cache.test.ts create mode 100644 packages/core/src/lib/terrain-tile-changes.ts create mode 100644 packages/core/src/lib/terrain-tile-write.ts create mode 100644 packages/core/src/lib/terrain-tiles.test.ts create mode 100644 packages/core/src/lib/terrain-tiles.ts create mode 100644 packages/core/src/schema/nodes/ramp.ts create mode 100644 packages/core/src/schema/nodes/terrain-break.ts create mode 100644 packages/core/src/schema/nodes/terrain-tile.ts create mode 100644 packages/core/src/store/terrain-break-mutations.test.ts diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 9bbccb342f..dae007790c 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -221,6 +221,24 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ remaps: ['clone-scene-graph'], note: 'Only the whole-graph clone remaps `dormerId`.', }), + ...(['startTargetId', 'endTargetId'] as const).map((path) => + row({ + kind: 'ramp', + path, + ...policy('node', 'connection', 'freeze', 'strip'), + targetKinds: ['door', 'level'], + remaps: ['clone-scene-graph'], + note: 'The modeled endpoint a ramp is measured against, not its host. Missing targets remain unmatched diagnostics; the authored profile stays in place.', + }), + ), + row({ + kind: 'ramp', + path: 'terrainEffect.siteId', + ...policy('node', 'internal', 'drop', 'strip'), + targetKinds: ['site'], + remaps: ['clone-scene-graph'], + note: 'The Site whose ground this grading receipt can restore. The receipt is scene-local ownership, not reusable preset content.', + }), row({ kind: 'item', path: 'blockFaceId', diff --git a/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts b/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts index 38e685e0fd..2968847917 100644 --- a/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts +++ b/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts @@ -7,7 +7,7 @@ import type { FloorPlacedFootprintContext, FloorPlacedFootprintsResolver, } from '../../registry/types' -import type { AnyNode, AnyNodeId, SlabNode } from '../../schema' +import type { AnyNode, AnyNodeId } from '../../schema' import { getFloorPlacedFootprints } from './floor-placed-footprints' export { getFloorPlacedFootprints } from './floor-placed-footprints' @@ -119,6 +119,7 @@ export function getFloorPlacedElevation({ // Skipped entirely under a pointer cap: the cursor, not the stored // host, decides the target surface during a drag. const supportSlabId = (effectiveNode as { supportSlabId?: string | null }).supportSlabId + const anchor: [number, number] = [position[0], position[2]] if (maxElevation == null && supportSlabId) { if (supportSlabId === GROUND_SUPPORT_ID) return groundLift() const host = nodes[supportSlabId] @@ -130,16 +131,15 @@ export function getFloorPlacedElevation({ footprint.position ?? position, footprint.dimensions, footprint.rotation, + anchor, ) - .map((candidate) => nodes[candidate.slabId]) - .filter( - (candidate): candidate is SlabNode => - candidate?.type === 'slab' && candidate.plateRole === 'platform', - ) - .sort((a, b) => b.elevation - a.elevation) + .filter((candidate) => { + const slab = nodes[candidate.slabId] + return slab?.type === 'slab' && slab.plateRole === 'platform' + }) const covering = coverings[0] if (covering) - return onFloor(covering.id, covering.elevation, footprint.position ?? position) + return onFloor(covering.slabId, covering.elevation, footprint.position ?? position) } const hosted = activeSpatialGrid().getHostSlabElevationForFootprint( resolvedLevelId, @@ -147,6 +147,7 @@ export function getFloorPlacedElevation({ footprint.position ?? position, footprint.dimensions, footprint.rotation, + anchor, ) if (hosted !== null) return onFloor(supportSlabId, hosted, footprint.position ?? position) } @@ -170,6 +171,7 @@ export function getFloorPlacedElevation({ footprint.dimensions, footprint.rotation, maxElevation, + anchor, ) const elevation = support.slabId === null diff --git a/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts b/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts index eaec68202d..9e020e6157 100644 --- a/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts +++ b/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts @@ -2,6 +2,12 @@ import { liftedManualSlab } from '../../lib/floor-construction-lift' import { selectSlabSupportForItem, slabSupportsItemFootprint } from '../../lib/item-slab-support' import { type PlanAabb, planFootprintAABB, planFootprintCorners } from '../../lib/plan-footprint' import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import { + type SlabTerrainFrame, + slabTerrainFrameOf, + slabTerrainHeightAt, +} from '../../lib/slab-terrain' +import { surfaceHeightAt } from '../../lib/terrain-field' import { levelBaseElevationAt } from '../../lib/terrain-support' import { floorPlacedCollides, nodeRegistry } from '../../registry' import type { AnyNode, AnyNodeId, CeilingNode, ItemNode, SlabNode, WallNode } from '../../schema' @@ -140,6 +146,134 @@ function intervalsOverlap(minA: number, maxA: number, minB: number, maxB: number return minA < maxB - epsilon && maxA > minB + epsilon } +function insideSlab(x: number, z: number, polygon: [number, number][], slab: SlabNode) { + return ( + pointInPolygon(x, z, polygon) && + !(slab.holes ?? []).some((hole) => hole.length >= 3 && pointInPolygon(x, z, hole)) + ) +} + +/** Split the ray wherever its plan point enters/leaves the footprint or a hole. */ +function slabRayIntervals( + origin: [number, number, number], + direction: [number, number, number], + polygon: [number, number][], + slab: SlabNode, +): Array<[number, number]> { + const [ox, , oz] = origin + const [dx, , dz] = direction + const cuts = new Set([0]) + for (const ring of [polygon, ...(slab.holes ?? [])]) { + for (const [i, a] of ring.entries()) { + const b = ring[(i + 1) % ring.length] + if (!b) continue + const ex = b[0] - a[0] + const ez = b[1] - a[1] + const denominator = dx * ez - dz * ex + if (Math.abs(denominator) < 1e-12) { + if (Math.abs((a[0] - ox) * dz - (a[1] - oz) * dx) > 1e-9) continue + const lengthSquared = dx * dx + dz * dz + if (lengthSquared < 1e-18) continue + for (const [x, z] of [a, b]) { + const t = ((x - ox) * dx + (z - oz) * dz) / lengthSquared + if (t >= 0) cuts.add(t) + } + continue + } + const t = ((a[0] - ox) * ez - (a[1] - oz) * ex) / denominator + const u = ((a[0] - ox) * dz - (a[1] - oz) * dx) / denominator + if (t >= 0 && u >= 0 && u <= 1) cuts.add(t) + } + } + const sorted = [...cuts].sort((a, b) => a - b) + const intervals: Array<[number, number]> = [] + for (const [i, start] of sorted.entries()) { + const end = sorted[i + 1] + if (end === undefined || end <= start) continue + const t = (start + end) / 2 + if (insideSlab(ox + dx * t, oz + dz * t, polygon, slab)) intervals.push([start, end]) + } + return intervals +} + +function addTerrainRayCuts( + cuts: Set, + origin: number, + direction: number, + gridOrigin: number, + spacing: number, + count: number, + start: number, + end: number, +) { + if (Math.abs(direction) < 1e-12) return + const first = (origin + direction * start - gridOrigin) / spacing + const last = (origin + direction * end - gridOrigin) / spacing + const low = Math.max(0, Math.ceil(Math.min(first, last))) + const high = Math.min(count - 1, Math.floor(Math.max(first, last))) + for (let i = low; i <= high; i++) { + const t = (gridOrigin + i * spacing - origin) / direction + if (t > start && t < end) cuts.add(t) + } +} + +function drapedSlabRayHit( + slab: SlabNode, + frame: SlabTerrainFrame, + polygon: [number, number][], + origin: [number, number, number], + direction: [number, number, number], +): { t: number; elevation: number } | null { + const [ox, oy, oz] = origin + const [dx, dy, dz] = direction + const [sx, sz] = frame.toSite(ox, oz) + const [nextX, nextZ] = frame.toSite(ox + dx, oz + dz) + const siteDx = nextX - sx + const siteDz = nextZ - sz + const height = (t: number) => + (frame.field ? surfaceHeightAt(frame.field, sx + siteDx * t, sz + siteDz * t) : 0) - + frame.baseY + + slab.elevation + if (Math.hypot(dx, dz) < 1e-12) { + if (Math.abs(dy) < 1e-12 || !insideSlab(ox, oz, polygon, slab)) return null + const elevation = height(0) + const t = (elevation - oy) / dy + return t > 0 ? { t, elevation } : null + } + for (const [start, end] of slabRayIntervals(origin, direction, polygon, slab)) { + const cuts = new Set([start, end]) + const field = frame.field + if (field) { + addTerrainRayCuts(cuts, sx, siteDx, field.origin[0], field.spacing, field.cols, start, end) + addTerrainRayCuts(cuts, sz, siteDz, field.origin[1], field.spacing, field.rows, start, end) + addTerrainRayCuts( + cuts, + sx + sz, + siteDx + siteDz, + field.origin[0] + field.origin[1], + field.spacing, + field.cols + field.rows - 1, + start, + end, + ) + } + const sorted = [...cuts].sort((a, b) => a - b) + // Between grid lines/diagonals the clamped terrain sample is affine. + // Solving each segment avoids missing a later hit after a hole or an earlier hit off-slab. + for (const [i, a] of sorted.entries()) { + const b = sorted[i + 1] + if (b === undefined) continue + const gapA = oy + dy * a - height(a) + const gapB = oy + dy * b - height(b) + if (gapA !== 0 && gapB !== 0 && gapA > 0 === gapB > 0) continue + const t = gapA === 0 ? a : gapB === 0 ? b : a + ((b - a) * gapA) / (gapA - gapB) + if (t > 0 && insideSlab(ox + dx * t, oz + dz * t, polygon, slab)) + return { t, elevation: height(t) } + } + } + return null +} + function resolveNodeLevelId(node: AnyNode, nodes: Record): string { if (node.type === 'level') return node.id @@ -188,7 +322,7 @@ export type ItemSlabSupport = { export type PointedSupportSurface = ItemSlabSupport & { /** - * Level-local XZ where the ray meets the pointed surface's plane, or + * Level-local XZ where the ray meets the pointed surface, or * null when the ray never reaches it (grazing / aimed above the base). * This is the plan point the pointer actually indicates: unlike a grid * event-plane hit — whose XZ shifts with whatever height the event @@ -328,6 +462,20 @@ export class SpatialGridManager { return true } + private terrainSource(): 'persisted' | 'live' { + return this.source.terrain() === undefined ? 'persisted' : 'live' + } + + private slabElevationAt(slab: SlabNode, anchor: readonly [number, number]): number { + return slabTerrainHeightAt( + slab, + this.source.nodes(), + anchor[0], + anchor[1], + this.terrainSource(), + ) + } + private getFloorGrid(levelId: string): SpatialGrid { if (!this.floorGrids.has(levelId)) { this.floorGrids.set(levelId, new SpatialGrid({ cellSize: this.cellSize })) @@ -839,10 +987,12 @@ export class SpatialGridManager { const slabMap = this.slabsByLevel.get(levelId) if (!slabMap) return 0 - let maxElevation = 0 + let maxElevation: number | undefined for (const stored of slabMap.values()) { const slab = this.effectiveSlabRecord(stored) - if (slab.polygon.length >= 3 && pointInPolygon(x, z, slab.polygon)) { + const polygon = + slab.terrainMode === 'draped' ? this.getRenderedSlabPolygon(levelId, slab) : slab.polygon + if (polygon.length >= 3 && pointInPolygon(x, z, polygon)) { // Check if point is in any hole let inHole = false const holes = slab.holes || [] @@ -854,14 +1004,17 @@ export class SpatialGridManager { } if (!inHole) { - const elevation = slab.elevation ?? 0.05 - if (elevation > maxElevation) { + const sampled = this.slabElevationAt(slab, [x, z]) + // Legacy flat queries retain their zero floor; draped tops can sit + // below the level origin after the site/building frame conversion. + const elevation = slab.terrainMode === 'draped' ? sampled : Math.max(0, sampled) + if (maxElevation === undefined || elevation > maxElevation) { maxElevation = elevation } } } } - return maxElevation + return maxElevation ?? 0 } /** @@ -886,6 +1039,9 @@ export class SpatialGridManager { * applies). Returns `{ elevation: 0, slabId: null }` when nothing * overlaps. * + * Heights use the node's anchor XZ, not footprint extrema. Composite callers + * pass the same `anchor` for each footprint so their parts stay rigid. + * * `maxElevation` is the pointer-decided cap: when set, only slabs whose * walking surface sits at or below `maxElevation + * SUPPORT_ELEVATION_EPSILON` may win — a deck hanging above the surface @@ -897,6 +1053,7 @@ export class SpatialGridManager { dimensions: [number, number, number], rotation: [number, number, number], maxElevation?: number | null, + anchor: readonly [number, number] = [position[0], position[2]], ): ItemSlabSupport { const slabMap = this.slabsByLevel.get(levelId) if (!slabMap) return { elevation: 0, slabId: null } @@ -905,22 +1062,22 @@ export class SpatialGridManager { Array.from(slabMap.values(), (slab) => this.effectiveSlabRecord(slab)), { position, dimensions, rotation }, (slab) => this.getRenderedSlabPolygon(levelId, slab), - { maxElevation }, + { maxElevation, elevationOf: (slab) => this.slabElevationAt(slab, anchor) }, ) return winner - ? { elevation: winner.elevation ?? 0.05, slabId: winner.id } + ? { elevation: this.slabElevationAt(winner, anchor), slabId: winner.id } : { elevation: 0, slabId: null } } /** * The walking surface the pointer actually points at: the nearest slab - * plane the ray crosses INSIDE that slab's rendered polygon (hole veto + * surface the ray crosses INSIDE that slab's rendered polygon (hole veto * applies), or the level base (`elevation: 0, slabId: null`) when it * crosses none. Ray origin/direction are level-local. Deliberately a * point test, not a footprint test — it answers "which surface is under * the cursor", which then caps the footprint election so a deck hanging * above the aimed-at floor never lifts the placement. `point` is the - * ray's crossing of that surface's plane — the stable plan point + * ray's crossing of that surface — the stable plan point * callers should elect/preview at (see {@link PointedSupportSurface}). */ getPointedSupportSurface( @@ -931,29 +1088,28 @@ export class SpatialGridManager { const slabMap = this.slabsByLevel.get(levelId) const [ox, oy, oz] = rayOrigin const [dx, dy, dz] = rayDirection - if (Math.abs(dy) < 1e-9) return { elevation: 0, slabId: null, point: null } - let best: { t: number; elevation: number; slabId: string } | null = null if (slabMap) { for (const stored of slabMap.values()) { const slab = this.effectiveSlabRecord(stored) if (slab.polygon.length < 3) continue + const rendered = this.getRenderedSlabPolygon(levelId, slab) + if (rendered.length < 3) continue + if (slab.terrainMode === 'draped') { + const frame = slabTerrainFrameOf(slab, this.source.nodes(), this.terrainSource()) + if (!frame) continue + const hit = drapedSlabRayHit(slab, frame, rendered, rayOrigin, rayDirection) + if (hit && (!best || hit.t < best.t)) best = { ...hit, slabId: slab.id } + continue + } + if (Math.abs(dy) < 1e-9) continue const elevation = slab.elevation ?? 0.05 const t = (elevation - oy) / dy if (t <= 0) continue if (best && t >= best.t) continue const x = ox + dx * t const z = oz + dz * t - const rendered = this.getRenderedSlabPolygon(levelId, slab) - if (rendered.length < 3 || !pointInPolygon(x, z, rendered)) continue - let inHole = false - for (const hole of slab.holes || []) { - if (hole.length >= 3 && pointInPolygon(x, z, hole)) { - inHole = true - break - } - } - if (inHole) continue + if (!insideSlab(x, z, rendered, slab)) continue best = { t, elevation, slabId: slab.id } } } @@ -964,7 +1120,7 @@ export class SpatialGridManager { point: [ox + dx * best.t, oz + dz * best.t], } } - const tBase = -oy / dy + const tBase = Math.abs(dy) < 1e-9 ? -1 : -oy / dy return { elevation: 0, slabId: null, @@ -983,6 +1139,7 @@ export class SpatialGridManager { position: [number, number, number], dimensions: [number, number, number], rotation: [number, number, number], + anchor: readonly [number, number] = [position[0], position[2]], ): SlabSupportCandidate[] { const slabMap = this.slabsByLevel.get(levelId) if (!slabMap) return [] @@ -991,7 +1148,7 @@ export class SpatialGridManager { for (const stored of slabMap.values()) { const slab = this.effectiveSlabRecord(stored) if (!this.slabSupportsFootprint(levelId, slab, position, dimensions, rotation)) continue - candidates.push({ slabId: slab.id, elevation: slab.elevation ?? 0.05 }) + candidates.push({ slabId: slab.id, elevation: this.slabElevationAt(slab, anchor) }) } candidates.sort( (a, b) => @@ -1014,12 +1171,13 @@ export class SpatialGridManager { position: [number, number, number], dimensions: [number, number, number], rotation: [number, number, number], + anchor: readonly [number, number] = [position[0], position[2]], ): number | null { const stored = this.slabsByLevel.get(levelId)?.get(slabId) if (!stored) return null const slab = this.effectiveSlabRecord(stored) if (!this.slabSupportsFootprint(levelId, slab, position, dimensions, rotation)) return null - return slab.elevation ?? 0.05 + return this.slabElevationAt(slab, anchor) } /** @@ -1343,6 +1501,13 @@ export function createSnapshotSpatialGrid( return grid } +/** A manager indexed over a scene's nodes as given: what a check or a test reads support from. */ +export function createSceneSpatialGrid( + nodes: Readonly>, +): SpatialGridManager { + return createSnapshotSpatialGrid(() => nodes as Record, resolveNodeLevelId) +} + type NodesStore = { getState(): { nodes: Record } } const supportIndexes = new WeakMap< object, diff --git a/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts b/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts index 4e4d8ee11a..b0f5b19156 100644 --- a/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts +++ b/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts @@ -54,10 +54,52 @@ export function initSpatialGridSync(): () => void { if (bulkSlabs) markAllSlabDependents(state.nodes, markDirty) const changedSlabContextLevels = new Set() const changedRoomSupportLevels = new Set() + let terrainFrameChanged = false const checkSlabContext = (id: string) => { const previous = prevState.nodes[id as AnyNodeId] const next = state.nodes[id as AnyNodeId] if (previous === next) return + if ( + (previous?.type === 'terrain-break' || next?.type === 'terrain-break') && + (previous?.type !== 'terrain-break' || + next?.type !== 'terrain-break' || + previous.parentId !== next.parentId || + previous.line !== next.line || + previous.left !== next.left || + previous.right !== next.right) + ) + terrainFrameChanged = true + if ( + (previous?.type === 'terrain-tile' || next?.type === 'terrain-tile') && + (previous?.type !== 'terrain-tile' || + next?.type !== 'terrain-tile' || + previous.parentId !== next.parentId || + previous.ix !== next.ix || + previous.iz !== next.iz || + previous.step !== next.step || + previous.heights !== next.heights) + ) + terrainFrameChanged = true + if ( + (previous?.type === 'building' || next?.type === 'building') && + (previous?.type !== 'building' || + next?.type !== 'building' || + previous.parentId !== next.parentId || + previous.position !== next.position || + previous.rotation !== next.rotation || + previous.children !== next.children) + ) + terrainFrameChanged = true + if ( + (previous?.type === 'level' || next?.type === 'level') && + (previous?.type !== 'level' || + next?.type !== 'level' || + previous.parentId !== next.parentId || + previous.height !== next.height || + previous.baseElevation !== next.baseElevation || + previous.level !== next.level) + ) + terrainFrameChanged = true const wallChanged = (previous?.type === 'wall' || next?.type === 'wall') && (previous?.type !== 'wall' || @@ -74,7 +116,8 @@ export function initSpatialGridSync(): () => void { next?.type !== 'slab' || previous.parentId !== next.parentId || previous.polygon !== next.polygon || - previous.elevation !== next.elevation) + previous.elevation !== next.elevation || + previous.terrainMode !== next.terrainMode) const roomChanged = (previous?.type === 'zone' || next?.type === 'zone') && (previous?.type !== 'zone' || @@ -187,11 +230,16 @@ export function initSpatialGridSync(): () => void { } } else if (node.type === 'slab' && prev.type === 'slab') { const supportChanged = + node.parentId !== prev.parentId || node.polygon !== prev.polygon || node.elevation !== prev.elevation || - node.holes !== prev.holes + node.holes !== prev.holes || + node.terrainMode !== prev.terrainMode if (supportChanged) { const levelId = resolveLevelId(node, state.nodes) + const previousLevelId = resolveLevelId(prev, prevState.nodes) + if (previousLevelId !== levelId) + spatialGridManager.handleNodeDeleted(node.id, node.type, previousLevelId) spatialGridManager.handleNodeUpdated(node, levelId) } if (!bulkSlabs) { @@ -248,6 +296,8 @@ export function initSpatialGridSync(): () => void { } } + if (terrainFrameChanged) markTerrainSupportDependents(state.nodes, markDirty) + // Unchanged slabs can lose an adopted wall band or a sibling seam. Their // stored polygons cannot identify objects standing on the former boundary. if (changedSlabContextLevels.size === 0) return @@ -331,7 +381,8 @@ export function countBulkSlabChanges( prev?.type !== 'slab' || (prev as SlabNode).polygon !== (node as SlabNode).polygon || (prev as SlabNode).elevation !== (node as SlabNode).elevation || - (prev as SlabNode).holes !== (node as SlabNode).holes + (prev as SlabNode).holes !== (node as SlabNode).holes || + (prev as SlabNode).terrainMode !== (node as SlabNode).terrainMode ) { count++ } @@ -430,14 +481,20 @@ export function markSlabChangeDependents( next.parentId !== previous.parentId || next.polygon !== previous.polygon || next.elevation !== previous.elevation || - next.holes !== previous.holes + next.holes !== previous.holes || + next.terrainMode !== previous.terrainMode // A slab's surface script is the surface what stands on the slab rests on. if (supportChanged || next.surfaceScript !== previous.surfaceScript) { markNodesOverlappingSlab(previous, nodes, markDirty, previousNodes) markNodesOverlappingSlab(next, nodes, markDirty) } - if (next.elevation !== previous.elevation) { + if ( + next.elevation !== previous.elevation || + (next.terrainMode ?? 'flat') !== (previous.terrainMode ?? 'flat') || + ((next.terrainMode === 'draped' || previous.terrainMode === 'draped') && + next.parentId !== previous.parentId) + ) { markDeckAttachedStairs(next.id, nodes, markDirty) } if ( @@ -482,6 +539,13 @@ export function markTerrainSupportDependents( nodes: Record, markDirty: (id: AnyNodeId) => void, ) { + const drapedSlabs = new Set() + const drapedLevels = new Set() + for (const node of Object.values(nodes)) { + if (node.type !== 'slab' || node.terrainMode !== 'draped') continue + drapedSlabs.add(node.id) + drapedLevels.add(resolveLevelId(node, nodes)) + } const plates = Object.values(nodes).filter( (node): node is SlabNode => node.type === 'slab' && @@ -530,7 +594,7 @@ export function markTerrainSupportDependents( for (const node of Object.values(nodes)) { if (node.type === 'slab') { // A deck's posts run down to the ground under each, on whatever storey it stands. - if (isDeckSlab(node, (id) => nodes[id])) { + if (isDeckSlab(node, (id) => nodes[id]) || node.terrainMode === 'draped') { markDirty(node.id) continue } @@ -565,6 +629,9 @@ export function markTerrainSupportDependents( continue } + if (node.type === 'stair' && node.deckSlabId && drapedSlabs.has(node.deckSlabId)) + markDirty(node.id) + const floorPlaced = nodeRegistry.get(node.type)?.capabilities?.floorPlaced if (!floorPlaced) { // A kind whose geometry builder resolved its own origin from the ground @@ -585,7 +652,8 @@ export function markTerrainSupportDependents( const parentId = node.parentId as AnyNodeId | null const parent = parentId ? nodes[parentId] : null if (parent && parent.type !== 'level') continue - if (!isGrade(resolveLevelId(node, nodes))) continue + const levelId = resolveLevelId(node, nodes) + if (!drapedLevels.has(levelId) && !isGrade(levelId)) continue markDirty(node.id) } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 96d9400714..5c8e1116ac 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,3 +1,8 @@ +import { setTerrainSceneSource } from './lib/terrain-source' +import terrainScene from './store/use-scene' + +setTerrainSceneSource(() => terrainScene.getState().nodes) + export type { PointAskPin, PointAskStatus, @@ -81,6 +86,7 @@ export { getFloorStackedPosition, } from './hooks/spatial-grid/floor-placed-elevation' export { + createSceneSpatialGrid, getWallBaseElevationForNodes, getWallEffectiveHeightForNodes, type PointedSupportSurface, @@ -397,7 +403,7 @@ export { nearestPointIn, resettledPosition, } from './lib/geometry-surfaces' -export { type LevelGradeStanding, levelGradeStanding } from './lib/grade-standing' +export { groundCovers, type LevelGradeStanding, levelGradeStanding } from './lib/grade-standing' export { type GroundLevel, groundLevelOf, levelUnderNamedGround } from './lib/ground-level' export { GROUND_SEAT_TOLERANCE, @@ -554,6 +560,28 @@ export { porchFramingSettings, } from './lib/porch-framing' export { type PorchPartMetadata, porchPartOf } from './lib/porch-framing-sync' +export { + type RampPoint, + type RampStation, + rampBounds, + rampCentrelineMaximumSlopePercent, + rampDefaultTransitionLength, + rampHeightAt, + rampLength, + rampMaximumSlopePercent, + rampOffsetPoint, + rampProjectPoint, + rampStations, + rampStepForSag, +} from './lib/ramp' +export { + type RampFacts, + type RampTargetMatch, + type RampTransitionFacts, + type RampWarning, + rampFacts, +} from './lib/ramp-facts' +export { planRampCreation, planRampEdit, planRampTerrain } from './lib/ramp-terrain' export { type EavePoint, eaveContains, @@ -666,6 +694,7 @@ export { slabPolygonContextFromGeometry, snapSlabEdgeToWallBand, } from './lib/slab-polygon' +export { type SlabTerrainFrame, slabTerrainFrameOf, slabTerrainHeightAt } from './lib/slab-terrain' export { deriveSlotId, isSlotMaterialName, @@ -703,6 +732,22 @@ export { type SceneStructureResult, type StructureIdFactory, } from './lib/structure-reconcile' +export { + TERRAIN_CONTEXT_HEIGHT, + TERRAIN_CONTINUATION_DISTANCE, + terrainContextHeightOf, + terrainPreviewField, +} from './lib/terrain-authority' +export { validateTerrainBreakRelations } from './lib/terrain-break-validation' +export { + type TerrainBreakSide, + terrainBreakFacts, + terrainBreakHeightAt, + terrainBreakIsClosed, + terrainBreakSideAt, + terrainBreaksOf, + validateTerrainBreak, +} from './lib/terrain-breaks' export { advanceStroke, type BrushSettings, @@ -711,6 +756,7 @@ export { brushHeightAt, DEFAULT_BRUSH_SETTINGS, detachStrokeAnchor, + diffuseHeights, highestOver, MIN_BRUSH_RADIUS_IN_SPACINGS, maxCoverage, @@ -745,9 +791,12 @@ export { quantize, sampleRangeOver, slopeAt, + storedHeightAt, surfaceHeightAt, type TerrainField, } from './lib/terrain-field' +export { fieldExtentForSite } from './lib/terrain-field-extent' +export { rampsGradingOf } from './lib/terrain-ramp-cut' export { raycastTerrain, type TerrainHit } from './lib/terrain-raycast' export { commitTerrainField, @@ -764,6 +813,20 @@ export { SITE_DATUM_Y, terrainSupportLift, } from './lib/terrain-support' +export { levelLocalToWorldXZ } from './lib/terrain-support-query' +export { planTerrainTileChanges } from './lib/terrain-tile-changes' +export { + planTerrainTileWrites, + type TerrainEditBounds, + type TerrainTileWrites, + terrainEditField, +} from './lib/terrain-tile-write' +export { + type TerrainNodes, + type TerrainSite, + terrainTilesOf, + tileFieldOf, +} from './lib/terrain-tiles' export { deriveUnit, type UnitDerivation, diff --git a/packages/core/src/lib/__fixtures__/terrain-lag-golden-sides.json b/packages/core/src/lib/__fixtures__/terrain-lag-golden-sides.json new file mode 100644 index 0000000000..9f861f0df2 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/terrain-lag-golden-sides.json @@ -0,0 +1 @@ +{"three rings, ground outside":[-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-1.438261124749673,-3.407184915563327,-2.4208125121453437,-0.49610172874538766,-4.474811416441655,-1.8876336255942376,-1.9531622221092535,-5.102769464458226,-1.053914428357973,-1.5218618732677194,-4.1479032589582685,-1.6369709874529574,-2.5436332389617675,-4.3078271656618865,-2.0659035845346945,-3.6320110272398947,-3.080597464406761,-1.5274719061098914,-3.198000000000001,-2.798,-2.6119999999999988,-2.7620000000000022,-3.2640000000000002,-3.9162404625212917,-1.158000000000002,-3.85,-3.7780000000000005,-1.8540000000000003,-4.1279999999999974,-3.3323061083698153,-1.3999999999999997,-5.361999999999998,-1.532,-1.7100000000000002,-4.476389398005921,-1.1720000000000002,-2.141999999999999,-5.016000000000002,-0.8620000000000008,-4.252,-3.556675286720736,-1.2380000000000002,-4.35,-3.7440000000000007,-1.1239999999999988,-4.198,-3.4322312519787825,-2.6439999999999984,-3.0860000000000003,-2.6020000000000003,-2.8680000000000003,-2.9007261534450772,-3.259999999999999,-2.9960000000000013,-2.370000000000001,-4.393999999999999,-2.64,-1.59920082105983,-5.545999999999999,-1.9940000000000009,-2.159999999999999,-4.556,-0.8620000000000019,-2.88318492409262,-4.712000000000001,-0.12600000000000056,-4.231999999999999,-4.37,-1.7956610024628756,-4.2059999999999995,-3.602000000000001,-1.5039999999999993,-5.023999999999999,-1.878,-2.4913309005656394,-4.154,-2.2499999999999996,-2.3019999999999996,-3.690000000000001,-2.406,-2.62080933551849,-2.226,-3.5940000000000003,-3.1200000000000006,-2.998,-3.3451607190299546,-2.046000000000001,-3.037999999999999,-4.632,-0.8780000000000003,-3.31,-4.490231390847951,-0.2639999999999996,-3.9899999999999993,-3.5460000000000025,-0.9200000000000003,-5.643999999999999,-4.841410460822431,-5.1789858723147475,-0.12526713483133564,-1.4370354938078682,-3.8015205178750175,-2.69,-3.2420000000000004,-2.722,-2.21,-3.684,-3.1,-4.274,-2.644,-2.846,-2.5739999999999994,-2.1619999999999995,-1.9380000000000002,-2.356,-3.64,-3.48,-1.662,-2.36,-1.5359999999999996,-4.722,-3.5,-1.248,0.056777343749999876,0,-3.8,-3.8,-4.448,-3.8,-4.65536,-3.8,-4.083600000000001,-3.8,-3.8,-3.34328,-3.8,-3.043,-3.8,-2.9784,-3.8,-3.8,-2.577,-3.8,-3.107,-3.8,-3.58033,-3.8,-3.8,-3.36,-3.8,-3.702,-3.8,-3.78071,-3.8,-3.8,-3.993,-3.8,-4.14967,-3.8,-4.29,-3.8,-3.8,-4.507,-3.8,-4.61522,-3.8,-5.0793,-3.8,-3.8,-5.32509,-3.8,-4.948,-3.04,-3.1108000000000002,-2.654999999999999,-3.029,-3.4196,-2.6995999999999998,-2.65,-3.7022000000000004,-3.4046000000000003,-4.29,-3.71,-2.9440000000000004,-3.6504000000000003,-3.73,-4.171199999999998,-4.133999999999999,-4.952000000000002,-4.8500000000000005,-4.722,-5.104800000000001,-5.07,-5.119999999999999,-5.1052,-5.106000000000001,-5.109999999999999,-5.0600000000000005,-5.097999999999999,-5.0732,-3.96,-4.0096,-1.5848000000000002,-1.6188000000000002,-1.7074000000000003,-1.0592000000000004,-0.98,-1.12,-1.0184000000000002,-1.437200000000001,-1.1296,-0.9915999999999998,-1.8676000000000001,-1.8800000000000001,-2.9488,-2.8868,-3.066,-3.0700000000000003,-3.092,-3.6,-0.8119999999999999,-3.6,-0.9295199999999999,-3.6,-3.6,-0.5099999999999999,-3.6,-1.03912,-3.6,-1.2448,-3.6,-3.6,-1.54,-3.6,-1.48776,-3.6,-1.8404,-3.6,-3.6,-2.36792,-3.6,-2.422,-3.6,-2.4576,-3.6,-3.6,-3.04728,-3.6,-2.478,-3.6,-2.1967999999999996,-3.6,-3.6,-2.876,-3.6,-2.0540000000000003,-3.6,-1.89368,-3.6,-3.6,-1.44,-3.6,-1.0732000000000002,-3.6,-0.9716,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-1.438261124749673,-3.407184915563327,-2.4208125121453437,-0.49610172874538766,-4.474811416441655,-1.8876336255942376,-1.9531622221092535,-5.102769464458226,-1.053914428357973,-1.5218618732677194,-4.1479032589582685,-1.6369709874529574,-2.5436332389617675,-4.3078271656618865,-2.0659035845346945,-3.6320110272398947,-3.080597464406761,-1.5274719061098914,-3.198000000000001,-2.798,-2.6119999999999988,-2.7620000000000022,-3.2640000000000002,-3.9162404625212917,-1.158000000000002,-3.85,-3.7780000000000005,-1.8540000000000003,-4.1279999999999974,-3.3323061083698153,-1.3999999999999997,-5.361999999999998,-1.532,-1.7100000000000002,-4.476389398005921,-1.1720000000000002,-2.141999999999999,-5.016000000000002,-0.8620000000000008,-4.252,-3.556675286720736,-1.2380000000000002,-4.35,-3.7440000000000007,-1.1239999999999988,-4.198,-3.4322312519787825,-2.6439999999999984,-3.0860000000000003,-4.7,-2.8680000000000003,-2.9007261534450772,-3.259999999999999,-2.9960000000000013,-2.370000000000001,-4.7,-2.64,-1.59920082105983,-5.545999999999999,-1.9940000000000009,-2.159999999999999,-4.556,-0.8620000000000019,-2.88318492409262,-4.712000000000001,-0.12600000000000056,-4.231999999999999,-4.37,-1.7956610024628756,-4.2059999999999995,-3.602000000000001,-1.5039999999999993,-5.023999999999999,-1.878,-2.4913309005656394,-4.154,-2.2499999999999996,-2.3019999999999996,-3.690000000000001,-2.406,-2.62080933551849,-2.226,-3.5940000000000003,-3.1200000000000006,-2.998,-3.3451607190299546,-2.046000000000001,-3.037999999999999,-4.632,-0.8780000000000003,-3.31,-4.490231390847951,-0.2639999999999996,-3.9899999999999993,-3.5460000000000025,-0.9200000000000003,-5.643999999999999,-4.841410460822431,-5.1789858723147475,-0.12526713483133564,-1.4370354938078682,-3.8015205178750175,-2.69,-3.2420000000000004,-2.722,-2.21,-3.684,-3.1,-4.274,-2.644,-2.846,-4.7,-2.1619999999999995,-1.9380000000000002,-2.356,-3.64,-3.48,-1.662,-2.36,-1.5359999999999996,-4.722,-3.5,-1.248,0.056777343749999876,0,-5.089999999999999,-4.89,-4.448,-4.7793600000000005,-4.65536,-4.096000000000002,-4.083600000000001,-3.20729,-3.2886200000000003,-3.34328,-3.0096000000000003,-3.043,-3.1310000000000002,-2.9784,-3.5201300000000004,-2.98439,-2.577,-3.1566,-3.107,-3.7291300000000005,-3.58033,-3.8729999999999998,-3.674,-3.36,-3.6486,-3.702,-3.7656499999999995,-3.78071,-4.027,-4.027,-3.993,-4.217409999999999,-4.14967,-4.352,-4.29,-4.132,-4.314,-4.507,-4.50623,-4.61522,-4.930499999999999,-5.0793,-4.86283,-5.03722,-5.32509,-4.878,-4.948,-4.7,-3.1108000000000002,-4.7,-4.7,-3.4196,-4.7,-2.65,-4.7,-3.4046000000000003,-4.7,-4.7,-2.9440000000000004,-4.7,-3.73,-4.7,-4.133999999999999,-4.7,-4.7,-4.722,-4.7,-5.07,-4.7,-5.1052,-4.7,-4.7,-5.0600000000000005,-4.7,-5.0732,-4.7,-4.0096,-4.7,-4.7,-1.7074000000000003,-4.7,-0.98,-4.7,-1.0184000000000002,-4.7,-4.7,-0.9915999999999998,-4.7,-1.8800000000000001,-4.7,-2.8868,-4.7,-4.7,-3.092,-3.6,-0.8119999999999999,-3.6,-0.9295199999999999,-3.6,-3.6,-0.5099999999999999,-3.6,-1.03912,-3.6,-1.2448,-3.6,-3.6,-1.54,-3.6,-1.48776,-3.6,-1.8404,-3.6,-3.6,-2.36792,-3.6,-2.422,-3.6,-2.4576,-3.6,-3.6,-3.04728,-3.6,-2.478,-3.6,-2.1967999999999996,-3.6,-3.6,-2.876,-3.6,-2.0540000000000003,-3.6,-1.89368,-3.6,-3.6,-1.44,-3.6,-1.0732000000000002,-3.6,-0.9716,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-1.438261124749673,-3.407184915563327,-2.4208125121453437,-0.49610172874538766,-4.474811416441655,-1.8876336255942376,-1.9531622221092535,-5.102769464458226,-1.053914428357973,-1.5218618732677194,-4.1479032589582685,-1.6369709874529574,-2.5436332389617675,-4.3078271656618865,-2.0659035845346945,-3.6320110272398947,-3.080597464406761,-1.5274719061098914,-3.198000000000001,-2.798,-2.6119999999999988,-2.7620000000000022,-3.2640000000000002,-3.9162404625212917,-1.158000000000002,-3.85,-3.7780000000000005,-1.8540000000000003,-4.1279999999999974,-3.3323061083698153,-1.3999999999999997,-5.361999999999998,-1.532,-1.7100000000000002,-4.476389398005921,-1.1720000000000002,-2.141999999999999,-5.016000000000002,-0.8620000000000008,-4.252,-3.556675286720736,-1.2380000000000002,-4.35,-3.7440000000000007,-1.1239999999999988,-4.198,-3.4322312519787825,-2.6439999999999984,-3.0860000000000003,-4.7,-2.8680000000000003,-2.9007261534450772,-3.259999999999999,-2.9960000000000013,-2.370000000000001,-4.7,-2.64,-1.59920082105983,-5.545999999999999,-1.9940000000000009,-2.159999999999999,-4.556,-0.8620000000000019,-2.88318492409262,-4.712000000000001,-0.12600000000000056,-4.231999999999999,-4.37,-1.7956610024628756,-4.2059999999999995,-3.602000000000001,-1.5039999999999993,-5.023999999999999,-1.878,-2.4913309005656394,-4.154,-2.2499999999999996,-2.3019999999999996,-3.690000000000001,-2.406,-2.62080933551849,-2.226,-3.5940000000000003,-3.1200000000000006,-2.998,-3.3451607190299546,-2.046000000000001,-3.037999999999999,-4.632,-0.8780000000000003,-3.31,-4.490231390847951,-0.2639999999999996,-3.9899999999999993,-3.5460000000000025,-0.9200000000000003,-5.643999999999999,-4.841410460822431,-5.1789858723147475,-0.12526713483133564,-1.4370354938078682,-3.8015205178750175,-2.69,-3.2420000000000004,-2.722,-2.21,-3.684,-3.1,-4.274,-2.644,-2.846,-4.7,-2.1619999999999995,-1.9380000000000002,-2.356,-3.64,-3.48,-1.662,-2.36,-1.5359999999999996,-4.722,-3.5,-1.248,0.056777343749999876,0,-3.8,-3.8,-4.448,-3.8,-4.65536,-3.8,-4.083600000000001,-3.8,-3.8,-3.34328,-3.8,-3.043,-3.8,-2.9784,-3.8,-3.8,-2.577,-3.8,-3.107,-3.8,-3.58033,-3.8,-3.8,-3.36,-3.8,-3.702,-3.8,-3.78071,-3.8,-3.8,-3.993,-3.8,-4.14967,-3.8,-4.29,-3.8,-3.8,-4.507,-3.8,-4.61522,-3.8,-5.0793,-3.8,-3.8,-5.32509,-3.8,-4.948,-4.7,-3.1108000000000002,-4.7,-4.7,-3.4196,-4.7,-2.65,-4.7,-3.4046000000000003,-4.7,-4.7,-2.9440000000000004,-4.7,-3.73,-4.7,-4.133999999999999,-4.7,-4.7,-4.722,-4.7,-5.07,-4.7,-5.1052,-4.7,-4.7,-5.0600000000000005,-4.7,-5.0732,-4.7,-4.0096,-4.7,-4.7,-1.7074000000000003,-4.7,-0.98,-4.7,-1.0184000000000002,-4.7,-4.7,-0.9915999999999998,-4.7,-1.8800000000000001,-4.7,-2.8868,-4.7,-4.7,-3.092,-1.01,-0.8119999999999999,-1.15272,-0.9295199999999999,-1.806,-1.0879999999999999,-0.5099999999999999,-1.26232,-1.03912,-1.486,-1.2448,-1.094,-1.288,-1.54,-1.4250399999999999,-1.48776,-1.766,-1.8404,-2.12712,-2.25784,-2.36792,-2.4000000000000004,-2.422,-2.194,-2.4576,-1.6364800000000006,-2.36056,-3.04728,-2.2176000000000005,-2.478,-1.8868,-2.1967999999999996,-1.36,-2.0900000000000003,-2.876,-2.102,-2.0540000000000003,-1.9579999999999997,-1.89368,-1.5499999999999998,-1.474,-1.44,-1.0856000000000001,-1.0732000000000002,-0.9739999999999999,-0.9716],"open break":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,-1.1347821555855508,0.3748270306409118,-0.8232398271161564,-1.8652094964054067,-0.08584300589251281,-0.19898296818406191,-1.5537161256199965,0.6972525036823319,-1.4111056624384617,-1.3660083091652517,-0.20905385713068372,-1.0837126371635404,-1.627783706254525,0.0008175139996963706,-2.426227614624253,-0.2449655601599132,-0.35843885504337936,-2.9272337884359505,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.137190375627886,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-2.8972027516055245,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-4.601028392089396,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-4.5154855153755,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.6530092996778234,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-2.450952319184876,-3.2039999999999984,-3.030000000000001,-2.390000000000001,-4.369999999999998,-2.6739999999999995,-1.0155449587294472,-5.545999999999999,-1.9940000000000009,-2.159999999999999,-4.556,-0.8620000000000019,-2.881572482635028,-4.712000000000001,-0.12600000000000056,-4.231999999999999,-4.37,-1.6526470270096019,-4.2059999999999995,-3.602000000000001,-1.5039999999999993,-5.023999999999999,-1.878,-2.491292569884013,-4.154,-2.2499999999999996,-2.3019999999999996,-3.690000000000001,-2.406,-2.6212013153897136,-2.226,-3.5940000000000003,-3.1200000000000006,-2.998,-3.3704224418427837,-2.046000000000001,-3.037999999999999,-4.632,-0.8780000000000003,-3.31,-4.501262227064304,-0.2639999999999996,-3.9899999999999993,-3.5460000000000025,-0.9200000000000003,-5.643999999999999,0.4822043929099511,-4.484334062174823,-1.3154510375600452,-0.2210319509616578,-0.1308147045033535,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.684,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.082,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-2.1619999999999995,-1.9380000000000002,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.64,-3.48,-1.662,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-1.5359999999999996,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.5,-1.248,0,0,-3.4288198364711477,-2.5326906974767107,-1.5584123719775265,-3.0707999999999998,-3.1699999999999995,-2.38,-2.2188,-2.6559999999999993,-3.0300000000000002,-3.314000000000001,-2.4264,-2.29],"open break, ground on its left":[-1.438261124749673,-3.407184915563327,-2.4208125121453437,-0.49610172874538766,-4.475098218267158,-1.8876336255942376,-1.9531622221092535,-5.102769464458226,-1.053914428357973,-1.5218618732677194,-4.1479032589582685,-1.6369709874529574,-2.5436332389617675,-4.3078271656618865,-2.0659035845346945,-3.6317068344344503,-3.080597464406761,-1.527619408273257,-3.198000000000001,-2.798,-2.6119999999999988,-2.7620000000000022,-3.2640000000000002,-3.9175178506213455,-1.158000000000002,-3.85,-3.7780000000000005,-1.8540000000000003,-4.1279999999999974,-3.3324496919133417,-1.3999999999999997,-5.361999999999998,-1.532,-1.7100000000000002,-4.501664992138324,-1.1720000000000002,-2.141999999999999,-5.016000000000002,-0.8620000000000008,-4.252,-3.568789693089158,-1.2380000000000002,-4.35,-3.7440000000000007,-1.1239999999999988,-4.198,-3.43313470703159,-2.6439999999999984,-3.0920000000000005,-2.436,-2.8680000000000003,-2.974523108195829,-3.259999999999999,-2.9960000000000013,-2.370000000000001,-4.315999999999999,-2.64,-2.572062459723186,-6.385999999999996,-1.739999999999998,-1.7199999999999995,-4.446000000000001,-1.0580000000000023,-2.0947148334196477,-5.476000000000011,0.3180000000000014,-5.823999999999992,-3.619999999999996,-1.4787522974823557,-5.804000000000002,-1.724,3.3480000000000034,-8.140000000000002,-2.64,-2.4930414822656033,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-1.8688882599517338,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-1.583456078048917,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-1.1437934716166354,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-4.841410460822431,-5.213552664210491,-0.12526713483133564,-2.4937488982750664,-3.8015205178750175,-2.69,-3.2420000000000004,-2.722,-2.21,-1.9939999999999993,-3.1,-4.274,-2.644,-2.846,-2.62,"refused: The covering terrain tile has no same-region source triangle for keep-ground.","refused: The covering terrain tile has no same-region source triangle for keep-ground.",-2.356,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-3.3400000000000007,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-2.36,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",-4.722,"refused: The covering terrain tile has no same-region source triangle for keep-ground.",0.9740000000000024,0.056777343749999876,0,-3.545462757418923,-3.062982404271713,-2.920383228569498,-3.1256,-3.1999999999999997,-2.33,-2.1936,-2.994000000000001,-3.102000000000001,-3.204000000000002,-2.4816000000000003,-2.3699999999999997,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5],"one ring, numeric both sides":[-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2],"legacy and a ring":[-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-4.155018192838953,-3.8322592278542866,-5.251745117187489,-6.249690429687501,-2.567990726433657,-2.930139048688315,-3.241696418975268,-3.4468261114948846,-3.986975043670653,-5.077410563430775,-1.8443617253048905,-2.747615368315709,-2.388689163572294,-3.331747880190437,-4.07416557763672,-1.259693131713871,-1.3714096491347985,-2.3513184221892605,-1.7242337923880793,-3.9922707609405426,-6.029806538162233,-1.0097982462293351,-1.275960388807643,-1.3029536741600423,-1.3765676711806758,-3.7401706660156235,-4.005308725585932,-0.5824815690709362,-1.5940052572524201,-0.47360326014465914,-1.4739281657081298,-5.42101406097412,-1.437725057601929,-0.6681916432659134,-1.7236572265625032,-0.36488198912048664,-2.141999999999999,-5.016000000000002,-1.1580806611328134,-0.9520350246429465,-0.9069339670562724,-0.5301769091796851,-4.35,-3.7440000000000007,-0.3359733872833299,-0.7650300859375063,-1.79725496325683,-2.6435270214080786,-3.0860000000000003,-2.436,-2.5370241417236326,-6.5173701171874985,-5.702607891799925,-2.9960000000000013,-2.370000000000001,-4.456877682617184,-6.389171335220331,-7.284336996307375,-5.670684072265627,-1.9940000000000009,-2.159999999999999,-6.031114179611204,-6.858955664062498,-6.567138724609388,-4.7688200378418,-0.12600000000000056,-4.231999999999999,-5.645785463867193,-6.409004741687429,-5.850504258873359,-4.043988089843753,-1.2834861611328081,-4.350022552717539,-6.064853069209581,-6.282808804835429,-5.3791363838966815,-1.1358121118774442,-2.844753678283696,-4.488365418642825,-5.926639856413498,-6.03401817256562,-4.920904079750532,-1.7854966396484344,-3.2565748096923857,-4.71008472584978,-6.227395622985339,-5.719076600363925,-4.931767646789557,-3.2339637355804354,-3.338363459947888,-4.982989776054947,-6.07306008632679,-5.4464626098047795,-2.0552862187500036,-3.779204218750008,-3.945562763721994,-5.274889870974867,-4.448366903011776,-3.024999999999996,-5.143999999999989,-8.250000000000004,-3.0531414856040198,-1.910893499829033,-3.854187500000001,-0.3970624999999983,-4.144999999999996,-6.094026980564819,-3.323145141601562,-5.800029907913211,-2.644,-2.846,-2.6280486029052734,-0.9253430871582028,-5.335271998256157,-0.5050624999999984,-2.7269374999999996,-7.309062499999998,-3.8787492100711414,-2.88124656250595,-6.151999999999994,-1.7949999999999982,-4.384999999999996,-6.585968565305974,-5.99,-5.99,-5.089999999999999,-4.89,-4.448,-4.7793600000000005,-4.65536,-4.096000000000002,-4.083600000000001,-3.20729,-3.2886200000000003,-3.34328,-3.0096000000000003,-3.043,-3.1310000000000002,-2.9784,-3.5201300000000004,-2.98439,-2.577,-3.1566,-3.107,-3.7291300000000005,-3.58033,-3.8729999999999998,-3.674,-3.36,-3.6486,-3.702,-3.7656499999999995,-3.78071,-4.027,-4.027,-3.993,-4.217409999999999,-4.14967,-4.352,-4.29,-4.132,-4.314,-4.507,-4.50623,-4.61522,-4.930499999999999,-5.0793,-4.86283,-5.03722,-5.32509,-4.878,-4.948],"legacy, tiles and rings":[-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-3.8,-2.7002915262414033,-4.129093259520969,-3.3157434846177476,-1.4084678939747173,-5.210011477601848,-2.559748640151765,-2.421605774587966,-5.311784859985372,-1.4163944574305682,-1.9641715296407787,-4.399095614011183,-1.9408166066592065,-2.5660573265352524,-4.3191135397334275,-2.0856373356397464,-3.643228773702082,-3.0941167603659205,-2.27180963452814,-3.198000000000001,-2.798,-2.6119999999999988,-2.7620000000000022,-3.2640000000000002,-4.090435961213007,-1.158000000000002,-3.85,-3.7780000000000005,-1.8540000000000003,-4.1279999999999974,-3.3369585985866577,-1.3999999999999997,-5.361999999999998,-1.532,-1.7100000000000002,-5.04705370445547,-1.1720000000000002,-2.141999999999999,-5.016000000000002,-0.8620000000000008,-4.252,-3.750633199317823,-1.2380000000000002,-4.35,-3.7440000000000007,-1.1239999999999988,-4.198,-3.442815844923696,-2.6439999999999984,-3.0860000000000003,-2.436,-2.8680000000000003,-3.7221469697834566,-3.259999999999999,-2.9960000000000013,-2.370000000000001,-4.315999999999999,-2.64,-2.1103836009389494,-5.545999999999999,-1.9940000000000009,-2.159999999999999,-4.556,-0.8620000000000019,-2.91613428503779,-4.712000000000001,-0.12600000000000056,-4.231999999999999,-4.37,-2.8641477289664596,-4.2059999999999995,-3.602000000000001,-1.5039999999999993,-5.023999999999999,-1.878,-2.889053081850137,-4.154,-2.2499999999999996,-2.3019999999999996,-3.690000000000001,-2.406,-2.64072819943886,-2.226,-3.5940000000000003,-3.1200000000000006,-2.998,-4.05494823363544,-2.046000000000001,-3.037999999999999,-4.632,-0.8780000000000003,-3.31,-4.798011528506675,-0.2639999999999996,-3.9899999999999993,-3.5460000000000025,-0.9200000000000003,-5.643999999999999,-5.948812667346547,-6.15683235131131,-1.402050488919631,-2.9686786744153495,-4.921641441000989,-2.69,-3.2420000000000004,-2.722,-2.21,-3.684,-3.1,-4.274,-2.644,-2.846,-2.62,-2.1619999999999995,-1.9380000000000002,-2.356,-3.64,-3.48,-1.662,-2.36,-1.5359999999999996,-4.722,-3.5,-1.248,-5.785154418945313,-5.99,-5.089999999999999,-4.89,-4.448,-4.7793600000000005,-4.65536,-4.096000000000002,-4.083600000000001,-3.20729,-3.2886200000000003,-3.34328,-3.0096000000000003,-3.043,-3.1310000000000002,-2.9784,-3.5201300000000004,-2.98439,-2.577,-3.1566,-3.107,-3.7291300000000005,-3.58033,-3.8729999999999998,-3.674,-3.36,-3.6486,-3.702,-3.7656499999999995,-3.78071,-4.027,-4.027,-3.993,-4.217409999999999,-4.14967,-4.352,-4.29,-4.132,-4.314,-4.507,-4.50623,-4.61522,-4.930499999999999,-5.0793,-4.86283,-5.03722,-5.32509,-4.878,-4.948,-3.6,-0.9295999999999999,-3.6,-3.6,-0.4786399999999999,-3.6,-0.8979999999999999,-3.6,-1.17592,-3.6,-3.6,-0.6639999999999999,-3.6,-1.36,-3.6,-1.4490399999999999,-3.6,-3.6,-2.02,-3.6,-2.27784,-3.6,-2.4228000000000005,-3.6,-3.6,-3.036,-3.6,-2.572,-3.6,-2.3184,-3.6,-3.6,-2.9215199999999997,-3.6,-2.3400000000000003,-3.6,-2.0768000000000004,-3.6,-3.6,-1.82368,-3.6,-1.464,-3.6,-1.0808000000000002,-3.6,-3.6,-0.9999999999999999,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-3.6,-2.7002915262414033,-4.129093259520969,-3.3157434846177476,-1.4084678939747173,-5.210011477601848,-2.559748640151765,-2.421605774587966,-5.311784859985372,-1.4163944574305682,-1.9641715296407787,-4.399095614011183,-1.9408166066592065,-2.5660573265352524,-4.3191135397334275,-2.0856373356397464,-3.643228773702082,-3.0941167603659205,-2.27180963452814,-3.198000000000001,-2.798,-2.6119999999999988,-2.7620000000000022,-3.2640000000000002,-4.090435961213007,-1.158000000000002,-3.85,-3.7780000000000005,-1.8540000000000003,-4.1279999999999974,-3.3369585985866577,-1.3999999999999997,-5.361999999999998,-1.532,-1.7100000000000002,-5.04705370445547,-1.1720000000000002,-2.141999999999999,-5.016000000000002,-0.8620000000000008,-4.252,-3.750633199317823,-1.2380000000000002,-4.35,-3.7440000000000007,-1.1239999999999988,-4.198,-3.442815844923696,-2.6439999999999984,-3.0860000000000003,-2.436,-2.8680000000000003,-3.7221469697834566,-3.259999999999999,-2.9960000000000013,-2.370000000000001,-4.315999999999999,-2.64,-2.1103836009389494,-5.545999999999999,-1.9940000000000009,-2.159999999999999,-4.556,-0.8620000000000019,-2.91613428503779,-4.712000000000001,-0.12600000000000056,-4.231999999999999,-4.37,-2.8641477289664596,-4.2059999999999995,-3.602000000000001,-1.5039999999999993,-5.023999999999999,-1.878,-2.889053081850137,-4.154,-2.2499999999999996,-2.3019999999999996,-3.690000000000001,-2.406,-2.64072819943886,-2.226,-3.5940000000000003,-3.1200000000000006,-2.998,-4.05494823363544,-2.046000000000001,-3.037999999999999,-4.632,-0.8780000000000003,-3.31,-4.798011528506675,-0.2639999999999996,-3.9899999999999993,-3.5460000000000025,-0.9200000000000003,-5.643999999999999,-5.948812667346547,-6.15683235131131,-1.402050488919631,-2.9686786744153495,-4.921641441000989,-2.69,-3.2420000000000004,-2.722,-2.21,-3.684,-3.1,-4.274,-2.644,-2.846,-2.62,-2.1619999999999995,-1.9380000000000002,-2.356,-3.64,-3.48,-1.662,-2.36,-1.5359999999999996,-4.722,-3.5,-1.248,-5.785154418945313,-5.99,-3.8,-3.8,-4.448,-3.8,-4.65536,-3.8,-4.083600000000001,-3.8,-3.8,-3.34328,-3.8,-3.043,-3.8,-2.9784,-3.8,-3.8,-2.577,-3.8,-3.107,-3.8,-3.58033,-3.8,-3.8,-3.36,-3.8,-3.702,-3.8,-3.78071,-3.8,-3.8,-3.993,-3.8,-4.14967,-3.8,-4.29,-3.8,-3.8,-4.507,-3.8,-4.61522,-3.8,-5.0793,-3.8,-3.8,-5.32509,-3.8,-4.948,-1.148,-0.9295999999999999,-1.6687999999999996,-0.9727199999999999,-0.4786399999999999,-1.1336,-0.8979999999999999,-1.39912,-1.17592,-1.946,-1.288,-0.6639999999999999,-1.2712,-1.36,-1.34504,-1.4490399999999999,-1.6920000000000004,-1.826,-2.02,-2.25304,-2.27784,-2.358,-2.4228000000000005,-1.7020000000000004,-2.4120000000000004,-3.036,-2.3053600000000003,-2.572,-2.0580000000000003,-2.3184,-1.3693600000000001,-2.1368,-2.9215199999999997,-2.0264000000000006,-2.3400000000000003,-2.14,-2.0768000000000004,-2.0679999999999996,-1.89368,-1.82368,-1.4764,-1.464,-1.1050400000000002,-1.0808000000000002,-1.0779999999999998,-0.968,-0.9999999999999999]} \ No newline at end of file diff --git a/packages/core/src/lib/__fixtures__/terrain-lag-golden.json b/packages/core/src/lib/__fixtures__/terrain-lag-golden.json new file mode 100644 index 0000000000..812fd4dad9 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/terrain-lag-golden.json @@ -0,0 +1 @@ +{"heights":{"tiles only":[-1.438261124749673,-1.9851729193759065,-2.5597306650178524,-3.407184915563327,-4.989922103633937,-5.043439275965273,-2.4208125121453437,-0.3146315968794424,-0.3513735905109212,-0.49610172874538766,-0.9275133794966265,-2.2912535742540143,-4.475098218267158,-3.776324585602828,-2.182299409268599,-1.8876336255942376,-1.2633293308323095,-1.3690559399930966,-1.9531622221092535,-2.639474338010866,-3.5900985040579534,-5.102769464458226,-5.115870991157898,-2.8063253380726096,-1.053914428357973,-1.0782163011783625,-1.034136038347079,-1.5218618732677194,-3.0651281396774666,-5.068465686810827,-4.1479032589582685,-2.6188558492044858,-2.3858251100350105,-1.6369709874529574,-1.259796761429134,-1.8155995495822153,-2.5436332389617675,-3.5197282266536565,-4.61853757357946,-4.3078271656618865,-2.8296977038976823,-2.0386769014751898,-2.0659035845346945,-1.7698523618453381,-2.211696401274683,-3.6317068344344503,-4.689275980827791,-3.9962733312687098,-3.080597464406761,-2.887829438993269,-2.0024246302155473,-1.5274719061098914,-1.9756391519943566,-2.5732164680646985,-3.198000000000001,-3.2040000000000024,-2.5800000000000023,-2.798,-3.3999999999999986,-3.095999999999999,-2.611999999999999,-3.0319999999999987,-3.3520000000000008,-2.7620000000000027,-2.592,-3.1959999999999997,-3.2640000000000002,-2.703999999999999,-4.059866522590828,-3.9162404625212917,-3.358766625710671,-2.2920000000000025,-1.158000000000002,-1.6179999999999994,-3.113999999999999,-3.85,-4.025999999999999,-4.313999999999999,-3.778000000000001,-2.140000000000002,-1.2360000000000004,-1.8540000000000003,-2.674000000000001,-3.186,-4.127999999999998,-5.592423873091396,-4.97087975203632,-3.3323061083698153,-1.0880000000000019,-0.39599999999999985,-1.3999999999999997,-2.634,-3.911999999999999,-5.361999999999999,-5.452000000000001,-3.500000000000002,-1.532,-0.9279999999999998,-1.0320000000000005,-1.7100000000000002,-3.6599999999999997,-5.533999999999998,-4.476389398005921,-4.01180304254609,-2.7079234669079453,-1.1720000000000002,-0.8140000000000002,-1.0199999999999996,-2.141999999999999,-4.427999999999998,-5.834,-5.016000000000002,-3.3480000000000008,-2.07,-0.8620000000000008,-0.32400000000000007,-1.8119999999999992,-4.252,-5.324000000000001,-3.668140884062537,-3.556464203996916,-2.938542469804216,-2.22,-1.2380000000000002,-1.1319999999999988,-2.707999999999999,-4.35,-4.586000000000001,-4.182,-3.7440000000000007,-2.424000000000001,-0.9540000000000001,-1.1239999999999992,-2.6519999999999992,-3.7100000000000004,-4.1979999999999995,-3.581855041468765,-3.643582179390624,-3.432202605848712,-2.7480000000000007,-2.119999999999999,-2.6439999999999992,-3.264,-3.0800000000000005,-3.0920000000000005,-3.6040000000000005,-3.406000000000001,-2.4360000000000004,-2.369999999999999,-2.9299999999999997,-2.868,-2.7300000000000004,-3.4219999999999993,-2.9007261534450772,-3.0722773865134085,-2.990047687481948,-3.2599999999999993,-4.059999999999999,-4.204,-2.9960000000000013,-2.0500000000000003,-2.226000000000001,-2.370000000000001,-2.3560000000000003,-3.2799999999999985,-4.315999999999999,-4.022,-2.984,-2.64,-2.4360000000000013,-1.2546854025953444,-1.59920082105983,-2.484600912031354,-4.437999999999997,-5.546,-4.580000000000001,-3.0060000000000002,-1.9940000000000007,-1.1160000000000014,-0.7740000000000006,-2.159999999999999,-4.337999999999999,-5.12,-4.556,-3.8419999999999996,-2.5900000000000003,-0.8620000000000019,-0.42349066982079026,-1.105533892354874,-2.88318492409262,-5.015999999999999,-5.406000000000001,-4.712000000000001,-3.676,-1.7940000000000014,-0.1260000000000004,-0.5339999999999988,-2.6099999999999985,-4.232,-5.02,-5.378,-4.370000000000001,-1.9260000000000006,-0.29800000000000043,-1.7956610024628756,-2.3469591287987326,-3.3074104300470744,-4.2059999999999995,-4.734000000000001,-4.954,-3.602000000000001,-1.4580000000000004,-0.6959999999999995,-1.5039999999999993,-2.4579999999999993,-3.55,-5.024,-5.328,-3.656000000000001,-1.878,-1.2919999999999994,-2.2280283213651373,-2.4913309005656394,-2.792198750604152,-3.2319999999999993,-4.154,-4.022000000000002,-2.8080000000000007,-2.2499999999999996,-2.4139999999999997,-2.2219999999999995,-2.3019999999999996,-3.4399999999999995,-4.2459999999999996,-3.690000000000001,-2.996,-2.864,-2.406,-2.1168544287491917,-2.3833075831958883,-2.62080933551849,-2.866,-2.712,-2.226,-2.6999999999999997,-3.6559999999999997,-3.594,-3.04,-3.1599999999999993,-3.12,-2.306000000000001,-2.128,-2.998,-3.452,-3.174,-3.3451607190299546,-3.406852490183077,-3.2791750557221304,-2.046000000000001,-0.7800000000000005,-1.2799999999999991,-3.037999999999999,-4.092,-4.386,-4.632,-3.890000000000001,-2.008000000000001,-0.8780000000000003,-1.4859999999999998,-2.5460000000000003,-3.31,-4.452,-4.65872205310161,-4.490231390847951,-3.328473363234387,-1.0060000000000016,-0.2639999999999996,-1.3159999999999992,-2.618,-3.9899999999999993,-5.494,-5.5920000000000005,-3.5460000000000025,-1.4520000000000008,-0.7840000000000001,-0.9200000000000003,-1.6520000000000004,-3.6559999999999997,-5.643999999999999,-3.245119468393755,-1.2796594554536764,-4.841410460822431,-4.316583605617641,-3.378629515648681,-5.1789858723147475,0.10698254611519947,-3.5651429746777565,-0.12526713483133564,-3.1871193973512653,-0.25415098605393505,-1.4370354938078682,-2.6353855924577014,-0.263662479277372,-3.8015205178750175,-1.8572287777421281,-3.0500000000000003,-2.69,-4.388,-3.132,-3.2420000000000004,-2.352,-2.41,-2.7219999999999995,-2.168,-3.244,-2.21,-2.9,-4.044,-3.684,-3.7840000000000003,-2.962,-3.1,-2.58,-2.646,-4.274,-3.3939999999999997,-5.982,-2.644,-4.450000000000001,-3.056,-2.846,-3.13,-1.03,-2.62,-0.09399999999999992,-3.376,-2.1619999999999995,-2.7600000000000002,-3.29,-1.9380000000000002,-2.754,-2.2079999999999997,-2.356,-3.9319999999999995,-3.116,-3.64,-2.642,-3.5500000000000003,-3.48,-2.3120000000000003,-3.412,-1.662,-2.862,-1.92,-2.36,-1.21,-4.686,-1.5359999999999996,-4.7540000000000004,-4.379999999999999,-4.722,-5.066,-2.7560000000000007,-3.5,-0.96,-1.9300000000000002,-1.248,-0.5560000000000002,-1.5759999999999998,0.056777343749999876,-3.2212514763208215,0,0,0,0.07413611014291838],"three rings, ground outside":[-1.438261124749673,-1.9851729193759065,-2.5597306650178524,-3.407184915563327,-4.989922103633937,-5.043439275965273,-2.4208125121453437,-0.3146315968794424,-0.3513735905109212,-0.49610172874538766,-0.9275133794966265,-2.294176869029578,-4.474811416441655,-3.776324585602828,-2.182299409268599,-1.8876336255942376,-1.2633293308323095,-1.3690559399930966,-1.9531622221092535,-2.639474338010866,-3.5900985040579534,-5.102769464458226,-5.115870991157898,-2.8063253380726096,-1.053914428357973,-1.0782163011783625,-1.034136038347079,-1.5218618732677194,-3.0679091501400206,-5.068189902240887,-4.1479032589582685,-2.6188558492044858,-2.3858251100350105,-1.6369709874529574,-1.259796761429134,-1.8155995495822153,-2.5436332389617675,-3.5197282266536565,-4.61853757357946,-4.3078271656618865,-2.8296977038976823,-2.0386769014751898,-2.0659035845346945,-1.7698523618453381,-2.211696401274683,-3.6320110272398947,-4.6892448277149015,-3.9962733312687098,-3.080597464406761,-2.887829438993269,-2.0024246302155473,-1.5274719061098914,-1.9756391519943566,-2.5732164680646985,-3.198000000000001,-3.2040000000000024,-2.5800000000000023,-2.798,-3.3999999999999986,-3.095999999999999,-2.6119999999999988,-3.0319999999999987,-3.3520000000000008,-2.7620000000000022,-2.5920000000000005,-3.1959999999999997,-3.2640000000000002,-2.7039999999999993,-4.059866522590828,-3.9162404625212917,-3.358766625710671,-2.2920000000000025,-1.158000000000002,-1.6179999999999994,-3.113999999999999,-3.85,-4.025999999999999,-4.313999999999998,-3.7780000000000005,-2.140000000000002,-1.2360000000000004,-1.8540000000000003,-2.6740000000000004,-3.186,-4.1279999999999974,-5.592423873091396,-4.97087975203632,-3.3323061083698153,-1.0880000000000019,-0.39599999999999985,-1.3999999999999997,-2.6339999999999995,-3.9119999999999986,-5.361999999999998,-5.452000000000001,-3.500000000000002,-1.532,-0.9279999999999998,-1.0320000000000005,-1.7100000000000002,-3.6599999999999997,-5.533999999999998,-4.476389398005921,-4.01180304254609,-2.7079234669079453,-1.1720000000000002,-0.8140000000000003,-1.0199999999999998,-2.141999999999999,-4.427999999999998,-5.834,-5.016000000000002,-3.3480000000000008,-2.07,-0.8620000000000008,-0.32400000000000007,-1.8119999999999992,-4.252,-5.324000000000001,-3.6683760923462807,-3.556675286720736,-2.9385695521694895,-2.22,-1.2380000000000002,-1.1319999999999986,-2.7079999999999984,-4.35,-3.8,-3.8,-3.7440000000000007,-2.424000000000001,-0.954,-1.1239999999999988,-2.6519999999999992,-3.7100000000000004,-4.198,-3.5821488332185543,-3.643810582869898,-3.4322312519787825,-2.7480000000000007,-2.1199999999999988,-2.6439999999999984,-3.264,-3.0800000000000014,-3.0860000000000003,-3.596,-3.406000000000001,-4.7,-4.7,-2.9299999999999993,-2.8680000000000003,-2.7300000000000004,-3.4219999999999997,-2.9007261534450772,-3.0722773865134085,-2.990047687481948,-3.259999999999999,-4.059999999999999,-4.204,-2.9960000000000013,-2.0500000000000003,-2.226000000000001,-2.370000000000001,-2.356,-4.7,-4.7,-4.022,-2.984,-2.64,-2.4360000000000013,-1.2546854025953444,-1.59920082105983,-2.484600912031354,-4.437999999999997,-5.545999999999999,-4.580000000000001,-3.0060000000000002,-1.9940000000000009,-1.1160000000000017,-0.7740000000000007,-2.159999999999999,-4.7,-4.7,-4.556,-3.8419999999999996,-2.5900000000000003,-0.8620000000000019,-0.42349066982079026,-1.105533892354874,-2.88318492409262,-5.015999999999999,-5.406000000000001,-4.712000000000001,-3.6760000000000006,-1.7940000000000016,-0.12600000000000056,-0.5339999999999989,-2.6099999999999985,-4.231999999999999,-5.02,-5.378,-4.37,-1.9260000000000006,-0.29800000000000043,-1.7956610024628756,-2.3469591287987326,-3.3074104300470744,-4.2059999999999995,-4.734,-4.954000000000001,-3.602000000000001,-1.4580000000000009,-0.6959999999999996,-1.5039999999999993,-2.4579999999999993,-3.55,-5.023999999999999,-5.328,-3.656000000000001,-1.878,-1.2919999999999994,-2.2280283213651373,-2.4913309005656394,-2.792198750604152,-3.2319999999999993,-4.154,-4.022000000000001,-2.808000000000001,-2.2499999999999996,-2.4139999999999997,-2.2219999999999995,-2.3019999999999996,-3.4399999999999995,-4.246,-3.690000000000001,-2.996,-2.864,-2.406,-2.1168544287491917,-2.3833075831958883,-2.62080933551849,-2.866,-2.7120000000000006,-2.226,-2.6999999999999993,-3.6559999999999993,-3.5940000000000003,-3.04,-3.1599999999999997,-3.1200000000000006,-2.306000000000001,-2.128,-2.998,-3.452,-3.174,-3.3451607190299546,-3.406852490183077,-3.2791750557221304,-2.046000000000001,-0.7800000000000005,-1.2799999999999991,-3.037999999999999,-4.092,-4.385999999999999,-4.632,-3.890000000000001,-2.008000000000001,-0.8780000000000003,-1.4859999999999998,-2.5460000000000003,-3.31,-4.452,-4.65872205310161,-4.490231390847951,-3.328473363234387,-1.0060000000000016,-0.2639999999999996,-1.3159999999999992,-2.618,-3.9899999999999993,-5.493999999999999,-5.592,-3.5460000000000025,-1.4520000000000008,-0.7840000000000001,-0.9200000000000003,-1.6520000000000001,-3.6559999999999997,-5.643999999999999,-3.245119468393755,-1.2796594554536764,-4.841410460822431,-4.316583605617641,-3.378629515648681,-5.1789858723147475,0.10698254611519947,-3.5653158378323857,-0.12526713483133564,-3.1871193973512653,-0.25415098605393505,-1.4370354938078682,-2.636172021425395,-0.263662479277372,-3.8015205178750175,-1.8572287777421281,-3.0500000000000003,-2.69,-4.388,-3.132,-3.2420000000000004,-2.352,-2.41,-2.722,-2.168,-3.244,-2.21,-2.9,-4.044,-3.684,-3.7840000000000003,-2.962,-3.1,-2.58,-2.646,-4.274,-3.3939999999999997,-5.982,-2.644,-3.8,-3.056,-2.846,-3.13,-1.03,-4.7,-0.09399999999999992,-3.376,-2.1619999999999995,-2.7600000000000002,-3.29,-1.9380000000000002,-2.754,-2.2079999999999997,-2.356,-3.932,-3.116,-3.64,-2.642,-3.5500000000000003,-3.48,-2.3120000000000003,-3.412,-1.662,-2.862,-1.92,-2.36,-1.21,-4.686,-1.5359999999999996,-4.7540000000000004,-4.379999999999999,-4.722,-5.066,-2.7560000000000007,-3.5,-0.96,-1.9300000000000002,-1.248,-0.5560000000000002,-1.5759999999999998,0.056777343749999876,-3.2212514763208215,0,0,0,0.07413611014291838,-3.8,-3.8,-3.8,-3.8,-4.8588,-4.76,-4.448,-3.8,-3.8,-3.8,-3.8,-4.7313600000000005,-4.65536,-4.38734,-3.8,-3.8,-3.8,-3.8,-4.083600000000001,-4.0760000000000005,-4.007,-3.8,-3.8,-3.8,-3.8,-3.2934200000000002,-3.3086200000000003,-3.34328,-3.8,-3.8,-3.8,-3.8,-3.0186000000000006,-3.043,-3.105,-3.8,-3.8,-3.8,-3.8,-2.9784,-2.872,-2.553,-3.8,-3.8,-3.8,-3.8,-2.95079,-2.84726,-2.577,-3.8,-3.8,-3.8,-3.8,-3.1374,-3.107,-2.889,-3.8,-3.8,-3.8,-3.8,-3.58033,-3.49017,-3.31139,-3.8,-3.8,-3.8,-3.8,-3.664,-3.591,-3.36,-3.8,-3.8,-3.8,-3.8,-3.6836,-3.702,-3.6670000000000003,-3.8,-3.8,-3.8,-3.8,-3.78071,-3.78831,-3.79265,-3.8,-3.8,-3.8,-3.8,-4.027,-4.016,-3.993,-3.8,-3.8,-3.8,-3.8,-4.18861,-4.14967,-4.03067,-3.8,-3.8,-3.8,-3.8,-4.29,-4.229,-4.0440000000000005,-3.8,-3.8,-3.8,-3.8,-4.328399999999999,-4.366,-4.507,-3.8,-3.8,-3.8,-3.8,-4.54943,-4.61522,-4.82105,-3.8,-3.8,-3.8,-3.8,-5.0793,-5.1705,-5.4975,-3.8,-3.8,-3.8,-3.8,-5.06842,-5.16722,-5.32509,-3.8,-3.8,-3.8,-3.8,-4.902,-4.948,-5.01,-4.7,-4.7,-4.7,-4.7,-3.1108000000000002,-3.24,-3.53,-4.7,-4.7,-4.7,-4.7,-3.0553999999999997,-3.1390000000000002,-3.4196,-4.7,-4.7,-4.7,-4.7,-2.6804,-2.65,-2.552,-4.7,-4.7,-4.7,-4.7,-3.4046000000000003,-3.2222,-2.7066,-4.7,-4.7,-4.7,-4.7,-3.6144000000000003,-3.47,-2.9440000000000004,-4.7,-4.7,-4.7,-4.7,-3.7148,-3.73,-3.738,-4.7,-4.7,-4.7,-4.7,-4.133999999999999,-4.111199999999999,-4.0784,-4.7,-4.7,-4.7,-4.7,-4.8428,-4.82,-4.722,-4.7,-4.7,-4.7,-4.7,-5.090400000000001,-5.07,-5.0384,-4.7,-4.7,-4.7,-4.7,-5.1052,-5.09,-5.086,-4.7,-4.7,-4.7,-4.7,-5.105199999999999,-5.09,-5.0600000000000005,-4.7,-4.7,-4.7,-4.7,-5.088399999999999,-5.0732,-4.979,-4.7,-4.7,-4.7,-4.7,-4.0096,-4.04,-4.088,-4.7,-4.7,-4.7,-4.7,-1.6212000000000002,-1.6288000000000002,-1.7074000000000003,-4.7,-4.7,-4.7,-4.7,-0.98,-0.98,-0.996,-4.7,-4.7,-4.7,-4.7,-1.0184000000000002,-0.9500000000000001,-0.802,-4.7,-4.7,-4.7,-4.7,-1.1199999999999999,-1.0896,-0.9915999999999998,-4.7,-4.7,-4.7,-4.7,-1.8724,-1.8800000000000001,-1.8780000000000001,-4.7,-4.7,-4.7,-4.7,-2.8868,-2.8488,-2.7980000000000005,-4.7,-4.7,-4.7,-4.7,-3.0772000000000004,-3.1,-3.092,-3.6,-3.6,-3.6,-3.6,-0.9295999999999999,-0.8119999999999999,-0.48999999999999994,-3.6,-3.6,-3.6,-3.6,-0.9295199999999999,-0.8019999999999999,-0.4786399999999999,-3.6,-3.6,-3.6,-3.6,-1.0423999999999998,-0.8979999999999999,-0.5099999999999999,-3.6,-3.6,-3.6,-3.6,-1.17592,-1.03912,-0.6012,-3.6,-3.6,-3.6,-3.6,-1.2448,-1.108,-0.6639999999999999,-3.6,-3.6,-3.6,-3.6,-1.3068,-1.36,-1.54,-3.6,-3.6,-3.6,-3.6,-1.4490399999999999,-1.48776,-1.6492,-3.6,-3.6,-3.6,-3.6,-1.8404,-1.8860000000000001,-2.02,-3.6,-3.6,-3.6,-3.6,-2.2626399999999998,-2.27784,-2.36792,-3.6,-3.6,-3.6,-3.6,-2.4228000000000005,-2.422,-2.4480000000000004,-3.6,-3.6,-3.6,-3.6,-2.4576,-2.5860000000000003,-3.036,-3.6,-3.6,-3.6,-3.6,-2.4157599999999997,-2.572,-3.04728,-3.6,-3.6,-3.6,-3.6,-2.3184,-2.478,-3.024,-3.6,-3.6,-3.6,-3.6,-2.1967999999999996,-2.3813600000000004,-2.9215199999999997,-3.6,-3.6,-3.6,-3.6,-2.15,-2.3400000000000003,-2.876,-3.6,-3.6,-3.6,-3.6,-2.0768000000000004,-2.0540000000000003,-1.9620000000000002,-3.6,-3.6,-3.6,-3.6,-1.89368,-1.89512,-1.82368,-3.6,-3.6,-3.6,-3.6,-1.4716,-1.464,-1.44,-3.6,-3.6,-3.6,-3.6,-1.0808000000000002,-1.0732000000000002,-1.1092000000000002,-3.6,-3.6,-3.6,-3.6,-0.9716,-0.96,-0.9999999999999999],"open break":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,-0.07706780442166962,-1.0155449587294472,-2.467581186470571,-4.437999999999997,-5.545999999999999,-4.580000000000001,-3.0060000000000002,-1.9940000000000009,-1.1160000000000017,-0.7740000000000007,-2.159999999999999,-4.337999999999998,-5.12,-4.556,-3.8419999999999996,-2.5900000000000003,-0.8620000000000019,0.33228771273039864,-0.8374188824629941,-2.881572482635028,-5.015999999999999,-5.406000000000001,-4.712000000000001,-3.6760000000000006,-1.7940000000000016,-0.12600000000000056,-0.5339999999999989,-2.6099999999999985,-4.231999999999999,-5.02,-5.378,-4.37,-1.9260000000000006,-0.29800000000000043,-1.6526470270096019,-2.3155219512705894,-3.3089149599376912,-4.2059999999999995,-4.734,-4.954000000000001,-3.602000000000001,-1.4580000000000009,-0.6959999999999996,-1.5039999999999993,-2.4579999999999993,-3.55,-5.023999999999999,-5.328,-3.656000000000001,-1.878,-1.2919999999999994,-2.212062188418516,-2.491292569884013,-2.792830141492386,-3.2319999999999993,-4.154,-4.022000000000001,-2.808000000000001,-2.2499999999999996,-2.4139999999999997,-2.2219999999999995,-2.3019999999999996,-3.4399999999999995,-4.246,-3.690000000000001,-2.996,-2.864,-2.406,-2.1186423450873137,-2.3864114569494683,-2.6212013153897136,-2.866,-2.7120000000000006,-2.226,-2.6999999999999993,-3.6559999999999993,-3.5940000000000003,-3.04,-3.1599999999999997,-3.1200000000000006,-2.306000000000001,-2.128,-2.998,-3.452,-3.174,-3.3704224418427837,-3.4159508507426346,-3.2797778124652144,-2.046000000000001,-0.7800000000000005,-1.2799999999999991,-3.037999999999999,-4.092,-4.385999999999999,-4.632,-3.890000000000001,-2.008000000000001,-0.8780000000000003,-1.4859999999999998,-2.5460000000000003,-3.31,-4.452,-4.689105216878741,-4.501262227064304,-3.328884280122327,-1.0060000000000016,-0.2639999999999996,-1.3159999999999992,-2.618,-3.9899999999999993,-5.493999999999999,-5.592,-3.5460000000000025,-1.4520000000000008,-0.7840000000000001,-0.9200000000000003,-1.6520000000000001,-3.6559999999999997,-5.643999999999999,2,2,2,2,2,2,2,2,2,2,2,-0.2210319509616578,2,0.4852629663315781,2,-1.793273280888826,2,2,2,2,2,2,2,2,2,2,2,-2.9,2,-3.684,2,-2.962,2,2,2,2,2,2,2,2,2,2,2,-1.03,2,-0.09399999999999992,2,-2.1619999999999995,-2.7600000000000002,2,-1.9380000000000002,2,-2.2079999999999997,2,-3.932,2,-3.64,2,-3.5500000000000003,-3.48,-2.3120000000000003,-3.412,-1.662,-2.862,-1.92,2,-1.21,2,-1.5359999999999996,2,-4.379999999999999,2,-5.066,2,-3.5,-0.96,-1.9300000000000002,-1.248,-0.5560000000000002,-1.5759999999999998,2,-3.2212514763208215,2,2,2,0.07413611014291838,2,2,2,2,-2.4697719837248537,-2.2708639742047922,-1.5584123719775265,2,2,2,2,-3.1091999999999995,-3.1699999999999995,-3.308,2,2,2,2,-2.2188,-2.12,-1.806,2,2,2,2,-3.0564000000000004,-3.1400000000000006,-3.314000000000001,2,2,2,2,-2.3735999999999997,-2.29,-2.006],"open break, ground on its left":[-1.438261124749673,-1.9851729193759065,-2.5597306650178524,-3.407184915563327,-4.989922103633937,-5.043439275965273,-2.4208125121453437,-0.3146315968794424,-0.3513735905109212,-0.49610172874538766,-0.9275133794966265,-2.2912535742540143,-4.475098218267158,-3.776324585602828,-2.182299409268599,-1.8876336255942376,-1.2633293308323095,-1.3690559399930966,-1.9531622221092535,-2.639474338010866,-3.5900985040579534,-5.102769464458226,-5.115870991157898,-2.8063253380726096,-1.053914428357973,-1.0782163011783625,-1.034136038347079,-1.5218618732677194,-3.0651281396774666,-5.068465686810827,-4.1479032589582685,-2.6188558492044858,-2.3858251100350105,-1.6369709874529574,-1.259796761429134,-1.8155995495822153,-2.5436332389617675,-3.5197282266536565,-4.61853757357946,-4.3078271656618865,-2.8296977038976823,-2.0386769014751898,-2.0659035845346945,-1.7698523618453381,-2.211696401274683,-3.6317068344344503,-4.689275980827791,-3.9962733312687098,-3.080597464406761,-2.887829438993269,-2.0024246302155473,-1.527619408273257,-1.9757281811482728,-2.5732218073189443,-3.198000000000001,-3.2040000000000024,-2.5800000000000023,-2.798,-3.3999999999999986,-3.095999999999999,-2.6119999999999988,-3.0319999999999987,-3.3520000000000008,-2.7620000000000022,-2.5920000000000005,-3.1959999999999997,-3.2640000000000002,-2.7039999999999993,-4.063611743236186,-3.9175178506213455,-3.358812729608389,-2.2920000000000025,-1.158000000000002,-1.6179999999999994,-3.113999999999999,-3.85,-4.025999999999999,-4.313999999999998,-3.7780000000000005,-2.140000000000002,-1.2360000000000004,-1.8540000000000003,-2.6740000000000004,-3.186,-4.1279999999999974,-5.607966443472915,-4.975693988469795,-3.3324496919133417,-1.0880000000000019,-0.39599999999999985,-1.3999999999999997,-2.6339999999999995,-3.9119999999999986,-5.361999999999998,-5.452000000000001,-3.500000000000002,-1.532,-0.9279999999999998,-1.0320000000000005,-1.7100000000000002,-3.6599999999999997,-5.533999999999998,-4.501664992138324,-4.020201438696453,-2.708194754059627,-1.1720000000000002,-0.8140000000000003,-1.0199999999999998,-2.141999999999999,-4.427999999999998,-5.834,-5.016000000000002,-3.3480000000000008,-2.07,-0.8620000000000008,-0.32400000000000007,-1.8119999999999992,-4.252,-5.324000000000001,-3.7024434152086276,-3.568789693089158,-2.93912514535816,-2.22,-1.2380000000000002,-1.1319999999999986,-2.7079999999999984,-4.35,-4.586000000000001,-4.182,-3.7440000000000007,-2.424000000000001,-0.954,-1.1239999999999988,-2.6519999999999992,-3.7100000000000004,-4.198,-3.635044858393533,-3.6610779945311474,-3.43313470703159,-2.7480000000000007,-2.1199999999999988,-2.6439999999999984,-3.264,-3.0800000000000014,-3.0920000000000005,-3.6040000000000005,-3.406000000000001,-2.436,-2.3699999999999983,-2.9299999999999993,-2.8680000000000003,-2.7300000000000004,-3.4219999999999997,-2.974523108195829,-3.0998166363309276,-2.99177531049602,-3.259999999999999,-4.059999999999999,-4.204,-2.9960000000000013,-2.0500000000000003,-2.226000000000001,-2.370000000000001,-2.356,-3.2799999999999985,-4.315999999999999,-4.022,-2.984,-2.64,-2.4360000000000013,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-3.245119468393755,-1.2796594554536764,-4.841410460822431,-4.323259427221666,-3.378629515648681,-5.213552664210491,0.10698254611519947,-3.619287820201487,-0.12526713483133564,-3.2876135380877543,-0.25415098605393505,-2.5,-2.6353855924577014,-2.5,-3.8015205178750175,-2.5,-3.0500000000000003,-2.69,-4.388,-3.132,-3.2420000000000004,-2.352,-2.41,-2.722,-2.168,-3.244,-2.21,-2.5,-4.044,-2.5,-3.7840000000000003,-2.5,-3.1,-2.58,-2.646,-4.274,-3.3939999999999997,-5.982,-2.644,-4.450000000000001,-3.056,-2.846,-3.13,-2.5,-2.62,-2.5,-3.376,-2.5,-2.5,-3.29,-2.5,-2.754,-2.5,-2.356,-2.5,-3.116,-2.5,-2.642,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,-2.36,-2.5,-4.686,-2.5,-4.7540000000000004,-2.5,-4.722,-2.5,-2.7560000000000007,-2.5,-2.5,-2.5,-2.5,-2.5,-2.5,0.056777343749999876,-2.5,0,0,0,-2.5,-3.545462757418923,-3.0977810375790384,-3.071614657033796,-3.062982404271713,-2.5,-2.5,-2.5,-3.0460000000000003,-3.086,-3.1256,-3.1399999999999997,-2.5,-2.5,-2.5,-2.5820000000000003,-2.33,-2.2464000000000004,-2.22,-2.5,-2.5,-2.5,-2.994000000000001,-3.064000000000001,-3.094400000000001,-3.102000000000001,-2.5,-2.5,-2.5,-2.7720000000000002,-2.5500000000000003,-2.4816000000000003,-2.46,-2.5,-2.5,-2.5],"one ring, numeric both sides":[1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,-4.7,-4.7,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,-4.7,-4.7,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,-4.7,-4.7,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,-4.7,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2,-4.7,-4.7,-4.7,-4.7,1.2,1.2,1.2],"legacy only":[-4.155018192838953,-3.897304754401669,-3.784324146878152,-3.8322592278542866,-4.031677196736192,-4.346221872886529,-5.251745117187489,-4.257833984375,-4.210214843750002,-6.249690429687501,-5.32752441406249,-2.2917646484375034,-2.567990726433657,-2.5183683519133657,-2.641912608809588,-2.930139048688315,-3.3548527493592672,-3.5535148220987938,-3.241696418975268,-3.1089125878742094,-3.179668061192569,-3.4468261114948846,-3.864263861736596,-4.920568078720081,-3.9869750436706544,-4.06638270037842,-6.226257949447634,-5.077410563430775,-1.6985900450897256,-1.9348926254550856,-1.8443617253048905,-1.9611707428867224,-2.273818566358295,-2.747615368315709,-2.936903309681445,-2.5576446216381883,-2.388689163572294,-2.468607773563047,-2.800613884377353,-3.331747880190437,-4.5039645394287,-3.792183528076171,-4.07416557763672,-6.156438993530275,-4.776350584106435,-1.259693131713871,-1.4003635282709146,-1.2633535677575658,-1.3714096491347985,-1.7054642267654643,-2.22148331532565,-2.3513184221892605,-1.8905621799102326,-1.6624656444954686,-1.7242337923880793,-2.1028902467713717,-2.752501321844949,-3.9922707609405426,-3.700801411041259,-4.274944448303224,-6.029806538162233,-4.420323597640983,-1.0319795609283484,-1.0097982462293351,-0.8245968569472504,-0.9247232200358488,-1.275960388807643,-1.8234905227693374,-1.852977102464296,-1.3029536741600423,-0.9935434159066956,-0.9977441091939547,-1.3765676711806758,-2.13059788274969,-3.3758230048828057,-3.740170666015625,-4.71010028515625,-5.835933559570315,-4.005308725585932,-1.0723549853515641,-0.8099626511550385,-0.5824815690709362,-0.6751313247271784,-1.0329177377997272,-1.5940052572524201,-1.5017568935798224,-0.8698408716008472,-0.47360326014465914,-0.39089185142813815,-0.6993958742870501,-1.4739281657081298,-2.644957532882688,-3.937633266448975,-5.42101406097412,-5.564393033981324,-3.527285089492798,-1.437725057601929,-0.8559920729064937,-0.5961362349669225,-0.6681916432659134,-1.0097130419617197,-1.5583776382105194,-1.7236572265625032,-1.0593154644317666,-0.5838507491455114,-0.36488198912048664,-0.4700280927734395,-0.9669079685211183,-2.141999999999999,-4.427999999999998,-5.834,-5.016000000000003,-3.3480000000000008,-2.07,-1.1580806611328134,-0.7345979424591087,-0.688755561889651,-0.9520350246429465,-1.4559178359375025,-1.5613408203124985,-0.9069339670562728,-0.4678239166259752,-0.3176813402557366,-0.530176909179686,-1.1789812946319573,-2.707999999999999,-4.35,-4.586000000000001,-4.182,-3.7440000000000007,-2.424000000000001,-1.0661641298828122,-0.33597338728332415,-0.09998825329589689,-0.2718075466155989,-0.7650300859374974,-2.5597607421874944,-2.0860660955657897,-1.79725496325683,-1.753667782180781,-2.015644989257808,-2.6435270214080786,-3.264,-3.0800000000000014,-3.0920000000000005,-3.6040000000000005,-3.406000000000001,-2.436,-2.232978584960937,-2.3131693406829834,-2.5370241417236326,-2.8739979419708246,-3.2935456953124995,-6.5173701171874985,-6.392058846298215,-6.130089742553709,-5.702607891799925,-5.080758379882811,-4.235686292648316,-2.9960000000000013,-2.0500000000000003,-2.226000000000001,-2.3700000000000014,-2.3560000000000003,-3.279999999999998,-4.456877682617187,-5.343416406661987,-5.975869645141602,-6.389171335220339,-6.618255414062501,-7.343427734375002,-7.284336996307375,-7.017925633544925,-6.4960794056701685,-5.670684072265627,-4.4936253929138195,-3.0060000000000002,-1.9940000000000007,-1.1160000000000017,-0.7740000000000006,-2.159999999999999,-4.337999999999999,-5.368205151367187,-6.031114179611204,-6.479869961547849,-6.745480966567991,-6.858955664062498,-6.834171875000013,-6.7721771306152485,-6.567138724609388,-6.18656250708009,-5.597954328125009,-4.7688200378418,-3.676,-1.7940000000000014,-0.12600000000000056,-0.5339999999999986,-2.6099999999999985,-4.232,-4.893592539062502,-5.323093262329106,-5.645785463867193,-5.8752992401123105,-6.025264687500005,-6.409004741687429,-6.328443455439889,-6.149302330263118,-5.850504258873359,-5.411499703015304,-4.819828028640749,-4.043988089843753,-1.3265720351562507,-0.517938132812499,-1.2834861611328057,-2.7003322851562515,-3.6502032412109386,-4.350022552717539,-5.110714698857742,-5.676936911631816,-6.064853069209581,-6.300294038859416,-6.368090890055658,-6.282808804835429,-6.100623519690748,-5.8031236657759395,-5.3791363838966815,-4.849000166980188,-4.369540780700688,-1.1358121118774414,-1.139536709106443,-1.9703488877715953,-2.844753678283696,-3.3433076946868914,-3.7322110944997524,-4.488365418642825,-5.123349986184634,-5.600467794876206,-5.926639856413498,-6.302985598505714,-6.213840830889956,-6.03401817256562,-5.751707674958139,-5.369158073063657,-4.920904079750532,-4.665485473144536,-1.229697636230469,-1.7854966396484344,-2.622411749389634,-3.087790104980475,-3.2565748096923857,-3.40792775687456,-4.083754677485652,-4.71008472584978,-5.2232733966824725,-5.606042311589874,-6.227395622985339,-6.139331787022135,-5.971488880061235,-5.719076600363925,-5.392626588830215,-5.026879985475646,-4.931767646789557,-1.554198905944824,-2.4393527679443325,-3.2339637355804296,-3.4068156051635814,-3.3511724414825466,-3.338363459947888,-3.912542099103563,-4.482515090407466,-4.982989776054947,-5.382600036613184,-6.153828000022761,-6.07306008632679,-5.925929040954987,-5.712570600482418,-5.4464626098047795,-5.157696571477064,-5.1683327812500055,-2.0552862187499996,-3.0846399374999973,-3.7992938359374855,-3.779204218750008,-3.5882684453125027,-3.4749462829489968,-3.945562763721994,-4.437070469703361,-4.892036180304247,-5.274889870974867,-4.252289199432841,-2.9895129546220063,-4.448366903011776,-2.346927753179804,-5.1190000000000015,-3.024999999999996,-4.4959999999999996,-2.1529999999999987,-5.143999999999989,-4.852999999999996,-4.949999999999997,-8.250000000000004,-3.173087284118092,-6.424976319017877,-3.0531414856040198,-6.389597453837565,-2.2141513652878104,-1.910893499829033,-2.666040730620745,-0.9021838464474721,-3.854187500000001,-1.3825624999999953,-3.756874999999999,-0.3970624999999983,-5.012374999999987,-4.017312499999996,-4.144999999999996,-8.003750000000004,-1.5025063350499717,-6.094026980564819,-1.1402105192645615,-6.045158615784086,-3.323145141601562,-5.740137329101566,-3.20715024482727,-5.800029907913211,-3.3939999999999997,-5.982,-2.644,-4.450000000000001,-3.0559999999999996,-2.8460000000000005,-3.13,-1.03,-2.6280486029052734,-0.09004827148437455,-3.0041699927520753,-0.9253430871582028,-5.847198442061747,-1.1574833556903223,-5.335271998256157,-0.7582684186373141,-5.723374999999994,-0.5050624999999984,-1.3167499999999999,-0.11693749999999792,-2.726937499999998,-4.391937499999992,-3.1915624999999963,-7.309062499999998,-2.9813075098314012,-6.180640877884917,-3.8787492100711414,-5.395391017894182,-5.803188279157847,-2.88124656250595,-5.536837072342427,-2.5587592588316266,-6.151999999999994,-2.2489999999999988,-2.9219999999999997,-1.7949999999999982,-4.546999999999998,-5.362999999999993,-4.384999999999996,-7.464999999999998,-3.724080359997488,-6.585968565305974,-4.1722346617224915,-6.2129502167878075,-5.99,-5.99,-5.99,-5.99,-5.99,-5.99],"legacy and a ring":[-4.155018192838953,-3.897304754401669,-3.784324146878152,-3.8322592278542866,-4.031677196736192,-4.346221872886529,-5.251745117187489,-4.257833984374999,-4.210214843750002,-6.249690429687501,-5.32752441406249,-2.2917646484375034,-2.567990726433657,-2.5183683519133657,-2.641912608809588,-2.930139048688315,-3.3548527493592672,-3.5535148220987938,-3.241696418975268,-3.1089125878742094,-3.179668061192569,-3.4468261114948846,-3.864263861736596,-4.920568078720081,-3.986975043670653,-4.06638270037842,-6.226257949447634,-5.077410563430775,-1.6985900450897256,-1.9348926254550856,-1.8443617253048905,-1.9611707428867224,-2.273818566358295,-2.747615368315709,-2.936903309681445,-2.5576446216381883,-2.388689163572294,-2.468607773563047,-2.800613884377353,-3.331747880190437,-4.5039645394287,-3.792183528076171,-4.07416557763672,-6.156438993530275,-4.776350584106435,-1.259693131713871,-1.4003635282709146,-1.2633535677575658,-1.3714096491347985,-1.7054642267654643,-2.22148331532565,-2.3513184221892605,-1.8905621799102326,-1.6624656444954686,-1.7242337923880793,-2.1028902467713717,-2.752501321844949,-3.9922707609405426,-3.700801411041259,-4.274944448303224,-6.029806538162233,-4.420323597640983,-1.0319795609283484,-1.0097982462293351,-0.8245968569472504,-0.9247232200358488,-1.275960388807643,-1.8234905227693374,-1.852977102464296,-1.3029536741600423,-0.9935434159066956,-0.9977441091939547,-1.3765676711806758,-2.13059788274969,-3.3758230048828057,-3.7401706660156235,-4.71010028515625,-5.835933559570315,-4.005308725585932,-1.0723549853515641,-0.8099626511550385,-0.5824815690709362,-0.6751313247271784,-1.0329177377997272,-1.5940052572524201,-1.5017568935798224,-0.8698408716008472,-0.47360326014465914,-0.39089185142813815,-0.6993958742870501,-1.4739281657081298,-2.644957532882688,-3.9376332664489726,-5.42101406097412,-5.564393033981324,-3.527285089492798,-1.437725057601929,-0.8559920729064937,-0.5961362349669225,-0.6681916432659134,-1.0097130419617197,-1.5583776382105194,-1.7236572265625032,-1.0593154644317666,-0.5838507491455114,-0.36488198912048664,-0.4700280927734395,-0.9669079685211183,-2.141999999999999,-4.427999999999998,-5.834,-5.016000000000002,-3.3480000000000008,-2.07,-1.1580806611328134,-0.7345979424591087,-0.688755561889651,-0.9520350246429465,-1.4559178359375025,-1.561340820312498,-0.9069339670562724,-0.46782391662597433,-0.3176813402557357,-0.5301769091796851,-1.1789812946319564,-2.7079999999999984,-4.35,-3.8,-3.8,-3.7440000000000007,-2.424000000000001,-1.066164129882815,-0.3359733872833299,-0.099988253295904,-0.2718075466156069,-0.7650300859375063,-2.5597607421874944,-2.0860660955657897,-1.79725496325683,-1.753667782180781,-2.015644989257808,-2.6435270214080786,-3.264,-3.0800000000000014,-3.0860000000000003,-3.596,-3.406000000000001,-2.436,-2.232978584960937,-2.3131693406829834,-2.5370241417236326,-2.8739979419708246,-3.2935456953124995,-6.5173701171874985,-6.392058846298215,-6.130089742553709,-5.702607891799925,-5.080758379882811,-4.235686292648316,-2.9960000000000013,-2.0500000000000003,-2.226000000000001,-2.370000000000001,-2.356,-3.2799999999999985,-4.456877682617184,-5.343416406661982,-5.975869645141595,-6.389171335220331,-6.618255414062494,-7.343427734375002,-7.284336996307375,-7.017925633544925,-6.4960794056701685,-5.670684072265627,-4.4936253929138195,-3.0060000000000002,-1.9940000000000009,-1.1160000000000017,-0.7740000000000007,-2.159999999999999,-4.337999999999998,-5.368205151367187,-6.031114179611204,-6.479869961547849,-6.745480966567991,-6.858955664062498,-6.834171875000013,-6.7721771306152485,-6.567138724609388,-6.18656250708009,-5.597954328125009,-4.7688200378418,-3.6760000000000006,-1.7940000000000016,-0.12600000000000056,-0.5339999999999989,-2.6099999999999985,-4.231999999999999,-4.893592539062502,-5.323093262329106,-5.645785463867193,-5.8752992401123105,-6.025264687500005,-6.409004741687429,-6.328443455439889,-6.149302330263118,-5.850504258873359,-5.411499703015304,-4.819828028640749,-4.043988089843753,-1.3265720351562522,-0.517938132812499,-1.2834861611328081,-2.7003322851562515,-3.6502032412109386,-4.350022552717539,-5.110714698857742,-5.676936911631816,-6.064853069209581,-6.300294038859416,-6.368090890055658,-6.282808804835429,-6.100623519690748,-5.8031236657759395,-5.3791363838966815,-4.849000166980188,-4.369540780700688,-1.1358121118774442,-1.139536709106443,-1.9703488877715996,-2.844753678283696,-3.3433076946868914,-3.7322110944997524,-4.488365418642825,-5.123349986184634,-5.600467794876206,-5.926639856413498,-6.302985598505714,-6.213840830889956,-6.03401817256562,-5.751707674958139,-5.369158073063657,-4.920904079750532,-4.665485473144536,-1.2296976362304726,-1.7854966396484344,-2.622411749389639,-3.087790104980475,-3.2565748096923857,-3.40792775687456,-4.083754677485652,-4.71008472584978,-5.2232733966824725,-5.606042311589874,-6.227395622985339,-6.139331787022135,-5.971488880061235,-5.719076600363925,-5.392626588830215,-5.026879985475646,-4.931767646789557,-1.5541989059448282,-2.4393527679443325,-3.2339637355804354,-3.4068156051635814,-3.3511724414825466,-3.338363459947888,-3.912542099103563,-4.482515090407466,-4.982989776054947,-5.382600036613184,-6.153828000022761,-6.07306008632679,-5.925929040954987,-5.712570600482418,-5.4464626098047795,-5.157696571477064,-5.1683327812500055,-2.0552862187500036,-3.0846399374999973,-3.799293835937489,-3.779204218750008,-3.5882684453125027,-3.4749462829489968,-3.945562763721994,-4.437070469703361,-4.892036180304247,-5.274889870974867,-4.252289199432841,-2.9895129546220063,-4.448366903011776,-2.346927753179804,-5.1190000000000015,-3.024999999999996,-4.4959999999999996,-2.1529999999999987,-5.143999999999989,-4.852999999999996,-4.949999999999997,-8.250000000000004,-3.173087284118092,-6.424976319017877,-3.0531414856040198,-6.389597453837565,-2.2141513652878104,-1.910893499829033,-2.666040730620745,-0.9021838464474721,-3.854187500000001,-1.3825624999999953,-3.756874999999999,-0.3970624999999983,-5.012374999999987,-4.017312499999996,-4.144999999999996,-8.003750000000004,-1.5025063350499717,-6.094026980564819,-1.1402105192645615,-6.045158615784086,-3.323145141601562,-5.740137329101566,-3.20715024482727,-5.800029907913211,-3.3939999999999997,-5.982,-2.644,-3.8,-3.056,-2.846,-3.13,-1.03,-2.6280486029052734,-0.09004827148437455,-3.0041699927520753,-0.9253430871582028,-5.847198442061747,-1.1574833556903223,-5.335271998256157,-0.7582684186373141,-5.723374999999994,-0.5050624999999984,-1.3167500000000039,-0.11693749999999792,-2.7269374999999996,-4.391937500000001,-3.1915624999999963,-7.309062499999998,-2.9813075098314012,-6.180640877884917,-3.8787492100711414,-5.395391017894182,-5.803188279157847,-2.88124656250595,-5.536837072342427,-2.5587592588316266,-6.151999999999994,-2.2489999999999988,-2.9220000000000033,-1.7949999999999982,-4.547,-5.363000000000001,-4.384999999999996,-7.464999999999998,-3.724080359997488,-6.585968565305974,-4.1722346617224915,-6.2129502167878075,-5.99,-5.99,-5.99,-5.99,-5.99,-5.99,-3.8,-3.8,-3.8,-3.8,-4.8588,-4.76,-4.448,-3.8,-3.8,-3.8,-3.8,-4.7313600000000005,-4.65536,-4.38734,-3.8,-3.8,-3.8,-3.8,-4.083600000000001,-4.0760000000000005,-4.007,-3.8,-3.8,-3.8,-3.8,-3.2934200000000002,-3.3086200000000003,-3.34328,-3.8,-3.8,-3.8,-3.8,-3.0186000000000006,-3.043,-3.105,-3.8,-3.8,-3.8,-3.8,-2.9784,-2.872,-2.553,-3.8,-3.8,-3.8,-3.8,-2.95079,-2.84726,-2.577,-3.8,-3.8,-3.8,-3.8,-3.1374,-3.107,-2.889,-3.8,-3.8,-3.8,-3.8,-3.58033,-3.49017,-3.31139,-3.8,-3.8,-3.8,-3.8,-3.664,-3.591,-3.36,-3.8,-3.8,-3.8,-3.8,-3.6836,-3.702,-3.6670000000000003,-3.8,-3.8,-3.8,-3.8,-3.78071,-3.78831,-3.79265,-3.8,-3.8,-3.8,-3.8,-4.027,-4.016,-3.993,-3.8,-3.8,-3.8,-3.8,-4.18861,-4.14967,-4.03067,-3.8,-3.8,-3.8,-3.8,-4.29,-4.229,-4.0440000000000005,-3.8,-3.8,-3.8,-3.8,-4.328399999999999,-4.366,-4.507,-3.8,-3.8,-3.8,-3.8,-4.54943,-4.61522,-4.82105,-3.8,-3.8,-3.8,-3.8,-5.0793,-5.1705,-5.4975,-3.8,-3.8,-3.8,-3.8,-5.06842,-5.16722,-5.32509,-3.8,-3.8,-3.8,-3.8,-4.902,-4.948,-5.01],"legacy, tiles and rings":[-2.7002915262414033,-2.8802514919697613,-3.2894033690390563,-4.129093259520969,-5.65493556143207,-5.74296343710494,-3.3157434846177476,-1.177876564377374,-1.1371676866309672,-1.4084678939747173,-1.9183609340909886,-3.139721537752031,-5.210011477601848,-4.467708706471694,-2.844871091147969,-2.559748640151765,-2.0204770128409955,-2.2754233492415246,-2.421605774587966,-2.895644067189746,-3.8297546207654127,-5.311784859985372,-5.353679944163048,-3.180320548197128,-1.4163944574305682,-1.3692980849165177,-1.4176315569215274,-1.9641715296407787,-3.3750357845438637,-5.3154370458763704,-4.399095614011183,-2.842966215838719,-2.627659922819783,-1.9408166066592065,-2.0092924816356255,-2.0775271559395376,-2.5660573265352524,-3.5298658952854614,-4.626575444593579,-4.3191135397334275,-2.8519885254380464,-2.0627292886488466,-2.0856373356397464,-1.8027901889450009,-2.240698449491267,-3.643228773702082,-4.698261898173866,-4.009441696432908,-3.0941167603659205,-2.904566273720067,-2.020071751119899,-2.27180963452814,-2.2246051386553822,-2.58363957977365,-3.198000000000001,-3.2040000000000024,-2.5800000000000023,-2.798,-3.3999999999999986,-3.095999999999999,-2.6119999999999988,-3.0319999999999987,-3.3520000000000008,-2.7620000000000022,-2.5920000000000005,-3.1959999999999997,-3.2640000000000002,-2.7039999999999993,-4.643151246247592,-4.090435961213007,-3.3652019247301377,-2.2920000000000025,-1.158000000000002,-1.6179999999999994,-3.113999999999999,-3.85,-4.025999999999999,-4.313999999999998,-3.7780000000000005,-2.140000000000002,-1.2360000000000004,-1.8540000000000003,-2.6740000000000004,-3.186,-4.1279999999999974,-6.067658942847497,-5.0958505221021495,-3.3369585985866577,-1.0880000000000019,-0.39599999999999985,-1.3999999999999997,-2.6339999999999995,-3.9119999999999986,-5.361999999999998,-5.452000000000001,-3.500000000000002,-1.532,-0.9279999999999998,-1.0320000000000005,-1.7100000000000002,-3.6599999999999997,-5.533999999999998,-5.04705370445547,-4.200173171684486,-2.716767095484088,-1.1720000000000002,-0.8140000000000003,-1.0199999999999998,-2.141999999999999,-4.427999999999998,-5.834,-5.016000000000002,-3.3480000000000008,-2.07,-0.8620000000000008,-0.32400000000000007,-1.8119999999999992,-4.252,-5.324000000000001,-4.239979873666784,-3.750633199317823,-2.948013668089696,-2.22,-1.2380000000000002,-1.1319999999999986,-2.7079999999999984,-4.35,-3.8,-3.8,-3.7440000000000007,-2.424000000000001,-0.954,-1.1239999999999988,-2.6519999999999992,-3.7100000000000004,-4.198,-4.1655717938217345,-3.83242940568262,-3.442815844923696,-2.7480000000000007,-2.1199999999999988,-2.6439999999999984,-3.264,-3.0800000000000014,-3.0860000000000003,-3.596,-3.406000000000001,-2.436,-2.3699999999999983,-2.9299999999999993,-2.8680000000000003,-2.7300000000000004,-3.4219999999999997,-3.7221469697834566,-3.4091899532707353,-3.018994691697873,-3.259999999999999,-4.059999999999999,-4.204,-2.9960000000000013,-2.0500000000000003,-2.226000000000001,-2.370000000000001,-2.356,-3.2799999999999985,-4.315999999999999,-4.022,-2.984,-2.64,-2.4360000000000013,-2.3283078442176808,-2.1103836009389494,-2.520497960731304,-4.437999999999997,-5.545999999999999,-4.580000000000001,-3.0060000000000002,-1.9940000000000009,-1.1160000000000017,-0.7740000000000007,-2.159999999999999,-4.337999999999998,-5.12,-4.556,-3.8419999999999996,-2.5900000000000003,-0.8620000000000019,-1.6162794096849886,-1.6673242269426123,-2.91613428503779,-5.015999999999999,-5.406000000000001,-4.712000000000001,-3.6760000000000006,-1.7940000000000016,-0.12600000000000056,-0.5339999999999989,-2.6099999999999985,-4.231999999999999,-5.02,-5.378,-4.37,-1.9260000000000006,-0.29800000000000043,-2.8641477289664596,-2.8344424875232916,-3.3368399408817075,-4.2059999999999995,-4.734,-4.954000000000001,-3.602000000000001,-1.4580000000000009,-0.6959999999999996,-1.5039999999999993,-2.4579999999999993,-3.55,-5.023999999999999,-5.328,-3.656000000000001,-1.878,-1.2919999999999994,-3.1320154537946854,-2.889053081850137,-2.820464702817607,-3.2319999999999993,-4.154,-4.022000000000001,-2.808000000000001,-2.2499999999999996,-2.4139999999999997,-2.2219999999999995,-2.3019999999999996,-3.4399999999999995,-4.246,-3.690000000000001,-2.996,-2.864,-2.406,-2.8811358883638665,-2.6673204612918053,-2.64072819943886,-2.866,-2.7120000000000006,-2.226,-2.6999999999999993,-3.6559999999999993,-3.5940000000000003,-3.04,-3.1599999999999997,-3.1200000000000006,-2.306000000000001,-2.128,-2.998,-3.452,-3.174,-4.05494823363544,-3.676694312628875,-3.299512286438255,-2.046000000000001,-0.7800000000000005,-1.2799999999999991,-3.037999999999999,-4.092,-4.385999999999999,-4.632,-3.890000000000001,-2.008000000000001,-0.8780000000000003,-1.4859999999999998,-2.5460000000000003,-3.31,-4.452,-5.406087531332521,-4.798011528506675,-3.3475630214938454,-1.0060000000000016,-0.2639999999999996,-1.3159999999999992,-2.618,-3.9899999999999993,-5.493999999999999,-5.592,-3.5460000000000025,-1.4520000000000008,-0.7840000000000001,-0.9200000000000003,-1.6520000000000001,-3.6559999999999997,-5.643999999999999,-4.408503592118537,-2.488968721703816,-5.948812667346547,-5.300999278268706,-4.632720998014948,-6.15683235131131,-1.2028066519142089,-4.5339402912844955,-1.402050488919631,-4.295308856312225,-1.6696402707466704,-2.9686786744153495,-3.919262380652163,-1.8795110566980455,-4.921641441000989,-3.234177273471124,-3.0500000000000003,-2.69,-4.388,-3.132,-3.2420000000000004,-2.352,-2.41,-2.722,-2.168,-3.244,-2.21,-2.9,-4.044,-3.684,-3.7840000000000003,-2.962,-3.1,-2.58,-2.646,-4.274,-3.3939999999999997,-5.982,-2.644,-3.8,-3.056,-2.846,-3.13,-1.03,-2.62,-0.09399999999999992,-3.376,-2.1619999999999995,-2.7600000000000002,-3.29,-1.9380000000000002,-2.754,-2.2079999999999997,-2.356,-3.932,-3.116,-3.64,-2.642,-3.5500000000000003,-3.48,-2.3120000000000003,-3.412,-1.662,-2.862,-1.92,-2.36,-1.21,-4.686,-1.5359999999999996,-4.7540000000000004,-4.379999999999999,-4.722,-5.066,-2.7560000000000007,-3.5,-0.96,-1.9300000000000002,-1.248,-0.5560000000000002,-1.5759999999999998,-5.785154418945313,-5.557957837729371,-5.99,-5.99,-5.99,-3.9458370460649497,-3.8,-3.8,-3.8,-3.8,-4.8588,-4.76,-4.448,-3.8,-3.8,-3.8,-3.8,-4.7313600000000005,-4.65536,-4.38734,-3.8,-3.8,-3.8,-3.8,-4.083600000000001,-4.0760000000000005,-4.007,-3.8,-3.8,-3.8,-3.8,-3.2934200000000002,-3.3086200000000003,-3.34328,-3.8,-3.8,-3.8,-3.8,-3.0186000000000006,-3.043,-3.105,-3.8,-3.8,-3.8,-3.8,-2.9784,-2.872,-2.553,-3.8,-3.8,-3.8,-3.8,-2.95079,-2.84726,-2.577,-3.8,-3.8,-3.8,-3.8,-3.1374,-3.107,-2.889,-3.8,-3.8,-3.8,-3.8,-3.58033,-3.49017,-3.31139,-3.8,-3.8,-3.8,-3.8,-3.664,-3.591,-3.36,-3.8,-3.8,-3.8,-3.8,-3.6836,-3.702,-3.6670000000000003,-3.8,-3.8,-3.8,-3.8,-3.78071,-3.78831,-3.79265,-3.8,-3.8,-3.8,-3.8,-4.027,-4.016,-3.993,-3.8,-3.8,-3.8,-3.8,-4.18861,-4.14967,-4.03067,-3.8,-3.8,-3.8,-3.8,-4.29,-4.229,-4.0440000000000005,-3.8,-3.8,-3.8,-3.8,-4.328399999999999,-4.366,-4.507,-3.8,-3.8,-3.8,-3.8,-4.54943,-4.61522,-4.82105,-3.8,-3.8,-3.8,-3.8,-5.0793,-5.1705,-5.4975,-3.8,-3.8,-3.8,-3.8,-5.06842,-5.16722,-5.32509,-3.8,-3.8,-3.8,-3.8,-4.902,-4.948,-5.01,-3.6,-3.6,-3.6,-3.6,-0.9295999999999999,-0.8119999999999999,-0.48999999999999994,-3.6,-3.6,-3.6,-3.6,-0.9295199999999999,-0.8019999999999999,-0.4786399999999999,-3.6,-3.6,-3.6,-3.6,-1.0423999999999998,-0.8979999999999999,-0.5099999999999999,-3.6,-3.6,-3.6,-3.6,-1.17592,-1.03912,-0.6012,-3.6,-3.6,-3.6,-3.6,-1.2448,-1.108,-0.6639999999999999,-3.6,-3.6,-3.6,-3.6,-1.3068,-1.36,-1.54,-3.6,-3.6,-3.6,-3.6,-1.4490399999999999,-1.48776,-1.6492,-3.6,-3.6,-3.6,-3.6,-1.8404,-1.8860000000000001,-2.02,-3.6,-3.6,-3.6,-3.6,-2.2626399999999998,-2.27784,-2.36792,-3.6,-3.6,-3.6,-3.6,-2.4228000000000005,-2.422,-2.4480000000000004,-3.6,-3.6,-3.6,-3.6,-2.4576,-2.5860000000000003,-3.036,-3.6,-3.6,-3.6,-3.6,-2.4157599999999997,-2.572,-3.04728,-3.6,-3.6,-3.6,-3.6,-2.3184,-2.478,-3.024,-3.6,-3.6,-3.6,-3.6,-2.1967999999999996,-2.3813600000000004,-2.9215199999999997,-3.6,-3.6,-3.6,-3.6,-2.15,-2.3400000000000003,-2.876,-3.6,-3.6,-3.6,-3.6,-2.0768000000000004,-2.0540000000000003,-1.9620000000000002,-3.6,-3.6,-3.6,-3.6,-1.89368,-1.89512,-1.82368,-3.6,-3.6,-3.6,-3.6,-1.4716,-1.464,-1.44,-3.6,-3.6,-3.6,-3.6,-1.0808000000000002,-1.0732000000000002,-1.1092000000000002,-3.6,-3.6,-3.6,-3.6,-0.9716,-0.96,-0.9999999999999999]},"legacyOnlyBounds":[-167.1642532240555,161.1942532240555]} \ No newline at end of file diff --git a/packages/core/src/lib/__fixtures__/terrain-lag-scenes.ts b/packages/core/src/lib/__fixtures__/terrain-lag-scenes.ts new file mode 100644 index 0000000000..36c61b669a --- /dev/null +++ b/packages/core/src/lib/__fixtures__/terrain-lag-scenes.ts @@ -0,0 +1,206 @@ +import { + AnyNode, + SiteNode, + TerrainBreakNode, + TerrainTileNode, +} from '../../schema' +import { encodeTerrainField } from '../terrain-codec' +import { createTerrainField, type TerrainField } from '../terrain-field' + +/* + * Scenes shaped like a large graded site (24 tiles, five retaining breaks), small enough + * for a test: a 35 × 50 m lot on 3 × 3 tiles of 32 m, graded between −6 and 0 m with a gentle + * noise, and breaks of each kind the authority supports. Deterministic: no random source, so the + * heights an old build read are the heights this file reads. + */ + +type Point = [number, number] +export type TerrainLagScene = { + name: string + site: SiteNode + nodes: Record + rings: Point[][] + open: Point[] | null +} + +const LOT: Point[] = [ + [-17.5, -25], + [17.5, -25], + [17.5, 25], + [-17.5, 25], +] + +const noise = (a: number, b: number) => { + let h = (Math.imul(a + 1013, 374761393) ^ Math.imul(b + 7919, 668265263)) >>> 0 + h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0 + return ((h ^ (h >>> 16)) >>> 0) / 4294967296 +} + +let roughness = 0.05 +let plateau = 0 + +const groundHeight = (x: number, z: number) => + -3 + + 2.6 * Math.sin(x / 9) * Math.cos(z / 7) - + 0.4 * Math.sin((x + z) / 3.1) + + roughness * noise(Math.round(x * 2), Math.round(z * 2)) + + (plateau && x >= 0 && x < 32 && z >= 0 && z < 32 ? plateau : 0) + +function tileHeights(ix: number, iz: number): TerrainField { + const field = createTerrainField({ origin: [ix * 32, iz * 32], spacing: 0.5, cols: 65, rows: 65, step: 0.01 }) + for (let row = 0; row < 65; row++) + for (let col = 0; col < 65; col++) + field.heights[row * 65 + col] = Math.round( + groundHeight(ix * 32 + col * 0.5, iz * 32 + row * 0.5) / field.step, + ) + return field +} + +const ring = (x0: number, z0: number, x1: number, z1: number): Point[] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], + [x0, z0], +] + +export const RING_A = ring(-8.7, -5.5, -1.65, 4.45) +export const RING_B = ring(-6, 12, 11, 20) +export const RING_C = ring(11.2, 5.6, 14.8, 8.4) +export const OPEN_LINE: Point[] = [ + [4, -40], + [4, 40], +] + +export function terrainLagScene( + name: string, + options: { + tiles?: boolean + legacy?: boolean + breaks?: { line: Point[]; left: number | 'ground'; right: number | 'ground' }[] + /** Sample-to-sample noise in metres (default 0.05); the owner's graded ground is smooth. */ + roughness?: number + /** A step in metres on the tile whose x and z are 0..32 (default none): a cliff on its borders. */ + plateau?: number + } = {}, +): TerrainLagScene { + const { tiles = true, legacy = false, breaks = [] } = options + roughness = options.roughness ?? 0.05 + plateau = options.plateau ?? 0 + const siteId = 'site_lag' + const tileNodes = tiles + ? [-1, 0, 1].flatMap((iz) => + [-1, 0, 1].map((ix) => + TerrainTileNode.parse({ + id: `terrain-tile_${ix + 1}_${iz + 1}`, + parentId: siteId, + ix, + iz, + level: 0, + step: 0.01, + heights: encodeTerrainField(tileHeights(ix, iz)).heights, + }), + ), + ) + : [] + const breakNodes = breaks.map((entry, index) => + TerrainBreakNode.parse({ + id: `terrain-break_${index}`, + parentId: siteId, + kind: 'retaining', + line: entry.line, + left: entry.left, + right: entry.right, + }), + ) + let terrain: ReturnType | undefined + if (legacy) { + const base = createTerrainField({ origin: [-16, -16], spacing: 0.5, cols: 65, rows: 65, step: 0.01 }) + for (let row = 0; row < 65; row++) + for (let col = 0; col < 65; col++) + base.heights[row * 65 + col] = Math.round(groundHeight(-16 + col * 0.5, -16 + row * 0.5) / 0.01) + terrain = encodeTerrainField(base) + } + const site = SiteNode.parse({ + id: siteId, + polygon: { type: 'polygon', points: LOT }, + children: [...tileNodes, ...breakNodes].map((node) => node.id), + ...(terrain ? { terrain } : {}), + }) + const nodes: Record = Object.fromEntries( + [site, ...tileNodes, ...breakNodes].map((node) => [node.id, node]), + ) + return { + name, + site, + nodes, + rings: breaks.filter((entry) => entry.line[0]?.join() === entry.line.at(-1)?.join()).map((entry) => entry.line), + open: breaks.find((entry) => entry.line[0]?.join() !== entry.line.at(-1)?.join())?.line ?? null, + } +} + +/** The scenes the equality tests and the profile read. */ +export function terrainLagScenes(): TerrainLagScene[] { + return [ + terrainLagScene('tiles only', {}), + terrainLagScene('three rings, ground outside', { + breaks: [ + { line: RING_A, left: -3.8, right: 'ground' }, + { line: RING_B, left: -4.7, right: 'ground' }, + { line: RING_C, left: -3.6, right: 'ground' }, + ], + }), + terrainLagScene('open break', { breaks: [{ line: OPEN_LINE, left: 2, right: 'ground' }] }), + terrainLagScene('open break, ground on its left', { + breaks: [{ line: OPEN_LINE, left: 'ground', right: -2.5 }], + }), + terrainLagScene('one ring, numeric both sides', { + breaks: [{ line: RING_B, left: -4.7, right: 1.2 }], + }), + terrainLagScene('legacy only', { tiles: false, legacy: true }), + terrainLagScene('legacy and a ring', { + tiles: false, + legacy: true, + breaks: [{ line: RING_A, left: -3.8, right: 'ground' }], + }), + terrainLagScene('legacy, tiles and rings', { + legacy: true, + breaks: [ + { line: RING_A, left: -3.8, right: 'ground' }, + { line: RING_C, left: -3.6, right: 'ground' }, + ], + }), + ] +} + +/** Sample points: a lattice over the lot and beyond, every tile edge, and both sides of each break. */ +export function terrainLagPoints(scene: TerrainLagScene): [number, number][] { + const points: [number, number][] = [] + for (let x = -44; x <= 44; x += 5.3) for (let z = -44; z <= 44; z += 5.3) points.push([x, z]) + for (const t of [-48, -32, 0, 32, 48]) for (let s = -30; s <= 30; s += 7.7) points.push([t, s], [s, t]) + const far: Point[] = [ + [-90, 0], + [90, 30], + [0, -100], + [0, 130], + [-130, 140], + [70, -70], + ] + points.push(...far) + const lines = [...scene.rings, ...(scene.open ? [scene.open] : [])] + for (const line of lines) + for (let i = 0; i < line.length - 1; i++) { + const a = line[i] as Point + const b = line[i + 1] as Point + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + const nx = (b[1] - a[1]) / length + const nz = -(b[0] - a[0]) / length + for (const u of [0, 0.13, 0.5, 0.87, 1]) + for (const d of [-1.7, -0.5, -0.12, 0, 0.12, 0.5, 1.7]) { + const x = a[0] + (b[0] - a[0]) * u + const z = a[1] + (b[1] - a[1]) * u + points.push([x + nx * d, z + nz * d]) + } + } + return points +} diff --git a/packages/core/src/lib/cutter-host.ts b/packages/core/src/lib/cutter-host.ts index 5cbbe0260e..97a4c416aa 100644 --- a/packages/core/src/lib/cutter-host.ts +++ b/packages/core/src/lib/cutter-host.ts @@ -3,6 +3,7 @@ import { getScaledDimensions } from '../schema/nodes/item' import { liftedManualSlab } from './floor-construction-lift' import { selectSlabSupportForItem } from './item-slab-support' import { getRenderableSlabPolygon, slabPolygonContextForLevel } from './slab-polygon' +import { slabTerrainHeightAt } from './slab-terrain' export function isCutterName(name: string): boolean { return name === 'cutout' || name === 'cut:wall' || name === 'cut:ceiling' || name === 'cut:slab' @@ -33,7 +34,10 @@ export function resolveCutterHost( slabs, { position: node.position, dimensions: getScaledDimensions(node), rotation: node.rotation }, (slab) => getRenderableSlabPolygon(slab, context), - { preferredSlabId: node.supportSlabId }, + { + preferredSlabId: node.supportSlabId, + elevationOf: (slab) => slabTerrainHeightAt(slab, nodes, node.position[0], node.position[2]), + }, ) } if (name !== 'cutout' && host?.type !== name.slice(4)) return diff --git a/packages/core/src/lib/floor-construction-lift.ts b/packages/core/src/lib/floor-construction-lift.ts index cacfeebaf8..636f8d0184 100644 --- a/packages/core/src/lib/floor-construction-lift.ts +++ b/packages/core/src/lib/floor-construction-lift.ts @@ -13,6 +13,15 @@ export function floorConstructionLift( nodes: Readonly>, node: AnyNode, ): number { + if ( + node.type === 'slab' && + node.terrainMode === 'draped' && + !node.plateRole && + node.boundary !== 'auto' && + !node.autoFromWalls && + !node.recessed + ) + return 0 let cache = memo.get(nodes) if (!cache) { cache = new WeakMap() diff --git a/packages/core/src/lib/floor-foundation-datum.ts b/packages/core/src/lib/floor-foundation-datum.ts index 4716dad158..d843606c7d 100644 --- a/packages/core/src/lib/floor-foundation-datum.ts +++ b/packages/core/src/lib/floor-foundation-datum.ts @@ -1,6 +1,10 @@ import { roofFaceShapes } from '../registry/roofs' import type { AnyNode, SlabNode } from '../schema' -import { DEFAULT_SLAB_ELEVATION, MIN_SLAB_THICKNESS } from '../schema/nodes/slab' +import { + DEFAULT_SLAB_ELEVATION, + DEFAULT_SLAB_THICKNESS, + MIN_SLAB_THICKNESS, +} from '../schema/nodes/slab' import { wallOverlapsSlabFootprint } from '../systems/slab/slab-support' import { getWallArcData } from '../systems/wall/wall-curve' import { wallOpeningBand } from './floor-opening-footprints' @@ -141,6 +145,22 @@ export function footprintLift(nodes: Readonly>, plate: S : 0 } +/** + * A plate that holds its underside, given a new top: a thicker or a thinner floor. A top put under + * the underside leaves no floor to thin, so the plate moves whole, as thick as it was (a stored + * plate thinner than a slab can be takes a slab's thickness): no write stores a floor with no + * thickness. + */ +export function upperFloorTopWrite( + plate: Pick, + nextTop: number, +): { elevation: number; thickness: number } { + const round = (value: number) => Math.round(value * 1e6) / 1e6 + const thinned = round(plate.thickness + nextTop - (plate.floorHeight ?? plate.elevation)) + const whole = plate.thickness >= MIN_SLAB_THICKNESS ? plate.thickness : DEFAULT_SLAB_THICKNESS + return { elevation: round(nextTop), thickness: thinned >= MIN_SLAB_THICKNESS ? thinned : whole } +} + export function upperFloorHeightControl( nodes: Readonly>, plate: SlabNode, diff --git a/packages/core/src/lib/floor-intent-changes.ts b/packages/core/src/lib/floor-intent-changes.ts index f68b00c446..f2e0beea94 100644 --- a/packages/core/src/lib/floor-intent-changes.ts +++ b/packages/core/src/lib/floor-intent-changes.ts @@ -23,6 +23,7 @@ import { floorPlateHoldsUnderside, footprintSupportsNode, supportDerivedFloorHeight, + upperFloorTopWrite, } from './floor-foundation-datum' import { changedLevelConstructionDisplacements, @@ -103,8 +104,7 @@ export function expandFloorIntentChanges( data: { ...update.data, floorHeight: undefined, - thickness: roundFloorElevation(plate.thickness + nextTop - currentTop), - elevation: roundFloorElevation(nextTop), + ...upperFloorTopWrite(plate, nextTop), } as Partial, } } diff --git a/packages/core/src/lib/floor-plate-thickness.test.ts b/packages/core/src/lib/floor-plate-thickness.test.ts new file mode 100644 index 0000000000..a044417669 --- /dev/null +++ b/packages/core/src/lib/floor-plate-thickness.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, test } from 'bun:test' +import { agentHouse, runSettled } from '../agent-operations/__fixtures__/sloped-lots' +import type { AnyNode, LevelNode, SlabNode } from '../schema' +import { MIN_SLAB_THICKNESS } from '../schema/nodes/slab' +import { filterDerivedNodeWrites } from '../store/derived-node-guard' +import { upperFloorTopWrite } from './floor-foundation-datum' +import { expandFloorIntentChanges } from './floor-intent-changes' + +/* + * A floor plate that stands over a level holds its underside: a new top makes it thicker or + * thinner. No write may leave it with no thickness (a scene of 13 Nov 2026 stored one at + * -1.419 m: a floor put back 1.47 m lower came out thinner than nothing). + */ + +describe('a new top on a plate that holds its underside', () => { + const plate = { elevation: 0.3, thickness: 0.2 } + for (const [name, top, expected] of [ + ['raised: thicker, the underside held', 0.5, { elevation: 0.5, thickness: 0.4 }], + [ + 'lowered within the floor: thinner, the underside held', + 0.15, + { elevation: 0.15, thickness: 0.05 }, + ], + ['lowered to the thinnest slab', 0.12, { elevation: 0.12, thickness: MIN_SLAB_THICKNESS }], + [ + 'lowered under the underside: the plate moves whole', + 0.05, + { elevation: 0.05, thickness: 0.2 }, + ], + ['lowered far under it', -1.4, { elevation: -1.4, thickness: 0.2 }], + ] as const) + test(name, () => { + expect(upperFloorTopWrite(plate, top)).toEqual(expected) + }) + + test('a plate stored thinner than a slab can be takes a slab thickness when its top is written', () => { + expect(upperFloorTopWrite({ elevation: 0.05, thickness: -1.4188 }, 0.05)).toEqual({ + elevation: 0.05, + thickness: 0.05, + }) + }) +}) + +describe('the main floor of a house with a level under it, lifted by the ground before that level was added', () => { + let house = agentHouse({ ground: (_x, z) => -0.16 * z }) + house = runSettled(house, 'add_level', { position: 'below', name: 'Lower', height: 2.7 }).nodes + const lower = Object.values(house).find( + (node): node is LevelNode => node.type === 'level' && node.name === 'Lower', + ) as LevelNode + house = runSettled(house, 'create_room', { + levelId: lower.id, + name: 'Rumpus', + polygon: [ + [-6, -4], + [6, -4], + [6, 4], + [-6, 4], + ], + }).nodes + const main = Object.values(house).find( + (node): node is SlabNode => node.type === 'slab' && node.parentId === 'level_ground', + ) as SlabNode + + test('it kept the lift: 0.69 m over its base, 0.05 m thick', () => { + expect(main.elevation).toBeCloseTo(0.69, 2) + expect(main.thickness).toBe(0.05) + }) + + for (const top of [0.05, 0.3, 0.66, 0.9]) + test(`its top written to ${top} m: the floor is stored at least ${MIN_SLAB_THICKNESS} m thick, by the intent and by the store`, () => { + const update = [{ id: main.id, data: { elevation: top } as Partial }] + const expanded = expandFloorIntentChanges(house, update).find((each) => each.id === main.id) + ?.data as Partial + expect(expanded.elevation).toBe(top) + expect(expanded.thickness as number).toBeGreaterThanOrEqual(MIN_SLAB_THICKNESS) + const kept = filterDerivedNodeWrites(house, { update }).update?.find( + (each) => each.id === main.id, + )?.data as Partial + expect(kept.elevation).toBe(top) + expect(kept.thickness as number).toBeGreaterThanOrEqual(MIN_SLAB_THICKNESS) + }) +}) diff --git a/packages/core/src/lib/grade-standing.test.ts b/packages/core/src/lib/grade-standing.test.ts index ce49358e57..87b4246459 100644 --- a/packages/core/src/lib/grade-standing.test.ts +++ b/packages/core/src/lib/grade-standing.test.ts @@ -10,7 +10,7 @@ import { ZoneNode, } from '../schema' import hillside from './__fixtures__/owner-hillside-grade.json' -import { levelGradeStanding } from './grade-standing' +import { groundCovers, levelGradeStanding } from './grade-standing' import { levelGroundBox } from './ground-window' import { encodeTerrainField } from './terrain-codec' import { createTerrainField } from './terrain-field' @@ -286,3 +286,71 @@ test('a pad outside every room (an entry stoop) is not a floor the ground buries expect(levelGradeStanding(nodes, 'level_g')).toBe('partly-below-grade') expect(levelGradeStanding(withRoom, 'level_g')).toBe('at-grade') }) +describe('groundCovers', () => { + test('on a hillside floor it is the buried half that the ground covers', () => { + const covers = groundCovers(hillsideStack(6), 'level_garden') + expect(covers(-3, 0)).toBe(false) + expect(covers(3, 0)).toBe(true) + }) + + test('a floor at grade is covered nowhere, an id that is no level either', () => { + expect(groundCovers(hillsideStack(6), 'level_street')(3, 0)).toBe(false) + expect(groundCovers(hillsideStack(6), 'level_missing')(3, 0)).toBe(false) + }) + + test('a floor the ground covers outright is covered everywhere', () => { + const nodes = hillsideStack(6) + const buried = { + ...nodes, + site_a: SiteNode.parse({ + id: 'site_a', + children: ['building_a'], + terrain: encodeTerrainField({ + ...createTerrainField({ cols: 33, rows: 33, spacing: 1, origin: [-16, -16] }), + heights: new Int16Array(33 * 33).fill(600), + }), + }), + } as typeof nodes + const covers = groundCovers(buried, 'level_garden') + expect(covers(-3, 0)).toBe(true) + expect(covers(3, 0)).toBe(true) + }) + + test('on a flat site a split level is covered over its sunken room only', () => { + const slab = (id: string, polygon: Array<[number, number]>, elevation: number) => + SlabNode.parse({ id, parentId: 'level_split', polygon, elevation }) + const nodes = buildNodes([ + BuildingNode.parse({ id: 'building_a', children: ['level_split'] }), + LevelNode.parse({ + id: 'level_split', + parentId: 'building_a', + level: 0, + children: ['slab_raised', 'slab_sunken'], + }), + slab( + 'slab_raised', + [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + 0.05, + ), + slab( + 'slab_sunken', + [ + [4, 0], + [8, 0], + [8, 4], + [4, 4], + ], + -1.2, + ), + ]) + expect(levelGradeStanding(nodes, 'level_split')).toBe('partly-below-grade') + const covers = groundCovers(nodes, 'level_split') + expect(covers(2, 2)).toBe(false) + expect(covers(6, 2)).toBe(true) + }) +}) diff --git a/packages/core/src/lib/grade-standing.ts b/packages/core/src/lib/grade-standing.ts index afa49eed01..e86341c813 100644 --- a/packages/core/src/lib/grade-standing.ts +++ b/packages/core/src/lib/grade-standing.ts @@ -3,6 +3,7 @@ import { BELOW_GRADE_TOLERANCE, getLevelElevations, isLevelBelowGrade, + levelFloorWorldY, levelPlaneWorldY, } from '../services/storey' import { pointInPolygon } from '../systems/slab/slab-support' @@ -66,6 +67,37 @@ export function levelGradeStanding( return buried === samples.length ? 'below-grade' : 'partly-below-grade' } +/** + * Whether the ground stands over `levelId`'s floor at a plan point of the level (building-local + * metres): everywhere on a level below grade, nowhere on one at grade, and on a level only partly + * below grade the floor under the point judged against the terrain, or against the datum on a flat + * site (the sunken room of a split level), the reading `levelGradeStanding` makes of the whole + * floor. A wall or a room asks it where the level as a whole is only partly buried. + */ +export function groundCovers( + nodes: Record, + levelId: string, +): (x: number, z: number) => boolean { + const standing = levelGradeStanding(nodes, levelId) + const level = nodes[levelId as LevelNode['id']] + const floorY = levelFloorWorldY(nodes, levelId) + if (standing !== 'partly-below-grade' || level?.type !== 'level' || floorY === null) { + const covered = standing === 'below-grade' + return () => covered + } + const field = terrainFieldOverLevel(nodes, level) + const placed = placedBuilding(nodes, level) + const plane = levelPlaneWorldY(nodes, levelId) + const slabs = floorSlabsOf(nodes, level) + return (x, z) => { + const slab = plane === null ? undefined : slabs.find((s) => pointInPolygon(x, z, s.polygon)) + const floor = plane !== null && slab ? plane + slab.elevation : floorY + if (!field) return floorBuriedOnFlatSite(floor) + const [worldX, worldZ] = levelLocalToWorldXZ(placed, x, z) + return heightAt(field, worldX, worldZ) - floor > BELOW_GRADE_TOLERANCE + } +} + /** * A flat site with no ground line named: the datum is the ground under every floor, and each floor * slab of the level is judged against it as the sampled path judges them against the field. A split @@ -100,7 +132,7 @@ const floorSlabsMemo = new WeakMap>() * level with rooms, under one of them. A slab outside every room (an entry pad, a stoop) is the * site's, as flatwork is, not a floor the ground can bury. */ -function floorSlabsOf(nodes: Record, level: LevelNode): SlabNode[] { +export function floorSlabsOf(nodes: Record, level: LevelNode): SlabNode[] { let levels = floorSlabsMemo.get(nodes) if (!levels) { levels = new Map() @@ -244,7 +276,7 @@ export function terrainFieldOverLevel( const site = (building?.parentId ? nodes[building.parentId as AnyNodeId] : undefined) ?? Object.values(nodes).find((node) => node.type === 'site') - return site?.type === 'site' ? terrainFieldOf(site) : null + return site?.type === 'site' ? terrainFieldOf(site, nodes) : null } /** @@ -285,6 +317,12 @@ export function footprintFloorSamples( return samples } +function placedBuilding(nodes: Record, level: LevelNode): BuildingNode | null { + const buildingId = getLevelElevations(nodes).get(level.id)?.buildingId + const building = buildingId ? nodes[buildingId as AnyNodeId] : undefined + return building?.type === 'building' ? (building as BuildingNode) : null +} + function slabSamples(polygon: Array<[number, number]>, spacing: number): Array<[number, number]> { const samples: Array<[number, number]> = [...polygon] const xs = polygon.map(([x]) => x) diff --git a/packages/core/src/lib/item-slab-support.ts b/packages/core/src/lib/item-slab-support.ts index 841de25dd6..755b229ce6 100644 --- a/packages/core/src/lib/item-slab-support.ts +++ b/packages/core/src/lib/item-slab-support.ts @@ -28,23 +28,34 @@ export function selectSlabSupportForItem( slabs: Iterable, footprint: Footprint, renderedPolygon: (slab: SlabNode) => [number, number][], - options: { maxElevation?: number | null; preferredSlabId?: string | null } = {}, + options: { + maxElevation?: number | null + preferredSlabId?: string | null + elevationOf?: (slab: SlabNode) => number + } = {}, ): SlabNode | undefined { - const { maxElevation, preferredSlabId } = options + const { maxElevation, preferredSlabId, elevationOf = (slab) => slab.elevation ?? 0.05 } = options if (maxElevation == null && preferredSlabId === 'ground') return let highest: SlabNode | undefined + let highestElevation = Number.NEGATIVE_INFINITY let preferred: SlabNode | undefined let covering: SlabNode | undefined + let coveringElevation = Number.NEGATIVE_INFINITY let prefersBase = false for (const slab of slabs) { if (slab.id === preferredSlabId && slab.plateRole === 'base') prefersBase = true - const elevation = slab.elevation ?? 0.05 + const elevation = elevationOf(slab) if (maxElevation != null && elevation > maxElevation + SUPPORT_ELEVATION_EPSILON) continue if (!slabSupportsItemFootprint(slab, footprint, renderedPolygon(slab))) continue - if (!highest || elevation > (highest.elevation ?? 0.05)) highest = slab + if (!highest || elevation > highestElevation) { + highest = slab + highestElevation = elevation + } if (slab.id === preferredSlabId) preferred = slab - if (slab.plateRole === 'platform' && (!covering || elevation > (covering.elevation ?? 0.05))) + if (slab.plateRole === 'platform' && (!covering || elevation > coveringElevation)) { covering = slab + coveringElevation = elevation + } } if (maxElevation == null) { if (prefersBase && covering) return covering diff --git a/packages/core/src/store/live-previews.ts b/packages/core/src/lib/live-previews.ts similarity index 100% rename from packages/core/src/store/live-previews.ts rename to packages/core/src/lib/live-previews.ts diff --git a/packages/core/src/lib/ramp-facts.ts b/packages/core/src/lib/ramp-facts.ts new file mode 100644 index 0000000000..ea63ca0a86 --- /dev/null +++ b/packages/core/src/lib/ramp-facts.ts @@ -0,0 +1,320 @@ +import type { SceneNodes } from '../agent-operations/types' +import { refuse } from '../agent-tools/refusal' +import type { AnyNode, AnyNodeId, BuildingNode, DoorNode, RampNode } from '../schema' +import { getLevelElevations, levelFloorWorldY } from '../services/storey' +import { getWallCurveFrameAt, getWallCurveLength } from '../systems/wall/wall-curve' +import { getWallThickness } from '../systems/wall/wall-footprint' +import { getWallBodyCenterOffset } from '../systems/wall/wall-frame' +import { findLevelAncestorId, resolveBuildingForLevel } from './node-ancestry' +import { getOpeningFloorDatum } from './opening-floor-datum' +import { pointInPolygon } from './polygon-relations' +import { + type RampPoint, + type RampStation, + rampCentrelineMaximumSlopePercent, + rampHeightAt, + rampLength, + rampMaximumSlopePercent, + rampStations, +} from './ramp' +import { slabTerrainHeightAt } from './slab-terrain' + +export type RampTargetMatch = { + targetId: string + kind: 'door' | 'level' | 'unknown' + matched: boolean + horizontalErrorM: number | null + heightErrorM: number | null + planeErrorM: number | null + planeToleranceM: number | null + lateralErrorM: number | null + lateralToleranceM: number | null + point: RampPoint | null + heightM: number | null + levelId: string | null +} +export type RampWarning = { + code: 'ramp_slope_exceeded' | 'ramp_target_mismatch' + message: string + endpoint?: 'start' | 'end' + targetId?: string +} +export type RampTransitionFacts = { + lengthM: number + startDistanceM: number + endDistanceM: number + startHeightM: number + endHeightM: number + startGradePercent: number + endGradePercent: number +} +export type RampFacts = { + lengthM: number + riseM: number + averageSlopePercent: number + maximumSlopePercent: number + centrelineMaximumSlopePercent: number + maxSlopePercent: number + heightToleranceM: number + startTransitionM: number + endTransitionM: number + plateauLengthM: number + transitions: { start: RampTransitionFacts; end: RampTransitionFacts } + endpoints: { + start: { point: RampPoint; heightM: number } + end: { point: RampPoint; heightM: number } + } + targets: { start: RampTargetMatch | null; end: RampTargetMatch | null } + warnings: RampWarning[] + retaining: { + kind: 'retaining_wall' + heightM: number + thicknessM: number + sides: ('left' | 'right')[] + } +} +const HEIGHT_TOLERANCE = 0.05 +const asNodes = (nodes: SceneNodes) => nodes as Record +type TargetFrame = { building: BuildingNode; baseY: number; levelId: string } + +function targetBuilding(ramp: RampNode, levelId: string, nodes: SceneNodes): BuildingNode | null { + const id = resolveBuildingForLevel(levelId as AnyNodeId, asNodes(nodes)) + const building = id ? nodes[id] : undefined + if ( + building?.type !== 'building' || + ![...building.position, ...building.rotation].every(Number.isFinite) + ) + return null + if (Math.abs(building.rotation[0]) > 1e-8 || Math.abs(building.rotation[2]) > 1e-8) return null + const site = ramp.parentId ? nodes[ramp.parentId] : undefined + if (site?.type !== 'site') return null + return building.parentId === ramp.parentId || + (site?.type === 'site' && site.children.includes(building.id)) + ? building + : null +} + +function toSite(building: BuildingNode, [x, z]: RampPoint): RampPoint { + const cos = Math.cos(building.rotation[1]), + sin = Math.sin(building.rotation[1]) + return [cos * x + sin * z + building.position[0], -sin * x + cos * z + building.position[2]] +} + +function toBuilding(building: BuildingNode, [x, z]: RampPoint): RampPoint { + const cos = Math.cos(building.rotation[1]), + sin = Math.sin(building.rotation[1]) + const dx = x - building.position[0], + dz = z - building.position[2] + return [cos * dx - sin * dz, sin * dx + cos * dz] +} + +function measureDoor( + ramp: RampNode, + target: DoorNode, + endpoint: RampStation, + { building, baseY }: TargetFrame, + nodes: SceneNodes, +): Partial { + const wall = target.parentId ? nodes[target.parentId] : undefined + if (wall?.type !== 'wall') return {} + const length = getWallCurveLength(wall) + if (!Number.isFinite(length) || length <= 1e-8) return {} + const frame = getWallCurveFrameAt(wall, target.position[0] / length) + const offset = getWallBodyCenterOffset(wall) + target.position[2] + const point = toSite(building, [ + frame.point.x + frame.normal.x * offset, + frame.point.y + frame.normal.y * offset, + ]) + const heightM = + building.position[1] + + baseY + + getOpeningFloorDatum(wall, target, nodes) + + target.position[1] - + target.height / 2 + const [cos, sin] = [Math.cos(building.rotation[1]), Math.sin(building.rotation[1])] + const tx = cos * frame.tangent.x + sin * frame.tangent.y + const tz = -sin * frame.tangent.x + cos * frame.tangent.y + const nx = cos * frame.normal.x + sin * frame.normal.y + const nz = -sin * frame.normal.x + cos * frame.normal.y + const dx = endpoint.point[0] - point[0], + dz = endpoint.point[1] - point[1] + const planeErrorM = Math.abs(dx * nx + dz * nz) + const planeToleranceM = getWallThickness(wall) / 2 + HEIGHT_TOLERANCE + const lateralErrorM = Math.abs(dx * tx + dz * tz) + const lateralToleranceM = + target.width / 2 + + (ramp.width / 2) * Math.abs(-endpoint.tangent[1] * tx + endpoint.tangent[0] * tz) + const heightErrorM = endpoint.height - heightM + return { + point, + heightM, + horizontalErrorM: Math.hypot(dx, dz), + heightErrorM, + planeErrorM, + planeToleranceM, + lateralErrorM, + lateralToleranceM, + matched: + planeErrorM <= planeToleranceM + 1e-8 && + lateralErrorM <= lateralToleranceM + 1e-8 && + Math.abs(heightErrorM) <= HEIGHT_TOLERANCE + 1e-8, + } +} + +function measureLevel( + endpoint: RampStation, + { building, baseY, levelId }: TargetFrame, + nodes: SceneNodes, +): Partial { + const local = toBuilding(building, endpoint.point) + const tops = Object.values(nodes).flatMap((node) => + node.type === 'slab' && + node.parentId === levelId && + !node.recessed && + pointInPolygon(local, node.polygon) && + !node.holes.some((hole) => pointInPolygon(local, hole)) + ? [building.position[1] + baseY + slabTerrainHeightAt(node, nodes, local[0], local[1])] + : [], + ) + const heightM = tops.length ? Math.max(...tops) : levelFloorWorldY(asNodes(nodes), levelId) + const heightErrorM = heightM === null ? null : endpoint.height - heightM + return { + heightM, + heightErrorM, + point: tops.length ? endpoint.point : null, + horizontalErrorM: tops.length ? 0 : null, + matched: + tops.length > 0 && heightErrorM !== null && Math.abs(heightErrorM) <= HEIGHT_TOLERANCE + 1e-8, + } +} + +function targetMatch( + ramp: RampNode, + targetId: string, + endpoint: RampStation, + nodes: SceneNodes, +): RampTargetMatch { + const target = nodes[targetId] + const kind = target?.type === 'door' || target?.type === 'level' ? target.type : 'unknown' + const levelId = findLevelAncestorId(targetId as AnyNodeId, asNodes(nodes)) + const result: RampTargetMatch = { + targetId, + kind, + matched: false, + horizontalErrorM: null, + heightErrorM: null, + planeErrorM: null, + planeToleranceM: null, + lateralErrorM: null, + lateralToleranceM: null, + point: null, + heightM: null, + levelId, + } + if (!levelId || kind === 'unknown') return result + const building = targetBuilding(ramp, levelId, nodes) + const baseY = getLevelElevations(asNodes(nodes)).get(levelId)?.baseY + if (!building || baseY === undefined || !Number.isFinite(baseY)) return result + const frame = { building, baseY, levelId } + const measured = { + ...result, + ...(target?.type === 'door' + ? measureDoor(ramp, target, endpoint, frame, nodes) + : measureLevel(endpoint, frame, nodes)), + } + const finite = [ + ...(measured.point ?? []), + ...Object.values(measured).filter((value) => typeof value === 'number'), + ].every(Number.isFinite) + return finite ? measured : result +} + +function transitionFacts( + ramp: RampNode, + startDistanceM: number, + endDistanceM: number, + startGradePercent: number, + endGradePercent: number, +): RampTransitionFacts { + return { + lengthM: endDistanceM - startDistanceM, + startDistanceM, + endDistanceM, + startHeightM: rampHeightAt(ramp, startDistanceM), + endHeightM: rampHeightAt(ramp, endDistanceM), + startGradePercent, + endGradePercent, + } +} + +/** Measured design facts, not accessibility, traffic or structural certification. */ +export function rampFacts(ramp: RampNode, nodes: SceneNodes): RampFacts { + const lengthM = rampLength(ramp) + const stations = rampStations(ramp, Math.max(0.5, lengthM / 1000)) + const start = stations[0] + const end = stations.at(-1) + if (!start || !end) refuse('ramp_degenerate', 'A ramp needs measurable endpoints.') + const targets = { + start: ramp.startTargetId ? targetMatch(ramp, ramp.startTargetId, start, nodes) : null, + end: ramp.endTargetId ? targetMatch(ramp, ramp.endTargetId, end, nodes) : null, + } + const maximumSlopePercent = rampMaximumSlopePercent(ramp) + const centrelineMaximumSlopePercent = rampCentrelineMaximumSlopePercent(ramp) + const signedGrade = Math.sign(ramp.endHeight - ramp.startHeight) * centrelineMaximumSlopePercent + const warnings: RampWarning[] = [] + if (maximumSlopePercent > ramp.maxSlopePercent + 1e-8) + warnings.push({ + code: 'ramp_slope_exceeded', + message: `Ramp maximum grade is ${maximumSlopePercent.toFixed(3)}%, above the stated ${ramp.maxSlopePercent}% target.`, + }) + for (const endpoint of ['start', 'end'] as const) { + const target = targets[endpoint] + if (target && !target.matched) + warnings.push({ + code: 'ramp_target_mismatch', + endpoint, + targetId: target.targetId, + message: `Ramp ${endpoint} does not reach ${target.targetId}: plan gap ${target.horizontalErrorM === null ? 'unmeasured' : `${target.horizontalErrorM.toFixed(3)} m`}, height difference ${target.heightErrorM === null ? 'unmeasured' : `${target.heightErrorM.toFixed(3)} m`}.`, + }) + } + return { + lengthM, + riseM: ramp.endHeight - ramp.startHeight, + averageSlopePercent: (Math.abs(ramp.endHeight - ramp.startHeight) / lengthM) * 100, + maximumSlopePercent, + centrelineMaximumSlopePercent, + maxSlopePercent: ramp.maxSlopePercent, + heightToleranceM: HEIGHT_TOLERANCE, + startTransitionM: ramp.startTransition, + endTransitionM: ramp.endTransition, + plateauLengthM: Math.max(0, lengthM - ramp.startTransition - ramp.endTransition), + transitions: { + start: transitionFacts( + ramp, + 0, + ramp.startTransition, + ramp.startTransition > 0 ? 0 : signedGrade, + signedGrade, + ), + end: transitionFacts( + ramp, + lengthM - ramp.endTransition, + lengthM, + signedGrade, + ramp.endTransition > 0 ? 0 : signedGrade, + ), + }, + endpoints: { + start: { point: ramp.start, heightM: ramp.startHeight }, + end: { point: end.point, heightM: ramp.endHeight }, + }, + targets, + warnings, + retaining: { + kind: 'retaining_wall', + heightM: ramp.retainingHeight, + thicknessM: 0.2, + sides: ramp.retainingHeight > 0 ? ['left', 'right'] : [], + }, + } +} diff --git a/packages/core/src/lib/ramp-terrain.ts b/packages/core/src/lib/ramp-terrain.ts new file mode 100644 index 0000000000..c10f15ff8b --- /dev/null +++ b/packages/core/src/lib/ramp-terrain.ts @@ -0,0 +1,338 @@ +import { applySceneChanges, mergeSceneChanges } from '../agent-operations/apply-changes' +import type { SceneChanges, SceneNodes } from '../agent-operations/types' +import { refuse } from '../agent-tools/refusal' +import type { RampNode, SiteNode } from '../schema' +import { polygonsOverlap } from './polygon-relations' +import { + rampBounds, + rampHeightAt, + rampLength, + rampOffsetPoint, + rampProjectPoint, + rampStations, +} from './ramp' +import { + applyHeightPatch, + createTerrainField, + heightAt, + quantize, + sampleRangeOver, + storedHeightAt, + type TerrainField, +} from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' +import { planTerrainTileChanges } from './terrain-tile-changes' +import { terrainEditField } from './terrain-tile-write' + +const GROUND_FIELDS = [ + 'parentId', + 'start', + 'segments', + 'width', + 'startHeight', + 'endHeight', + 'thickness', + 'startTransition', + 'endTransition', + 'terrainMode', + 'retainingHeight', +] as const satisfies readonly (keyof RampNode)[] + +export function rampGroundInputsChanged(before: RampNode, after: RampNode): boolean { + return GROUND_FIELDS.some((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key])) +} + +function siteOf(ramp: RampNode, nodes: SceneNodes): SiteNode { + const site = ramp.parentId ? nodes[ramp.parentId] : undefined + if (site?.type !== 'site') refuse('no_site', 'A ramp must be owned by a Site.') + return site +} + +function corridor(ramp: RampNode) { + const stations = rampStations(ramp, Math.max(0.5, rampLength(ramp) / 500)) + const half = ramp.width / 2 + (ramp.retainingHeight > 0 ? 0.2 : 0) + return [ + ...stations.map((station) => rampOffsetPoint(station, half)), + ...[...stations].reverse().map((station) => rampOffsetPoint(station, -half)), + ] +} + +function requireSeparated(ramp: RampNode, nodes: SceneNodes): void { + const otherRamps = Object.values(nodes).filter( + (node): node is RampNode => + node.type === 'ramp' && node.id !== ramp.id && node.parentId === ramp.parentId, + ) + if (otherRamps.length > 128) + refuse( + 'ramp_sampling_limit', + 'At most 128 existing ramp corridors can be compared in one edit.', + ) + const bounds = rampBounds(ramp, true) + let outline: ReturnType | undefined + let visits = 0 + for (const other of otherRamps) { + const box = rampBounds(other, true) + if ( + bounds.maxX < box.minX || + bounds.minX > box.maxX || + bounds.maxZ < box.minZ || + bounds.minZ > box.maxZ + ) + continue + outline ??= corridor(ramp) + const otherOutline = corridor(other) + visits += outline.length * otherOutline.length + if (visits > 2_000_000) + refuse('ramp_sampling_limit', 'Comparing ramp corridors exceeds two million edge pairs.') + if (polygonsOverlap(outline, otherOutline)) + refuse('ramp_self_intersection', 'The proposed ramp corridor intersects an existing ramp.', { + rampId: other.id, + }) + } +} + +function fieldOf(site: SiteNode, nodes: SceneNodes, ramp: RampNode): TerrainField { + const bounds = rampBounds(ramp) + const count = + (Math.ceil((bounds.maxX - bounds.minX) / 0.5) + 4) * + (Math.ceil((bounds.maxZ - bounds.minZ) / 0.5) + 4) + if (!Number.isFinite(count) || count * ramp.segments.length > 2_000_000) + refuse('ramp_sampling_limit', 'Ramp grading exceeds two million segment projections.') + const field = terrainEditField(site, nodes, { + minX: bounds.minX - 0.5, + minZ: bounds.minZ - 0.5, + maxX: bounds.maxX + 0.5, + maxZ: bounds.maxZ + 0.5, + }) + if ( + !field || + ![ + ...field.origin, + field.spacing, + field.step, + field.origin[0] + (field.cols - 1) * field.spacing, + field.origin[1] + (field.rows - 1) * field.spacing, + ].every(Number.isFinite) || + field.spacing <= 0 || + field.step <= 0 || + !field.heights.every((height) => Number.isFinite(height * field.step)) + ) + refuse('no_terrain', 'The Site terrain cannot be read as finite heights.') + return field +} + +function patchUnder(ramp: RampNode, field: TerrainField) { + const bounds = rampBounds(ramp) + const maxX = field.origin[0] + (field.cols - 1) * field.spacing + const maxZ = field.origin[1] + (field.rows - 1) * field.spacing + if ( + bounds.minX < field.origin[0] - 1e-8 || + bounds.minZ < field.origin[1] - 1e-8 || + bounds.maxX > maxX + 1e-8 || + bounds.maxZ > maxZ + 1e-8 + ) + refuse('outside_terrain', 'The ramp corridor extends outside the Site terrain field.') + const range = sampleRangeOver(field, bounds.minX, bounds.minZ, bounds.maxX, bounds.maxZ) + if (!range) refuse('outside_terrain', 'The ramp corridor misses the Site terrain field.') + const cols = range.col1 - range.col0 + 1, + rows = range.row1 - range.row0 + 1 + if (cols * rows * ramp.segments.length > 2_000_000) + refuse( + 'ramp_sampling_limit', + 'Ramp terrain grading exceeds two million segment projections; simplify the alignment.', + ) + const heights = new Int16Array(cols * rows) + const samples: NonNullable['samples'] = [] + let changed = false + for (let row = 0; row < rows; row++) + for (let col = 0; col < cols; col++) { + const source = (range.row0 + row) * field.cols + range.col0 + col + const index = row * cols + col + heights[index] = field.heights[source] ?? 0 + const x = field.origin[0] + (range.col0 + col) * field.spacing + const z = field.origin[1] + (range.row0 + row) * field.spacing + const projected = rampProjectPoint(ramp, [x, z]) + if (!projected.inside) continue + const height = rampHeightAt(ramp, projected.distance) - ramp.thickness + const units = height / field.step + if (!Number.isFinite(units) || units < -32768 || units > 32767) + refuse( + 'ramp_terrain_range', + 'The ramp underside exceeds the terrain height quantization range.', + ) + const value = quantize(field, height) + if (heights[index] !== value) samples.push([source, heights[index] ?? 0, value]) + changed ||= heights[index] !== value + heights[index] = value + } + return { patch: { col0: range.col0, row0: range.row0, cols, rows, heights }, changed, samples } +} + +function gradeTerrain(ramp: RampNode, nodes: SceneNodes) { + rampLength(ramp) + const site = siteOf(ramp, nodes) + requireSeparated(ramp, nodes) + if (ramp.terrainMode === 'none') return { changes: {} as SceneChanges, effect: undefined } + const field = fieldOf(site, nodes, ramp) + const { patch, changed, samples } = patchUnder(ramp, field) + const effect: NonNullable = { + siteId: site.id, + origin: [...field.origin], + spacing: field.spacing, + cols: field.cols, + rows: field.rows, + step: field.step, + samples, + } + const changes = changed + ? planTerrainTileChanges(site, nodes, field, applyHeightPatch(field, patch)) + : {} + return { changes, effect } +} + +/** Terrain-only planning; creation and edit planners also retain the ramp's owned samples. */ +export function planRampTerrain(ramp: RampNode, nodes: SceneNodes): SceneChanges { + const { changes } = gradeTerrain(ramp, nodes) + requireRampChangeBudget(changes, nodes) + return changes +} + +function withEffect(ramp: RampNode, effect: RampNode['terrainEffect']): RampNode { + const owned = { ...ramp } + if (effect) owned.terrainEffect = effect + else delete owned.terrainEffect + return owned +} + +/** Reconstruct a receipt's grid without rebasing or rewriting the frozen legacy field. */ +function receiptFields( + effect: NonNullable, + site: SiteNode, + nodes: SceneNodes, +) { + if (effect.cols * effect.rows > 2_000_000) + refuse('ramp_sampling_limit', 'The ramp receipt exceeds two million terrain samples.') + const authority = persistedTerrainFieldOf(site, nodes) + const field = createTerrainField(effect) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = authority + ? quantize( + field, + storedHeightAt( + authority, + field.origin[0] + col * field.spacing, + field.origin[1] + row * field.spacing, + ), + ) + : 0 + const before = { ...field, heights: field.heights.slice() } + const after = { ...field, heights: field.heights.slice() } + for (const [index, previous, applied] of effect.samples) { + if (index >= field.heights.length) + refuse( + 'ramp_terrain_grid_changed', + 'A ramp terrain receipt contains an invalid sample index.', + ) + before.heights[index] = previous + after.heights[index] = applied + } + return { before, after } +} + +/** Restore only ground still equal to the receipt, including receipts tied to a legacy grid. */ +export function planRampGroundRelease(ramp: RampNode, nodes: SceneNodes): SceneChanges { + const effect = ramp.terrainEffect + if (!effect?.samples.length) return {} + const site = nodes[effect.siteId] + if (site?.type !== 'site') return {} + const receipt = receiptFields(effect, site, nodes) + const field = terrainEditField(site, nodes, { + minX: effect.origin[0], + minZ: effect.origin[1], + maxX: effect.origin[0] + (effect.cols - 1) * effect.spacing, + maxZ: effect.origin[1] + (effect.rows - 1) * effect.spacing, + }) + const heights = new Int16Array(field.heights) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) { + const index = row * field.cols + col + const x = field.origin[0] + col * field.spacing + const z = field.origin[1] + row * field.spacing + const previous = quantize(field, heightAt(receipt.before, x, z)) + const applied = quantize(field, heightAt(receipt.after, x, z)) + if (previous !== applied && heights[index] === applied) heights[index] = previous + } + const changes = planTerrainTileChanges(site, nodes, field, { ...field, heights }) + requireRampChangeBudget(changes, nodes) + return changes +} + +export function planRampCreation(ramp: RampNode, nodes: SceneNodes): SceneChanges { + const { changes: terrain, effect } = gradeTerrain(ramp, nodes) + const changes: SceneChanges = { + ...terrain, + create: [ + ...(terrain.create ?? []), + { node: withEffect(ramp, effect), parentId: ramp.parentId ?? undefined }, + ], + } + requireRampChangeBudget(changes, nodes) + return changes +} + +/** All surfaces apply the profile, released ground and new cut/fill in the same undo step. */ +export function planRampEdit(ramp: RampNode, nodes: SceneNodes): SceneChanges { + const previous = nodes[ramp.id] + if (previous?.type !== 'ramp') refuse('ramp_not_found', 'The ramp to edit is not in the scene.') + rampLength(ramp) + if (!rampGroundInputsChanged(previous, ramp)) { + const next = withEffect(ramp, previous.terrainEffect) + const data = Object.fromEntries( + [...new Set([...Object.keys(previous), ...Object.keys(next)])] + .filter( + (key) => + JSON.stringify(previous[key as keyof RampNode]) !== + JSON.stringify(next[key as keyof RampNode]), + ) + .map((key) => [key, next[key as keyof RampNode]]), + ) + const changes = Object.keys(data).length ? { update: [{ id: ramp.id, data }] } : {} + requireRampChangeBudget(changes, nodes) + return changes + } + const released = planRampGroundRelease(previous, nodes) + const { changes: terrain, effect } = gradeTerrain(ramp, applySceneChanges(nodes, released)) + const changes = mergeSceneChanges([ + released, + terrain, + { update: [{ id: ramp.id, data: { ...withEffect(ramp, effect), terrainEffect: effect } }] }, + ]) + requireRampChangeBudget(changes, nodes) + return changes +} + +/** Each node must fit; the shared authority splits a multi-node edit into operations. */ +export function requireRampChangeBudget(changes: SceneChanges, nodes: SceneNodes): void { + const updates = changes.update?.map(({ id, data }) => ({ + id, + data, + from: Object.fromEntries( + Object.keys(data).map((key) => [ + key, + (nodes[id] as unknown as Record | undefined)?.[key] ?? null, + ]), + ), + })) + const deletes = changes.delete?.map((id) => ({ id, from: nodes[id] })) + const limitBytes = 62 * 1024 + for (const mutation of [...(updates ?? []), ...(changes.create ?? []), ...(deletes ?? [])]) { + const bytes = new TextEncoder().encode(JSON.stringify(mutation)).byteLength + if (bytes > limitBytes) + refuse( + 'terrain_write_too_large', + 'A ramp or terrain node exceeds the shared scene operation size; nothing was written.', + { bytes, limitBytes }, + ) + } +} diff --git a/packages/core/src/lib/ramp.ts b/packages/core/src/lib/ramp.ts new file mode 100644 index 0000000000..f9b945cf71 --- /dev/null +++ b/packages/core/src/lib/ramp.ts @@ -0,0 +1,412 @@ +import { refuse } from '../agent-tools/refusal' +import { RampNode } from '../schema/nodes/ramp' +import { segmentsIntersect } from './polygon-relations' + +export type RampPoint = [number, number] +export type RampStation = { + point: RampPoint + tangent: RampPoint + distance: number + height: number +} +type Piece = { + start: RampPoint + end: RampPoint + at: number + length: number + center?: RampPoint + angle: number + sweep: number + radius: number +} +type Path = { pieces: Piece[]; length: number; grade: number } +const MAX_STATIONS = 2048 +const EPS = 1e-8 +const TANGENT_TOLERANCE_RADIANS = 1e-6 +const paths = new WeakMap() +const gap = (a: RampPoint, b: RampPoint) => Math.hypot(a[0] - b[0], a[1] - b[1]) + +function pieceOf(start: RampPoint, segment: RampNode['segments'][number], at: number): Piece { + if (segment.type === 'line') { + const length = gap(start, segment.end) + if (length <= EPS) refuse('ramp_degenerate', 'A ramp line needs distinct endpoints.') + return { + start, + end: segment.end, + at, + length, + angle: Math.atan2(segment.end[1] - start[1], segment.end[0] - start[0]), + sweep: 0, + radius: 0, + } + } + const radius = gap(start, segment.center) + if (radius <= EPS || Math.abs(segment.sweep) <= EPS) + refuse('ramp_degenerate', 'A ramp arc needs a nonzero radius and sweep.') + if (Math.abs(segment.sweep) >= Math.PI * 2 - EPS) + refuse( + 'ramp_self_intersection', + 'A full-circle ramp stacks its corridor; use a nonintersecting path.', + ) + const angle = Math.atan2(start[1] - segment.center[1], start[0] - segment.center[0]) + const end: RampPoint = [ + segment.center[0] + radius * Math.cos(angle + segment.sweep), + segment.center[1] + radius * Math.sin(angle + segment.sweep), + ] + return { + start, + end, + at, + center: segment.center, + angle, + sweep: segment.sweep, + radius, + length: radius * Math.abs(segment.sweep), + } +} + +function pathOf(ramp: RampNode): Path { + const cached = paths.get(ramp) + if (cached) return cached + const parsed = RampNode.safeParse(ramp) + if (!parsed.success) refuse('invalid_input', parsed.error.message) + let start = ramp.start + let length = 0 + const pieces = ramp.segments.map((segment) => { + const piece = pieceOf(start, segment, length) + const halfEnvelope = ramp.width / 2 + (ramp.retainingHeight > 0 ? 0.2 : 0) + if (piece.center && piece.radius <= halfEnvelope) + refuse( + 'ramp_inner_radius', + 'The arc inner radius must clear half the ramp width and any retaining side.', + ) + start = piece.end + length += piece.length + return piece + }) + const transition = ramp.startTransition + ramp.endTransition + if (transition > length) + refuse( + 'ramp_transition_overlap', + 'Ramp transitions cannot overlap; shorten them or lengthen the path.', + ) + const grade = (ramp.endHeight - ramp.startHeight) / (length - transition / 2) + if (![length, grade * 100, ramp.endHeight - ramp.startHeight, ...start].every(Number.isFinite)) + refuse('ramp_non_finite', 'The ramp length, endpoint and grade must be finite.') + const path = { pieces, length, grade } + requireSimpleCorridor(ramp, path) + requireTangentJoints(path) + paths.set(ramp, path) + return path +} + +function frameAt(piece: Piece, distance: number): { point: RampPoint; tangent: RampPoint } { + const t = Math.max(0, Math.min(1, (distance - piece.at) / piece.length)) + if (!piece.center) + return { + point: + t === 0 + ? piece.start + : t === 1 + ? piece.end + : [ + piece.start[0] * (1 - t) + piece.end[0] * t, + piece.start[1] * (1 - t) + piece.end[1] * t, + ], + tangent: [Math.cos(piece.angle), Math.sin(piece.angle)], + } + const angle = piece.angle + piece.sweep * t + const sign = Math.sign(piece.sweep) + return { + point: + t === 0 + ? piece.start + : t === 1 + ? piece.end + : [ + piece.center[0] + piece.radius * Math.cos(angle), + piece.center[1] + piece.radius * Math.sin(angle), + ], + tangent: [-Math.sin(angle) * sign, Math.cos(angle) * sign], + } +} + +function requireTangentJoints(path: Path): void { + for (let index = 1; index < path.pieces.length; index++) { + const previous = path.pieces[index - 1] + const next = path.pieces[index] + if (!previous || !next) continue + const incoming = frameAt(previous, previous.at + previous.length).tangent + const outgoing = frameAt(next, next.at).tangent + const angle = Math.abs( + Math.atan2( + incoming[0] * outgoing[1] - incoming[1] * outgoing[0], + incoming[0] * outgoing[0] + incoming[1] * outgoing[1], + ), + ) + if (angle > TANGENT_TOLERANCE_RADIANS) + refuse('ramp_joint_not_tangent', 'Ramp segments must meet with a tangent transition.', { + jointIndex: index, + angleDegrees: (angle * 180) / Math.PI, + toleranceRadians: TANGENT_TOLERANCE_RADIANS, + incoming, + outgoing, + }) + } +} + +function heightOn(ramp: RampNode, path: Path, distance: number): number { + const d = Math.max(0, Math.min(path.length, distance)) + const startTransition = ramp.startTransition, + endTransition = ramp.endTransition + const effective = path.length - (startTransition + endTransition) / 2 + if (d === path.length) return ramp.endHeight + let weight = (d - startTransition / 2) / effective + if (startTransition > 0 && d < startTransition) + weight = (d * (d / startTransition)) / 2 / effective + if (endTransition > 0 && d > path.length - endTransition) { + const remaining = path.length - d + weight = 1 - (remaining * (remaining / endTransition)) / 2 / effective + } + return ramp.startHeight * (1 - weight) + ramp.endHeight * weight +} + +function distances(path: Path, step: number): number[] { + const counts = path.pieces.map((piece) => + Math.max(1, Math.ceil(piece.length / step), Math.ceil(Math.abs(piece.sweep) / (Math.PI / 36))), + ) + if (counts.reduce((sum, count) => sum + count, 1) > MAX_STATIONS) + refuse( + 'ramp_sampling_limit', + `A ramp is limited to ${MAX_STATIONS} stations; simplify it or increase the station step.`, + ) + return [ + 0, + ...path.pieces.flatMap((piece, index) => { + const count = counts[index] ?? 1 + return Array.from({ length: count }, (_, i) => piece.at + (piece.length * (i + 1)) / count) + }), + ] +} + +function stationsOn(ramp: RampNode, path: Path, step: number): RampStation[] { + const candidates = [ + ...distances(path, step), + ramp.startTransition, + path.length - ramp.endTransition, + ].sort((a, b) => a - b) + const ds: number[] = [] + for (const distance of candidates) { + const previous = ds.at(-1) + if (previous === undefined || distance - previous > EPS) ds.push(distance) + else if (distance === path.length) ds[ds.length - 1] = distance + } + if (ds.length > MAX_STATIONS) + refuse('ramp_sampling_limit', 'Ramp transitions exceed the station budget.') + return ds.map((distance) => { + const piece = + path.pieces.find((candidate) => distance <= candidate.at + candidate.length + EPS) ?? + path.pieces.at(-1) + if (!piece) refuse('ramp_degenerate', 'A ramp needs at least one usable segment.') + const frame = frameAt(piece, distance) + const next = path.pieces[path.pieces.indexOf(piece) + 1] + if (next && Math.abs(distance - next.at) <= EPS) { + const outgoing = frameAt(next, distance).tangent + const x = frame.tangent[0] + outgoing[0], + z = frame.tangent[1] + outgoing[1] + const norm = Math.hypot(x, z) + if (norm <= EPS) + refuse('ramp_self_intersection', 'A ramp cannot reverse direction at a joint.') + frame.tangent = [x / norm, z / norm] + } + return { ...frame, distance, height: heightOn(ramp, path, distance) } + }) +} + +export function rampOffsetPoint(station: RampStation, offset: number): RampPoint { + return [ + station.point[0] - station.tangent[1] * offset, + station.point[1] + station.tangent[0] * offset, + ] +} + +function requireSimpleCorridor(ramp: RampNode, path: Path): void { + const stations = stationsOn(ramp, path, Math.max(0.5, path.length / 1000)) + const half = ramp.width / 2 + (ramp.retainingHeight > 0 ? 0.2 : 0) + const ring = [ + ...stations.map((station) => rampOffsetPoint(station, half)), + ...[...stations].reverse().map((station) => rampOffsetPoint(station, -half)), + ] + if (ring.some((point) => !point.every(Number.isFinite))) + refuse('ramp_non_finite', 'Ramp corridor coordinates must be finite.') + for (let i = 0; i < ring.length; i++) { + const a = ring[i], + b = ring[(i + 1) % ring.length] + if (!a || !b) continue + for (let j = i + 2; j < ring.length; j++) { + if (i === 0 && j === ring.length - 1) continue + const c = ring[j], + d = ring[(j + 1) % ring.length] + if (!c || !d) continue + if ( + Math.max(a[0], b[0]) < Math.min(c[0], d[0]) || + Math.max(c[0], d[0]) < Math.min(a[0], b[0]) || + Math.max(a[1], b[1]) < Math.min(c[1], d[1]) || + Math.max(c[1], d[1]) < Math.min(a[1], b[1]) + ) + continue + if (segmentsIntersect(a, b, c, d)) + refuse('ramp_self_intersection', 'Ramp corridors cannot intersect or stack in plan.') + } + } +} + +/** Exact centreline plan length; arc lengths do not depend on rendering resolution. */ +export function rampLength(ramp: RampNode): number { + return pathOf(ramp).length +} + +/** Practical creation defaults, not a persisted geometric constraint. */ +export function rampDefaultTransitionLength(ramp: RampNode): number { + return Math.min(1.5, rampLength(ramp) / 4) +} + +/** Linear-grade transitions integrate to the authored endpoint height exactly. */ +export function rampHeightAt(ramp: RampNode, distance: number): number { + if (!Number.isFinite(distance)) refuse('ramp_non_finite', 'Ramp station distance must be finite.') + return heightOn(ramp, pathOf(ramp), distance) +} + +/** + * The station step at which a plan chord of the corridor's edge stays within `sagM` of the true + * curve: the default step on a gentle arc, finer on a tight one. The outer edge runs on the + * larger circle, so its chord is the longest for the same centreline step. + */ +export function rampStepForSag(ramp: RampNode, sagM: number): number { + const path = pathOf(ramp) + let step = Math.max(0.5, path.length / 1000) + for (const piece of path.pieces) { + if (!piece.center) continue + const outer = piece.radius + ramp.width / 2 + step = Math.min(step, piece.radius * Math.sqrt((8 * sagM) / outer)) + } + return Math.max(step, path.length / 1500) +} + +export function rampStations(ramp: RampNode, stepM?: number): RampStation[] { + const path = pathOf(ramp) + const step = stepM ?? Math.max(0.5, path.length / 1000) + if (!Number.isFinite(step) || step <= 0) + refuse('invalid_input', 'Ramp station step must be positive and finite.') + return stationsOn(ramp, path, step) +} + +export function rampMaximumSlopePercent(ramp: RampNode): number { + const path = pathOf(ramp) + const centreline = Math.abs(path.grade) * 100 + const at = (distance: number) => + Math.min( + ramp.startTransition > 0 ? distance / ramp.startTransition : 1, + ramp.endTransition > 0 ? (path.length - distance) / ramp.endTransition : 1, + 1, + ) + const maximum = Math.max( + ...path.pieces.map((piece) => { + const from = piece.at, + to = from + piece.length + const local = Math.max( + at(from), + at(to), + at(Math.max(from, Math.min(to, ramp.startTransition))), + ) + return ( + centreline * local * (piece.center ? piece.radius / (piece.radius - ramp.width / 2) : 1) + ) + }), + ) + if (!Number.isFinite(maximum)) refuse('ramp_non_finite', 'Ramp edge grades must be finite.') + return maximum +} + +export function rampCentrelineMaximumSlopePercent(ramp: RampNode): number { + return Math.abs(pathOf(ramp).grade) * 100 +} + +/** Flat-capped corridor bounds include exact circular extrema, not just tessellation vertices. */ +export function rampBounds(ramp: RampNode, includeRetaining = false) { + const path = pathOf(ramp) + const half = ramp.width / 2 + (includeRetaining && ramp.retainingHeight > 0 ? 0.2 : 0) + const points = path.pieces.flatMap((piece) => { + const ends = [frameAt(piece, piece.at), frameAt(piece, piece.at + piece.length)] + const points = ends.flatMap((end) => [ + rampOffsetPoint({ ...end, distance: 0, height: 0 }, half), + rampOffsetPoint({ ...end, distance: 0, height: 0 }, -half), + ]) + if (piece.center) + for (const angle of [0, Math.PI / 2, Math.PI, Math.PI * 1.5]) { + const sweep = + (((Math.sign(piece.sweep) * (angle - piece.angle)) % (Math.PI * 2)) + Math.PI * 2) % + (Math.PI * 2) + if (sweep <= Math.abs(piece.sweep)) + for (const radius of [piece.radius - half, piece.radius + half]) + points.push([ + piece.center[0] + radius * Math.cos(angle), + piece.center[1] + radius * Math.sin(angle), + ]) + } + return points + }) + for (const station of stationsOn(ramp, path, path.length)) { + points.push(rampOffsetPoint(station, half), rampOffsetPoint(station, -half)) + } + const bounds = { + minX: Math.min(...points.map(([x]) => x)), + maxX: Math.max(...points.map(([x]) => x)), + minZ: Math.min(...points.map(([, z]) => z)), + maxZ: Math.max(...points.map(([, z]) => z)), + } + if (!Object.values(bounds).every(Number.isFinite)) + refuse('ramp_non_finite', 'Ramp corridor bounds must be finite.') + return bounds +} + +/** Analytic nearest centreline station, with flat end caps for terrain grading. */ +export function rampProjectPoint( + ramp: RampNode, + point: RampPoint, +): { distance: number; lateral: number; inside: boolean } { + if (!point.every(Number.isFinite)) + refuse('ramp_non_finite', 'A ramp projection point must be finite.') + const path = pathOf(ramp) + let best = { distance: 0, lateral: Infinity, inside: false } + for (const piece of path.pieces) { + let t: number + if (piece.center) { + const angle = Math.atan2(point[1] - piece.center[1], point[0] - piece.center[0]) + const directed = + (((Math.sign(piece.sweep) * (angle - piece.angle)) % (Math.PI * 2)) + Math.PI * 2) % + (Math.PI * 2) + t = directed / Math.abs(piece.sweep) + if (t > 1) t = gap(point, piece.start) < gap(point, piece.end) ? 0 : 1 + } else { + const dx = piece.end[0] - piece.start[0], + dz = piece.end[1] - piece.start[1] + t = + ((point[0] - piece.start[0]) / piece.length) * (dx / piece.length) + + ((point[1] - piece.start[1]) / piece.length) * (dz / piece.length) + } + const distance = piece.at + Math.max(0, Math.min(1, t)) * piece.length + const frame = frameAt(piece, distance) + const dx = point[0] - frame.point[0], + dz = point[1] - frame.point[1] + const lateral = Math.hypot(dx, dz) + const along = dx * frame.tangent[0] + dz * frame.tangent[1] + const capped = + (distance <= EPS && along < -EPS) || (distance >= path.length - EPS && along > EPS) + if (lateral < best.lateral) + best = { distance, lateral, inside: !capped && lateral <= ramp.width / 2 + EPS } + } + if (!Number.isFinite(best.lateral)) + refuse('ramp_non_finite', 'The point cannot be projected onto a finite ramp station.') + return best +} diff --git a/packages/core/src/lib/slab-terrain.test.ts b/packages/core/src/lib/slab-terrain.test.ts new file mode 100644 index 0000000000..9136292a98 --- /dev/null +++ b/packages/core/src/lib/slab-terrain.test.ts @@ -0,0 +1,273 @@ +import { describe, expect, test } from 'bun:test' +import { + createSceneSpatialGrid, + createTerrainField, + encodeTerrainField, + liftedManualSlab, + slabTerrainHeightAt, + useLiveTerrain, +} from '@pascal-app/core' +import { type AnyNode, BuildingNode, LevelNode, SiteNode, SlabNode } from '@pascal-app/core/schema' + +function scene(transformed = false, offset = 0) { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + for (let z = 0; z < 9; z++) { + for (let x = 0; x < 9; x++) field.heights[z * 9 + x] = 50 * x + 25 * z + 100 * offset + } + const site = SiteNode.parse({ + id: 'site_drape', + children: ['building_drape'], + terrain: encodeTerrainField(field), + polygon: { + type: 'polygon', + points: [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ], + }, + }) + const building = BuildingNode.parse({ + id: 'building_drape', + parentId: site.id, + children: ['level_drape'], + position: transformed ? [3, 2, 4] : [0, 0, 0], + rotation: transformed ? [0, Math.PI / 2, 0] : [0, 0, 0], + }) + const level = LevelNode.parse({ + id: 'level_drape', + parentId: building.id, + level: 0, + height: 3, + baseElevation: transformed ? 1 : 0, + children: ['slab_drape'], + }) + const slab = SlabNode.parse({ + id: 'slab_drape', + parentId: level.id, + polygon: [ + [1, 1], + [3, 1], + [3, 3], + [1, 3], + ], + elevation: 0.1, + thickness: 0.05, + terrainMode: 'draped', + autoFromWalls: false, + metadata: { flatwork: 'walk' }, + }) + return { + slab, + nodes: Object.fromEntries( + [site, building, level, slab].map((node) => [node.id, node]), + ) as Record, + } +} + +// Analytical plane y=.5x+.25z: the slab samples terrain in Site coordinates, +// then expresses the top in its own level frame with the authored clearance. +describe('draped slab support height', () => { + for (const courtyard of [false, true]) { + test(`a raised base does not add foundation lift to draped clearance (courtyard=${courtyard})`, () => { + const { nodes, slab } = scene() + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + const site = SiteNode.parse({ ...nodes.site_drape, terrain: encodeTerrainField(field) }) + const base = SlabNode.parse({ + id: 'slab_foundation', + parentId: slab.parentId, + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + holes: courtyard + ? [ + [ + [0.5, 0.5], + [3.5, 0.5], + [3.5, 3.5], + [0.5, 3.5], + ], + ] + : [], + plateRole: 'base', + floorHeight: 1.05, + referenceFloorElevation: 0.05, + elevation: 1.05, + }) + const path = SlabNode.parse({ ...slab, elevation: 0.03 }) + const raised = { ...nodes, [site.id]: site, [base.id]: base, [path.id]: path } + const lifted = liftedManualSlab(raised, path) + expect(lifted.elevation).toBeCloseTo(0.03, 8) + expect(slabTerrainHeightAt(lifted, raised, 2, 2)).toBeCloseTo(0.03, 8) + const flat = SlabNode.parse({ ...path, terrainMode: 'flat' }) + expect(liftedManualSlab({ ...raised, [flat.id]: flat }, flat).elevation).toBeCloseTo(1.03, 8) + if (courtyard) { + const support = createSceneSpatialGrid(raised).getSlabSupportForItem( + 'level_drape', + [2, 0, 2], + [0.2, 1, 0.2], + [0, 0, 0], + ) + expect(support.slabId).toBe(path.id) + expect(support.elevation).toBeCloseTo(0.03, 8) + } + }) + } + + test('follows both horizontal terrain axes with the requested clearance', () => { + const { slab, nodes } = scene() + const before = structuredClone(nodes) + for (const [x, z, height] of [ + [1, 1, 0.85], + [2, 1, 1.35], + [2, 3, 1.85], + ] as const) { + expect(slabTerrainHeightAt(slab, nodes, x, z)).toBeCloseTo(height, 8) + } + expect(nodes).toEqual(before) + }) + + test('rotated and translated buildings do not sample terrain in the wrong frame', () => { + const { slab, nodes } = scene(true) + // local(2,1) -> Site(4,2); Site top=2.5+.1, level origin Y=2+1. + expect(slabTerrainHeightAt(slab, nodes, 2, 1)).toBeCloseTo(-0.4, 8) + // local(1,3) -> Site(6,3); Site top=3.75+.1, same level origin. + expect(slabTerrainHeightAt(slab, nodes, 1, 3)).toBeCloseTo(0.85, 8) + }) + + test('replacing Site terrain changes support without changing the authored slab', () => { + const { slab, nodes } = scene() + const saved = structuredClone(slab) + expect(slabTerrainHeightAt(slab, nodes, 2, 1)).toBeCloseTo(1.35, 8) + const raised = scene(false, 1).nodes.site_drape + if (!raised) throw new Error('The raised Site fixture is missing') + expect(slabTerrainHeightAt(slab, { ...nodes, [raised.id]: raised }, 2, 1)).toBeCloseTo(2.35, 8) + expect(slab).toEqual(saved) + }) + + test('legacy and explicitly flat slabs keep the authored top even above shaped ground', () => { + const { slab, nodes } = scene(true) + for (const terrainMode of [undefined, 'flat'] as const) { + const flat = SlabNode.parse({ ...slab, terrainMode, elevation: 0.7 }) + expect(slabTerrainHeightAt(flat, nodes, 2, 1)).toBe(0.7) + expect(slabTerrainHeightAt(flat, nodes, 1, 3)).toBe(0.7) + } + }) + + test('absent terrain is datum ground, not an unknown fabricated slope', () => { + const { slab, nodes } = scene() + const site = SiteNode.parse({ ...nodes.site_drape, terrain: undefined }) + expect(slabTerrainHeightAt(slab, { ...nodes, [site.id]: site }, 2, 1)).toBeCloseTo(0.1, 8) + }) + + test('persisted facts and headless support ignore an uncommitted live terrain stroke', () => { + const { slab, nodes } = scene() + const live = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + live.heights.fill(500) + useLiveTerrain.getState().begin('site_drape', live) + try { + expect(slabTerrainHeightAt(slab, nodes, 2, 2)).toBeCloseTo(1.6, 8) + expect(slabTerrainHeightAt(slab, nodes, 2, 2, 'live')).toBeCloseTo(5.1, 8) + expect(createSceneSpatialGrid(nodes).getSlabElevationAt('level_drape', 2, 2)).toBeCloseTo( + 1.6, + 8, + ) + } finally { + useLiveTerrain.getState().end('site_drape') + } + expect(slabTerrainHeightAt(slab, nodes, 2, 2, 'live')).toBeCloseTo(1.6, 8) + }) + + test('support and downward pointer queries use the sampled top rather than the flat clearance', () => { + const { nodes } = scene() + const grid = createSceneSpatialGrid(nodes) + expect(grid.getSlabElevationAt('level_drape', 2, 2)).toBeCloseTo(1.6, 8) + const support = grid.getSlabSupportForItem('level_drape', [2, 0, 2], [0.2, 1, 0.2], [0, 0, 0]) + expect(support.slabId).toBe('slab_drape') + expect(support.elevation).toBeCloseTo(1.6, 8) + const pointed = grid.getPointedSupportSurface('level_drape', [2, 10, 2], [0, -1, 0]) + expect(pointed.slabId).toBe('slab_drape') + expect(pointed.elevation).toBeCloseTo(1.6, 8) + expect(pointed.point).toEqual([2, 2]) + }) + + test('a draped support below the level origin keeps its negative local height', () => { + const { nodes, slab } = scene(true) + const grid = createSceneSpatialGrid(nodes) + // local(2,1.5) -> Site(4.5,2): terrain 2.75 + .1 clearance - 3 origin. + expect(grid.getSlabElevationAt('level_drape', 2, 1.5)).toBeCloseTo(-0.15, 8) + const support = grid.getSlabSupportForItem('level_drape', [2, 0, 1.5], [0.2, 1, 0.2], [0, 0, 0]) + expect(support.slabId).toBe(slab.id) + expect(support.elevation).toBeCloseTo(-0.15, 8) + const flat = SlabNode.parse({ ...slab, terrainMode: 'flat', elevation: -0.15 }) + expect( + createSceneSpatialGrid({ ...nodes, [slab.id]: flat }).getSlabElevationAt( + 'level_drape', + 2, + 1.5, + ), + ).toBe(0) + }) + + test('offset item footprints sample their common node anchor rather than each part centre', () => { + const { nodes } = scene() + const grid = createSceneSpatialGrid(nodes) + for (const x of [1.75, 2.25]) { + const support = grid.getSlabSupportForItem( + 'level_drape', + [x, 0, 2], + [0.2, 1, 0.2], + [0, 0, 0], + undefined, + [2, 2], + ) + expect(support.slabId).toBe('slab_drape') + expect(support.elevation).toBeCloseTo(1.6, 8) + } + }) + + test('support election observes changed terrain and an explicit return to flat mode', () => { + const { nodes, slab } = scene() + const raised = scene(false, 1).nodes.site_drape + if (!raised) throw new Error('The raised Site fixture is missing') + expect( + createSceneSpatialGrid({ ...nodes, [raised.id]: raised }).getSlabElevationAt( + 'level_drape', + 2, + 2, + ), + ).toBeCloseTo(2.6, 8) + expect( + createSceneSpatialGrid({ + ...nodes, + [slab.id]: { ...slab, terrainMode: 'flat' }, + }).getSlabElevationAt('level_drape', 2, 2), + ).toBeCloseTo(0.1, 8) + }) + + test('a draped slab hole does not become item or pointer support', () => { + const { nodes, slab } = scene() + const perforated = SlabNode.parse({ + ...slab, + holes: [ + [ + [1.5, 1.5], + [2.5, 1.5], + [2.5, 2.5], + [1.5, 2.5], + ], + ], + }) + const grid = createSceneSpatialGrid({ ...nodes, [slab.id]: perforated }) + expect( + grid.getSlabSupportForItem('level_drape', [2, 0, 2], [0.1, 1, 0.1], [0, 0, 0]).slabId, + ).not.toBe(slab.id) + expect(grid.getPointedSupportSurface('level_drape', [2, 10, 2], [0, -1, 0]).slabId).not.toBe( + slab.id, + ) + }) +}) diff --git a/packages/core/src/lib/slab-terrain.ts b/packages/core/src/lib/slab-terrain.ts new file mode 100644 index 0000000000..ac4714c8be --- /dev/null +++ b/packages/core/src/lib/slab-terrain.ts @@ -0,0 +1,59 @@ +import type { AnyNode, AnyNodeId, SlabNode } from '../schema' +import { getLevelElevations } from '../services/storey' +import { surfaceHeightAt, type TerrainField } from './terrain-field' +import { persistedTerrainFieldOf, terrainFieldOf } from './terrain-source' + +export type SlabTerrainFrame = { + field: TerrainField | null + baseY: number + toSite: (x: number, z: number) => [number, number] +} + +export function slabTerrainFrameOf( + slab: SlabNode, + nodes: Readonly>, + source: 'persisted' | 'live' = 'persisted', +): SlabTerrainFrame | null { + if ( + slab.terrainMode !== 'draped' || + slab.plateRole || + slab.boundary === 'auto' || + slab.autoFromWalls || + slab.recessed + ) + return null + const level = slab.parentId ? nodes[slab.parentId] : undefined + const building = level?.parentId ? nodes[level.parentId] : undefined + const site = building?.parentId ? nodes[building.parentId] : undefined + if (level?.type !== 'level' || building?.type !== 'building' || site?.type !== 'site') return null + if (Math.abs(building.rotation[0]) > 1e-9 || Math.abs(building.rotation[2]) > 1e-9) return null + const angle = building.rotation[1] + const cosine = Math.cos(angle) + const sine = Math.sin(angle) + const baseY = + building.position[1] + + (getLevelElevations(nodes as Record).get(level.id)?.baseY ?? 0) + return { + field: source === 'live' ? terrainFieldOf(site, nodes) : persistedTerrainFieldOf(site, nodes), + baseY, + toSite: (x, z) => [ + cosine * x + sine * z + building.position[0], + -sine * x + cosine * z + building.position[2], + ], + } +} + +export function slabTerrainHeightAt( + slab: SlabNode, + nodes: Readonly>, + x: number, + z: number, + source: 'persisted' | 'live' = 'persisted', +): number { + const frame = slabTerrainFrameOf(slab, nodes, source) + if (!frame) return slab.elevation + const [siteX, siteZ] = frame.toSite(x, z) + return ( + (frame.field ? surfaceHeightAt(frame.field, siteX, siteZ) : 0) - frame.baseY + slab.elevation + ) +} diff --git a/packages/core/src/lib/terrain-authority.ts b/packages/core/src/lib/terrain-authority.ts new file mode 100644 index 0000000000..fb3833619c --- /dev/null +++ b/packages/core/src/lib/terrain-authority.ts @@ -0,0 +1,831 @@ +import { refuse } from '../agent-tools/refusal' +import type { TerrainBreakNode } from '../schema/nodes/terrain-break' +import { TERRAIN_TILE_SIZE } from '../schema/nodes/terrain-tile' +import { + isolatedTerrainPlaneFlagged, + isolatedTriangleFlags, + type TerrainBreakSide, + terrainBreakSideAt, + terrainBreaksOf, +} from './terrain-breaks' +import { + DEFAULT_TERRAIN_SPACING, + DEFAULT_TERRAIN_STEP, + heightAt, + heightAtSample, + type TerrainField, +} from './terrain-field' +import { + type GradedSample, + gradedSamplesOf, + insideRampCut, + type RampCut, + rampCutOf, + rampsGradingOf, +} from './terrain-ramp-cut' +import { type TerrainNodes, type TerrainSite, terrainTilesOf, tileFieldOf } from './terrain-tiles' + +/** Border value and outward slope decay to the source-derived context plane at 64m. */ +export const TERRAIN_CONTINUATION_DISTANCE = 64 +/** Flat sites and tile-only sites have no legacy relief from which to infer context. */ +export const TERRAIN_CONTEXT_HEIGHT = 0 + +/** Frozen legacy minimum, capped at datum; tile edits and lot resizing never move it. */ +export function terrainContextHeightOf(base: TerrainField | null): number { + if (base?.contextHeight !== undefined) return base.contextHeight + let minimum = TERRAIN_CONTEXT_HEIGHT + if (base) for (const sample of base.heights) minimum = Math.min(minimum, sample * base.step) + return minimum +} + +type TileField = { ix: number; iz: number; field: TerrainField } +type Border = { x: number; z: number; distance: number } + +function borderOf(field: TerrainField, x: number, z: number): Border { + const bx = Math.max( + field.origin[0], + Math.min(x, field.origin[0] + (field.cols - 1) * field.spacing), + ) + const bz = Math.max( + field.origin[1], + Math.min(z, field.origin[1] + (field.rows - 1) * field.spacing), + ) + return { x: bx, z: bz, distance: Math.hypot(x - bx, z - bz) } +} + +function tileCoordinates(value: number): number[] { + const index = Math.floor(value / TERRAIN_TILE_SIZE) + return value === index * TERRAIN_TILE_SIZE ? [index - 1, index] : [index] +} + +function tileAt(tiles: Map, x: number, z: number): TileField | undefined { + for (const ix of tileCoordinates(x)) { + for (const iz of tileCoordinates(z)) { + const tile = tiles.get(`${ix},${iz}`) + if (tile) return tile + } + } + return undefined +} + +function tileSample( + tiles: Map, + tile: TileField, + col: number, + row: number, +): number { + const x = tile.field.origin[0] + col * tile.field.spacing + const z = tile.field.origin[1] + row * tile.field.spacing + const owner = tileAt(tiles, x, z) ?? tile + return heightAtSample( + owner.field, + (x - owner.field.origin[0]) / owner.field.spacing, + (z - owner.field.origin[1]) / owner.field.spacing, + ) +} + +function tileHeight(tiles: Map, tile: TileField, x: number, z: number): number { + const field = tile.field + const u = Math.max(0, Math.min(field.cols - 1, (x - field.origin[0]) / field.spacing)) + const v = Math.max(0, Math.min(field.rows - 1, (z - field.origin[1]) / field.spacing)) + const col = Math.min(field.cols - 2, Math.floor(u)) + const row = Math.min(field.rows - 2, Math.floor(v)) + const tc = u - col + const tr = v - row + const h00 = tileSample(tiles, tile, col, row) + const h10 = tileSample(tiles, tile, col + 1, row) + const h01 = tileSample(tiles, tile, col, row + 1) + const h11 = tileSample(tiles, tile, col + 1, row + 1) + return tc + tr <= 1 + ? h00 + (h10 - h00) * tc + (h01 - h00) * tr + : h11 + (h01 - h11) * (1 - tc) + (h10 - h11) * (1 - tr) +} + +function continuedHeight( + field: TerrainField, + read: (x: number, z: number) => number, + x: number, + z: number, + border: Border, + contextHeight: number, +): number { + const dx = x - border.x + const dz = z - border.z + const h = read(border.x, border.z) + const slopeX = + dx === 0 + ? 0 + : (Math.sign(dx) * (h - read(border.x - Math.sign(dx) * field.spacing, border.z))) / + field.spacing + const slopeZ = + dz === 0 + ? 0 + : (Math.sign(dz) * (h - read(border.x, border.z - Math.sign(dz) * field.spacing))) / + field.spacing + const t = border.distance / TERRAIN_CONTINUATION_DISTANCE + return ( + contextHeight + + (h - contextHeight) * (1 - 3 * t * t + 2 * t * t * t) + + (slopeX * dx + slopeZ * dz) * (1 - t) * (1 - t) + ) +} + +function continuation( + sources: { field: TerrainField; read: (x: number, z: number) => number }[], + x: number, + z: number, + contextHeight: number, +): number { + const candidates = sources + .map((source) => ({ source, border: borderOf(source.field, x, z) })) + .filter(({ border }) => border.distance < TERRAIN_CONTINUATION_DISTANCE) + let nearestDistance = TERRAIN_CONTINUATION_DISTANCE + for (const { source, border } of candidates) { + if (border.distance === 0) return source.read(x, z) + nearestDistance = Math.min(nearestDistance, border.distance) + } + let weighted = 0 + let weightSum = 0 + for (const { source, border } of candidates) { + // Inverse-distance blending avoids a bisector seam between disconnected authored tiles. + const weight = + ((1 - border.distance / TERRAIN_CONTINUATION_DISTANCE) * + (nearestDistance / border.distance)) ** + 2 + weighted += continuedHeight(source.field, source.read, x, z, border, contextHeight) * weight + weightSum += weight + } + return weightSum > 0 ? weighted / weightSum : contextHeight +} + +function boundsSources(tiles: Map, base: TerrainField | null): BoundsSource[] { + const sources: BoundsSource[] = [...tiles.values()].map((tile) => ({ + field: tile.field, + exposed: [ + !tiles.has(`${tile.ix - 1},${tile.iz}`), + !tiles.has(`${tile.ix + 1},${tile.iz}`), + !tiles.has(`${tile.ix},${tile.iz - 1}`), + !tiles.has(`${tile.ix},${tile.iz + 1}`), + ], + notch: [ + !tiles.has(`${tile.ix - 1},${tile.iz - 1}`), + !tiles.has(`${tile.ix + 1},${tile.iz - 1}`), + !tiles.has(`${tile.ix - 1},${tile.iz + 1}`), + !tiles.has(`${tile.ix + 1},${tile.iz + 1}`), + ], + })) + if (base) sources.push({ field: base, exposed: [true, true, true, true] }) + return sources +} + +function unionExtent(site: TerrainSite, fields: TerrainField[]) { + const points: (readonly [number, number])[] = [...(site.polygon?.points ?? [])] + for (const field of fields) { + points.push(field.origin, [ + field.origin[0] + (field.cols - 1) * field.spacing, + field.origin[1] + (field.rows - 1) * field.spacing, + ]) + } + let minX = Number.POSITIVE_INFINITY + let minZ = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let maxZ = Number.NEGATIVE_INFINITY + for (const [x, z] of points) { + minX = Math.min(minX, x) + minZ = Math.min(minZ, z) + maxX = Math.max(maxX, x) + maxZ = Math.max(maxZ, z) + } + minX = Math.floor(minX / DEFAULT_TERRAIN_SPACING) + minZ = Math.floor(minZ / DEFAULT_TERRAIN_SPACING) + maxX = Math.ceil(maxX / DEFAULT_TERRAIN_SPACING) + maxZ = Math.ceil(maxZ / DEFAULT_TERRAIN_SPACING) + return { + origin: [minX * DEFAULT_TERRAIN_SPACING, minZ * DEFAULT_TERRAIN_SPACING] as const, + cols: maxX - minX + 1, + rows: maxZ - minZ + 1, + } +} + +function authorityHeightBounds(fields: TerrainField[]): readonly [number, number] { + let lo = TERRAIN_CONTEXT_HEIGHT + let hi = TERRAIN_CONTEXT_HEIGHT + let smallestSpacing = Number.POSITIVE_INFINITY + for (const field of fields) { + smallestSpacing = Math.min(smallestSpacing, field.spacing) + for (const sample of field.heights) { + lo = Math.min(lo, sample * field.step) + hi = Math.max(hi, sample * field.step) + } + } + // d(1-d/N)² peaks at 4N/27; both outward slope components fit this envelope. + const slopeRelief = + (((hi - lo) / smallestSpacing) * Math.SQRT2 * TERRAIN_CONTINUATION_DISTANCE * 4) / 27 + return [lo - slopeRelief, hi + slopeRelief] +} + +/** The slope term's range over the quadrant of directions a corner sample continues into. */ +function quadrantSlope(gx: number, gz: number): [number, number] { + const upper = gx >= 0 && gz >= 0 ? Math.hypot(gx, gz) : Math.max(gx, gz) + const lower = gx <= 0 && gz <= 0 ? -Math.hypot(gx, gz) : Math.min(gx, gz) + return [lower, upper] +} + +const T_STEPS = 64 + +type BoundsSource = { + field: TerrainField + /** Which sides no neighbouring tile covers: west, east, north, south (x-, x+, z-, z+). */ + exposed: readonly [boolean, boolean, boolean, boolean] + /** Corners (nw, ne, sw, se) with no tile diagonally beyond them, though both sides are shared. */ + notch?: readonly [boolean, boolean, boolean, boolean] +} + +/** + * The tightest bounds the authority's own formulas allow, not a worst case over the slope. + * + * Inside a source's rectangle the ground is one of its samples (or a plane through three). + * Outside, `continuation` blends, with positive weights, each source's continued value, so its + * range is inside the union of the sources' own: from a border sample of height h, outward slope + * g and distance t of 64 m, `continuedHeight` is ctx + (h - ctx)(1 - 3t² + 2t³) + g·64·t(1 - t)², + * linear in (h, g) for a fixed t and the border's h and g linear between samples, so its extremes + * are at the lattice samples of the border. Only a side no neighbouring tile covers is a border + * ground continues from: past a shared side the ground is the neighbour's own samples, and the + * weights give a tile behind another next to nothing. `slopeRelief` before was the largest slope + * the quantisation could hold times the full distance: a ±160 m envelope for 6 m of relief. + */ +function tightHeightBounds(sources: BoundsSource[], contextHeight: number): [number, number] { + let lo = Math.min(TERRAIN_CONTEXT_HEIGHT, contextHeight) + let hi = TERRAIN_CONTEXT_HEIGHT + for (const { field, exposed, notch } of sources) { + for (const sample of field.heights) { + lo = Math.min(lo, sample * field.step) + hi = Math.max(hi, sample * field.step) + } + const { cols, rows, spacing, step, heights } = field + if (cols < 2 || rows < 2) continue + const at = (c: number, r: number) => (heights[r * cols + c] ?? 0) * step + const reach = (h: number, gLow: number, gHigh: number) => { + for (let k = 0; k <= T_STEPS; k++) { + const t = k / T_STEPS + const blend = contextHeight + (h - contextHeight) * (1 - 3 * t * t + 2 * t * t * t) + const slope = TERRAIN_CONTINUATION_DISTANCE * t * (1 - t) * (1 - t) + lo = Math.min(lo, blend + gLow * slope) + hi = Math.max(hi, blend + gHigh * slope) + } + } + const [west, east, north, south] = exposed + const [nw, ne, sw, se] = notch ?? [false, false, false, false] + for (let r = 0; r < rows; r++) + for (let c = 0; c < cols; c++) { + const corner = + (nw && c === 0 && r === 0) || + (ne && c === cols - 1 && r === 0) || + (sw && c === 0 && r === rows - 1) || + (se && c === cols - 1 && r === rows - 1) + const onWest = (west || corner) && c === 0 + const onEast = (east || corner) && c === cols - 1 + const onNorth = (north || corner) && r === 0 + const onSouth = (south || corner) && r === rows - 1 + if (!(onWest || onEast || onNorth || onSouth)) continue + const h = at(c, r) + // Outward slopes along x and z, where this sample is on that side's border. + const gx = onWest + ? (h - at(1, r)) / spacing + : onEast + ? (h - at(cols - 2, r)) / spacing + : undefined + const gz = onNorth + ? (h - at(c, 1)) / spacing + : onSouth + ? (h - at(c, rows - 2)) / spacing + : undefined + if (gx !== undefined && gz !== undefined) { + const [low, high] = quadrantSlope(gx, gz) + reach(h, low, high) + } else { + const g = (gx ?? gz) as number + reach(h, g, g) + } + } + } + // The tiles behind another contribute a sliver of their own continuation, weights near zero. + const pad = 0.01 + 0.01 * (hi - lo) + return [lo - pad, hi + pad] +} + +type BreakAuthority = { + breaks: TerrainBreakNode[] + tiles: Map + base: TerrainField | null + contextByRegion: Map + fallback?: BreakAuthority +} +type Source = { field: TerrainField; read: (x: number, z: number) => number } +const breakAuthorities = new WeakMap() +/** The two grounds a ramp-cut authority is made of, so a live preview can be made of both. */ +const rampCutHalves = new WeakMap< + TerrainField, + { graded: TerrainField; natural: TerrainField; cuts: readonly RampCut[] } +>() +/** Authorities whose bounds are the true ones (tiles or breaks), not the legacy envelope. */ +const tightBounds = new WeakSet() + +function breakSidesAt(breaks: TerrainBreakNode[], x: number, z: number): TerrainBreakSide[] { + return breaks.map((boundary) => terrainBreakSideAt(boundary, x, z)) +} + +function regionContext( + authority: BreakAuthority, + sides: TerrainBreakSide[], + accepts: (x: number, z: number) => boolean, +): number { + const key = sides.join(',') + const cached = authority.contextByRegion.get(key) + if (cached !== undefined) return cached + let context = 0 + const base = authority.base + if (base) { + for (let r = 0; r < base.rows; r++) { + for (let c = 0; c < base.cols; c++) { + if (accepts(base.origin[0] + c * base.spacing, base.origin[1] + r * base.spacing)) + context = Math.min(context, (base.heights[r * base.cols + c] ?? 0) * base.step) + } + } + } + authority.contextByRegion.set(key, context) + return context +} + +const KEEP_GROUND_MESSAGE = + 'Keep-ground needs a same-side source triangle within 32 grid cells; widen the ground region or give a numeric side.' + +/** + * The triangle tables of a grid, kept for as long as the grid and the breaks are the same + * objects: editing one tile builds the authority again, and the other 23 tiles' tables are + * still the tables of their own region. + */ +const flagTables = new WeakMap< + TerrainField, + { breaks: readonly TerrainBreakNode[]; regions: Map } +>() + +function regionFlags( + authority: BreakAuthority, + field: TerrainField, + sides: TerrainBreakSide[], + accepts: (x: number, z: number) => boolean, +): Uint8Array { + let entry = flagTables.get(field) + const { breaks } = authority + if ( + !entry || + entry.breaks.length !== breaks.length || + entry.breaks.some((boundary, index) => boundary !== breaks[index]) + ) { + entry = { breaks, regions: new Map() } + flagTables.set(field, entry) + } + const key = sides.join(',') + let flags = entry.regions.get(key) + if (!flags) { + flags = isolatedTriangleFlags(field, accepts, breaks) + entry.regions.set(key, flags) + } + return flags +} + +function isolatedSources( + authority: BreakAuthority, + sides: TerrainBreakSide[], + accepts: (x: number, z: number) => boolean, + x: number, + z: number, +): Source[] { + const { tiles, base } = authority + const sources: Source[] = [] + const add = (field: TerrainField, sample?: (c: number, r: number) => number) => { + const flags = regionFlags(authority, field, sides, accepts) + if (isolatedTerrainPlaneFlagged(field, flags, x, z, sample)) + sources.push({ + field, + read: (px, pz) => { + const plane = isolatedTerrainPlaneFlagged(field, flags, px, pz, sample) + if (plane) return plane(px, pz) + refuse('unsupported_geometry', KEEP_GROUND_MESSAGE) + }, + }) + } + for (const tile of tiles.values()) add(tile.field, (c, r) => tileSample(tiles, tile, c, r)) + if (base) add(base) + return sources +} + +function regionGround( + authority: BreakAuthority, + sides: TerrainBreakSide[], + x: number, + z: number, +): number { + const { breaks, tiles, base } = authority + if (authority.fallback && base && borderOf(base, x, z).distance > 0) + return regionGround(authority.fallback, sides, x, z) + const accepts = (px: number, pz: number) => { + for (let i = 0; i < breaks.length; i++) + if (terrainBreakSideAt(breaks[i] as TerrainBreakNode, px, pz) !== sides[i]) return false + return true + } + // A point a tile covers reads that tile's source triangle alone: the other tiles' planes were + // searched for and never read. + const tile = tileAt(tiles, x, z) + if (tile) { + const plane = isolatedTerrainPlaneFlagged( + tile.field, + regionFlags(authority, tile.field, sides, accepts), + x, + z, + (c, r) => tileSample(tiles, tile, c, r), + ) + if (plane) return plane(x, z) + refuse( + 'unsupported_geometry', + 'The covering terrain tile has no same-region source triangle for keep-ground.', + ) + } + if (base && borderOf(base, x, z).distance === 0) { + const plane = isolatedTerrainPlaneFlagged( + base, + regionFlags(authority, base, sides, accepts), + x, + z, + ) + if (plane) return plane(x, z) + refuse('unsupported_geometry', KEEP_GROUND_MESSAGE) + } + const sources = isolatedSources(authority, sides, accepts, x, z) + return continuation(sources, x, z, regionContext(authority, sides, accepts)) +} + +function regionHeight( + authority: BreakAuthority, + sides: TerrainBreakSide[], + x: number, + z: number, +): number { + for (let i = authority.breaks.length - 1; i >= 0; i--) { + const boundary = authority.breaks[i] + const side = sides[i] + if (!boundary || !side) continue + const value = boundary[side] + if (typeof value === 'number') return value + } + return regionGround(authority, sides, x, z) +} + +function breakSideHeight( + authority: BreakAuthority, + boundary: TerrainBreakNode, + side: TerrainBreakSide, + x: number, + z: number, +): number { + const sides = breakSidesAt(authority.breaks, x, z) + const index = authority.breaks.findIndex((candidate) => candidate.id === boundary.id) + if (index >= 0) sides[index] = side + return regionHeight(authority, sides, x, z) +} + +const PROBE_OFFSETS = [0.02, 0.25, 0.6, 1.2] + +function probeBreakBounds(field: TerrainField, breaks: TerrainBreakNode[]): [number, number] { + let lo = Number.POSITIVE_INFINITY + let hi = Number.NEGATIVE_INFINITY + const read = field.readHeightAt + if (!read) return [lo, hi] + for (const boundary of breaks) { + for (let i = 0; i < boundary.line.length - 1; i++) { + const a = boundary.line[i] as [number, number] + const b = boundary.line[i + 1] as [number, number] + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + if (length < 1e-9) continue + const nx = (b[1] - a[1]) / length + const nz = -(b[0] - a[0]) / length + const count = Math.max(1, Math.ceil(length / field.spacing)) + for (let k = 0; k <= count; k++) { + const x = a[0] + ((b[0] - a[0]) * k) / count + const z = a[1] + ((b[1] - a[1]) * k) / count + for (const offset of PROBE_OFFSETS) + for (const sign of [-1, 1]) { + try { + const value = read(x + nx * offset * sign, z + nz * offset * sign) + lo = Math.min(lo, value) + hi = Math.max(hi, value) + } catch { + // a side with no source triangle refuses; there is no height to bound + } + } + } + } + } + return [lo, hi] +} + +function withTerrainBreaks( + field: TerrainField, + breaks: TerrainBreakNode[], + tiles: Map, + base: TerrainField | null, + fallback?: BreakAuthority, +): TerrainField { + if (!breaks.length) return field + const authority: BreakAuthority = { + breaks, + tiles, + base, + contextByRegion: new Map(), + fallback, + } + const numeric = breaks.flatMap((boundary) => + [boundary.left, boundary.right].filter((value): value is number => typeof value === 'number'), + ) + const bounds = field.heightBounds ?? [0, 0] + const result: TerrainField & { heightBounds: [number, number] } = { + ...field, + terrainBreaks: breaks, + heightBounds: [Math.min(bounds[0], ...numeric), Math.max(bounds[1], ...numeric)], + readHeightAt: (x, z) => regionHeight(authority, breakSidesAt(breaks, x, z), x, z), + readHeightInRegion: (ox, oz, x, z) => + regionHeight(authority, breakSidesAt(breaks, ox, oz), x, z), + readHeightOnSide: (boundary, side, x, z) => breakSideHeight(authority, boundary, side, x, z), + } + // Ground kept beside a break is read from a plane through the nearest same-side triangle, which + // runs a little past its samples: take the reads along each break, both sides, into the bounds. + if (!fallback) { + const probed = probeBreakBounds(result, breaks) + result.heightBounds = [ + Math.min(result.heightBounds[0], probed[0]), + Math.max(result.heightBounds[1], probed[1]), + ] + } + breakAuthorities.set(result, authority) + return result +} + +function authorityOver( + site: TerrainSite, + base: TerrainField | null, + tiles: Map, + breaks: TerrainBreakNode[], +): TerrainField | null { + if (!base && tiles.size === 0 && !breaks.length) return null + const contextHeight = terrainContextHeightOf(base) + const sources = [...tiles.values()].map((tile) => ({ + field: tile.field, + read: (x: number, z: number) => tileHeight(tiles, tile, x, z), + })) + if (base) sources.push({ field: base, read: (x, z) => heightAt(base, x, z) }) + const unchangedLayout = + base && + tiles.size === 0 && + (site.polygon?.points ?? []).every(([x, z]) => borderOf(base, x, z).distance === 0) + const fields = sources.map((source) => source.field) + const extentSite = breaks.length + ? { + ...site, + polygon: { + type: 'polygon' as const, + points: [...(site.polygon?.points ?? []), ...breaks.flatMap((boundary) => boundary.line)], + }, + } + : site + const field: TerrainField = { + ...(unchangedLayout + ? { + origin: base.origin, + cols: base.cols, + rows: base.rows, + } + : unionExtent(extentSite, fields)), + spacing: unchangedLayout ? base.spacing : DEFAULT_TERRAIN_SPACING, + step: base?.step ?? sources[0]?.field.step ?? DEFAULT_TERRAIN_STEP, + heights: unchangedLayout ? base.heights : new Int16Array(0), + // A lot of legacy ground alone keeps the bounds it always had; tiles and breaks get true ones. + heightBounds: + tiles.size > 0 || breaks.length > 0 + ? tightHeightBounds(boundsSources(tiles, base), contextHeight) + : authorityHeightBounds(fields), + contextHeight, + readHeightAt: (x, z) => { + const tile = tileAt(tiles, x, z) + if (tile) return tileHeight(tiles, tile, x, z) + if (base && borderOf(base, x, z).distance === 0) return heightAt(base, x, z) + return continuation(sources, x, z, contextHeight) + }, + } + const authority = withTerrainBreaks(field, breaks, tiles, base) + if (tiles.size > 0 || breaks.length > 0) tightBounds.add(authority) + return authority +} + +/** The tiles with the ramps' graded samples put back, or null when none is still as graded. */ +function tilesBeforeGrading( + tiles: Map, + samples: readonly GradedSample[], +): Map | null { + const heights = new Map() + const owners = (coordinate: number) => { + const index = Math.floor(coordinate / TERRAIN_TILE_SIZE) + return coordinate === index * TERRAIN_TILE_SIZE ? [index - 1, index] : [index] + } + for (const { x, z, previousM, appliedM } of samples) { + for (const ix of owners(x)) { + for (const iz of owners(z)) { + const key = `${ix},${iz}` + const tile = tiles.get(key) + if (!tile) continue + const { field } = tile + const col = (x - field.origin[0]) / field.spacing + const row = (z - field.origin[1]) / field.spacing + if (!Number.isInteger(col) || !Number.isInteger(row)) continue + if (col < 0 || row < 0 || col >= field.cols || row >= field.rows) continue + const index = row * field.cols + col + // Ground sculpted since the grading is the person's own and stays. + if (Math.abs((field.heights[index] ?? 0) * field.step - appliedM) > field.step / 2) continue + let own = heights.get(key) + if (!own) { + own = new Int16Array(field.heights) + heights.set(key, own) + } + own[index] = Math.max(-32768, Math.min(32767, Math.round(previousM / field.step))) + } + } + } + if (!heights.size) return null + const before = new Map(tiles) + for (const [key, own] of heights) { + const tile = tiles.get(key) as TileField + before.set(key, { ...tile, field: { ...tile.field, heights: own } }) + } + return before +} + +/** + * The ground beside a graded ramp is the natural ground, read up to the corridor's own edge; the + * corridor keeps the graded samples. Without this a lattice triangle that straddles the edge + * mixes lowered and natural samples, and every reader (the mesh, the pointer ray, the lawn, the + * normals) sees the ground dip toward the roadway by up to a cell along a curved edge. + */ +function withRampCuts( + graded: TerrainField, + natural: TerrainField, + cuts: readonly RampCut[], +): TerrainField { + const inGradedCorridor = (x: number, z: number) => cuts.some((cut) => insideRampCut(cut, x, z)) + const bounds: [number, number] = [ + Math.min(graded.heightBounds?.[0] ?? 0, natural.heightBounds?.[0] ?? 0), + Math.max(graded.heightBounds?.[1] ?? 0, natural.heightBounds?.[1] ?? 0), + ] + const gradedOnSide = graded.readHeightOnSide + const naturalOnSide = natural.readHeightOnSide + const read = (field: TerrainField, x: number, z: number) => + (field.readHeightAt as (x: number, z: number) => number)(x, z) + const result: TerrainField = { + ...graded, + heightBounds: bounds, + readStoredHeightAt: (x, z) => read(graded, x, z), + readHeightAt: (x, z) => read(inGradedCorridor(x, z) ? graded : natural, x, z), + // A region is the one its origin lies in: a vertex on the corridor's edge takes its normal + // from the natural ground on both sides of it. + readHeightInRegion: (ox, oz, x, z) => { + const field = inGradedCorridor(ox, oz) ? graded : natural + return field.readHeightInRegion ? field.readHeightInRegion(ox, oz, x, z) : read(field, x, z) + }, + ...(gradedOnSide && naturalOnSide + ? { + readHeightOnSide: ( + boundary: TerrainBreakNode, + side: TerrainBreakSide, + x: number, + z: number, + ) => (inGradedCorridor(x, z) ? gradedOnSide : naturalOnSide)(boundary, side, x, z), + } + : {}), + } + const authority = breakAuthorities.get(graded) + if (authority) breakAuthorities.set(result, authority) + if (tightBounds.has(graded)) tightBounds.add(result) + rampCutHalves.set(result, { graded, natural, cuts }) + return result +} + +export function terrainAuthorityField( + site: TerrainSite, + base: TerrainField | null, + nodes?: TerrainNodes, +): TerrainField | null { + const breaks = terrainBreaksOf(site, nodes) + const tiles = new Map() + for (const tile of terrainTilesOf(site, nodes)) { + const field = tileFieldOf(tile) + const key = `${tile.ix},${tile.iz}` + if (field && !tiles.has(key)) tiles.set(key, { ix: tile.ix, iz: tile.iz, field }) + } + const graded = authorityOver(site, base, tiles, breaks) + if (!graded || !tiles.size) return graded + const ramps = rampsGradingOf(site, nodes) + if (!ramps.length) return graded + const cuts = ramps.flatMap((ramp) => rampCutOf(ramp) ?? []) + const before = cuts.length + ? tilesBeforeGrading(tiles, gradedSamplesOf(cuts.map((cut) => cut.ramp))) + : null + if (!before) return graded + const natural = authorityOver(site, base, before, breaks) + return natural ? withRampCuts(graded, natural, cuts) : graded +} + +const previewFields = new WeakMap>() +const NO_PERSISTED = {} as TerrainField + +/** + * A live edit overrides only its bounded working rectangle, not the rest of the scene. + * + * One field for one pair: every ground mesh, the skirt and each break ask for the same preview on + * every dab, and making it reads every sample of the edit for its bounds (a 480 m lot is 954 000 + * samples, asked for 258 times a dab). + */ +export function terrainPreviewField( + preview: TerrainField, + persisted: TerrainField | null, +): TerrainField { + if (preview === persisted) return persisted + let made = previewFields.get(preview) + if (!made) { + made = new WeakMap() + previewFields.set(preview, made) + } + const key = persisted ?? NO_PERSISTED + let field = made.get(key) + if (!field) { + field = makeTerrainPreviewField(preview, persisted) + made.set(key, field) + } + return field +} + +function makeTerrainPreviewField( + preview: TerrainField, + persisted: TerrainField | null, +): TerrainField { + // Each ground is previewed on its own, so outside the stroke's rectangle the ground beside a + // ramp stays natural (the break branch below would fall back to the graded tiles for all of it). + const halves = persisted ? rampCutHalves.get(persisted) : undefined + if (halves) + return withRampCuts( + terrainPreviewField(preview, halves.graded), + terrainPreviewField(preview, halves.natural), + halves.cuts, + ) + if (!persisted) + return { + ...preview, + heightBounds: authorityHeightBounds([preview]), + contextHeight: TERRAIN_CONTEXT_HEIGHT, + readHeightAt: (x, z) => { + const border = borderOf(preview, x, z) + return border.distance === 0 + ? heightAt(preview, x, z) + : border.distance >= TERRAIN_CONTINUATION_DISTANCE + ? TERRAIN_CONTEXT_HEIGHT + : continuedHeight( + preview, + (px, pz) => heightAt(preview, px, pz), + x, + z, + border, + TERRAIN_CONTEXT_HEIGHT, + ) + }, + } + // Outside its rectangle the preview reads the persisted ground, so against true persisted + // bounds only the preview's own samples add to them. + const previewBounds = tightBounds.has(persisted) + ? tightHeightBounds( + [{ field: preview, exposed: [true, true, true, true] }], + TERRAIN_CONTEXT_HEIGHT, + ) + : authorityHeightBounds([preview]) + const persistedBounds = persisted.heightBounds ?? authorityHeightBounds([persisted]) + const field: TerrainField = { + ...persisted, + heightBounds: [ + Math.min(previewBounds[0], persistedBounds[0]), + Math.max(previewBounds[1], persistedBounds[1]), + ], + readHeightAt: (x, z) => + borderOf(preview, x, z).distance === 0 ? heightAt(preview, x, z) : heightAt(persisted, x, z), + } + const authority = breakAuthorities.get(persisted) + return authority + ? withTerrainBreaks(field, authority.breaks, new Map(), preview, authority) + : field +} diff --git a/packages/core/src/lib/terrain-bounds.test.ts b/packages/core/src/lib/terrain-bounds.test.ts new file mode 100644 index 0000000000..d35f15a82d --- /dev/null +++ b/packages/core/src/lib/terrain-bounds.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test } from 'bun:test' +import { + RING_A, + RING_C, + terrainLagScene, + terrainLagScenes, +} from './__fixtures__/terrain-lag-scenes' +import { heightAt } from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' + +/* + * Failure modes this file pins (the terrain lag, 15 Oct): the virtual ground's `heightBounds` was a + * worst case over the slope, ±160 m for 6 m of relief on the owner's scene, so the lot's block + * dropped to −168 m, every terrain raycast clipped against a 320 m tall box, and a bound that + * is tight must still contain the ground: + * - a bound that sits inside the sampled extremes clips terrain out of a raycast or a frustum; + * - a bound far outside them costs the draw and the march; + * - a legacy-only scene's bounds change. + */ + +const smooth = { roughness: 0 } +const graded = [ + { line: RING_A, left: -3.8 as number | 'ground', right: 'ground' as number | 'ground' }, + { line: RING_C, left: -3.6 as number | 'ground', right: 'ground' as number | 'ground' }, +] +// The owner's ground is graded smooth; the noisy scenes of the golden tests are rougher than it +// and the cliff has an eight-metre step on a shared tile border. +const scenes = [ + ...terrainLagScenes().filter((scene) => scene.name !== 'legacy only'), + terrainLagScene('smooth, tiles only', smooth), + terrainLagScene('smooth, rings', { ...smooth, breaks: graded }), + terrainLagScene('smooth, legacy and rings', { ...smooth, legacy: true, breaks: graded }), + terrainLagScene('cliff on an interior tile', { ...smooth, plateau: 8 }), + terrainLagScene('cliff and rings', { ...smooth, plateau: 8, breaks: graded }), +] +const tight = (name: string) => name.startsWith('smooth') || name.startsWith('cliff') + +function sampled(field: NonNullable>) { + const [ox, oz] = field.origin + const maxX = ox + (field.cols - 1) * field.spacing + const maxZ = oz + (field.rows - 1) * field.spacing + let lo = Number.POSITIVE_INFINITY + let hi = Number.NEGATIVE_INFINITY + for (let x = ox - 70; x <= maxX + 70; x += 1.7) + for (let z = oz - 70; z <= maxZ + 70; z += 1.7) { + const h = heightAt(field, x, z) + lo = Math.min(lo, h) + hi = Math.max(hi, h) + } + return { lo, hi } +} + +describe('the virtual ground’s height bounds are the ground’s', () => { + test.each(scenes.map((scene) => [scene.name, scene] as const))( + '%s: contain every sampled height and sit near the extremes', + (_, scene) => { + const field = persistedTerrainFieldOf(scene.site, scene.nodes)! + const [lo, hi] = field.heightBounds! + const real = sampled(field) + expect(lo).toBeLessThanOrEqual(real.lo + 1e-9) + expect(hi).toBeGreaterThanOrEqual(real.hi - 1e-9) + // Ground blends the borders of every tile along an edge, so the border-by-border extreme + // this bound takes is a little past the blended one: 2 m on ground this steep and this rough. + const tolerance = tight(scene.name) ? 2 : 3.5 + expect(real.lo - lo).toBeLessThan(tolerance) + expect(hi - real.hi).toBeLessThan(tolerance) + }, + ) + + test('a relief of −6…0 m is bounded by a few metres, not by 160', () => { + const scene = scenes.find((entry) => entry.name === 'three rings, ground outside')! + const [lo, hi] = persistedTerrainFieldOf(scene.site, scene.nodes)!.heightBounds! + expect(lo).toBeGreaterThan(-12) + expect(hi).toBeLessThan(6) + }) +}) diff --git a/packages/core/src/lib/terrain-break-validation.ts b/packages/core/src/lib/terrain-break-validation.ts new file mode 100644 index 0000000000..e521bdb849 --- /dev/null +++ b/packages/core/src/lib/terrain-break-validation.ts @@ -0,0 +1,40 @@ +import { refuse } from '../agent-tools/refusal' +import type { SiteNode } from '../schema/nodes/site' +import { terrainBreakFacts, terrainBreaksOf, validateTerrainBreakLotSpan } from './terrain-breaks' +import { persistedTerrainFieldOf } from './terrain-source-persisted' +import type { TerrainNodes } from './terrain-tiles' + +function validateSiteBreaks(site: SiteNode, nodes: TerrainNodes): void { + const breaks = terrainBreaksOf(site, nodes) + if (!breaks.length) return + for (const boundary of breaks) validateTerrainBreakLotSpan(boundary, site.polygon.points) + const field = persistedTerrainFieldOf(site, nodes) + if (!field) refuse('no_terrain', 'The proposed terrain-break field cannot be read.') + for (const boundary of breaks) terrainBreakFacts(boundary, field) +} + +export function validateTerrainBreakRelations( + before: TerrainNodes, + next: TerrainNodes, + changedIds: Iterable, +): void { + const sites = new Set() + for (const id of changedIds) { + for (const node of [before[id], next[id]]) { + if ((node?.type === 'terrain-break' || node?.type === 'terrain-tile') && node.parentId) + sites.add(node.parentId) + if (node?.type === 'site') sites.add(node.id) + } + const boundary = next[id] + if (boundary?.type !== 'terrain-break') continue + const site = boundary.parentId ? next[boundary.parentId] : undefined + if (site?.type !== 'site') + refuse('invalid_parent', 'A terrain break must belong directly to a site.') + if (boundary.kind !== 'cliff' && boundary.kind !== 'retaining' && boundary.kind !== 'soil') + refuse('invalid_input', 'A terrain break must be cliff, retaining or soil.') + } + for (const id of sites) { + const site = next[id] + if (site?.type === 'site') validateSiteBreaks(site, next) + } +} diff --git a/packages/core/src/lib/terrain-breaks.test.ts b/packages/core/src/lib/terrain-breaks.test.ts new file mode 100644 index 0000000000..c564d03e5e --- /dev/null +++ b/packages/core/src/lib/terrain-breaks.test.ts @@ -0,0 +1,623 @@ +import { describe, expect, test } from 'bun:test' +import { + createSceneSpatialGrid, + createTerrainField, + encodeTerrainField, + heightAt, + isFlatOver, + normalAt, + persistedTerrainFieldOf, + raycastTerrain, + slabTerrainHeightAt, + slopeAt, + type TerrainField, + terrainBreakFacts, + terrainBreakHeightAt, + terrainBreakSideAt, + terrainBreaksOf, + terrainContours, + terrainPreviewField, +} from '@pascal-app/core' +import { + AnyNode, + BuildingNode, + LevelNode, + SiteNode, + SlabNode, + TerrainBreakNode, + TerrainTileNode, +} from '@pascal-app/core/schema' + +const line: [number, number][] = [ + [4, 0], + [4, 8], +] +const ring: [number, number][] = [ + [2, 2], + [6, 2], + [6, 6], + [2, 6], + [2, 2], +] + +function terrainBreak(overrides: Record = {}) { + return TerrainBreakNode.parse({ + id: 'terrain-break_edge', + parentId: 'site_breaks', + line, + kind: 'cliff', + left: 5, + right: 2, + ...overrides, + }) +} + +function scene(field: TerrainField, breaks: TerrainBreakNode[] = [terrainBreak()]) { + const site = SiteNode.parse({ + id: 'site_breaks', + children: breaks.map((edge) => edge.id), + terrain: encodeTerrainField(field), + }) + const nodes: Record = Object.fromEntries( + [site, ...breaks].map((node) => [node.id, node]), + ) + const authority = persistedTerrainFieldOf(site, nodes) + if (!authority) throw new Error('Expected terrain authority') + return { site, nodes, authority } +} + +// Contract oracles: directed XZ cross product, constant planes and the 3-4-5 +// triangle. Neither expected heights nor face areas are obtained from candidate geometry. +describe('terrain break persisted contract', () => { + test('round-trips through the public node union and belongs only to its parent site', () => { + const edge = terrainBreak() + expect(AnyNode.parse(JSON.parse(JSON.stringify(edge)))).toEqual(edge) + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + const { site, nodes } = scene(field) + const other = terrainBreak({ id: 'terrain-break_other', parentId: 'site_other' }) + expect(terrainBreaksOf(site, { ...nodes, [other.id]: other }).map((node) => node.id)).toEqual([ + edge.id, + ]) + }) + + test('requires a numeric side and supported, nondegenerate line geometry', () => { + for (const invalid of [ + { left: 'ground', right: 'ground' }, + { left: Number.NaN }, + { right: Number.POSITIVE_INFINITY }, + { + line: [ + [0, 0], + [0, 0], + ], + }, + { + line: [ + [0, 0], + [2, 1], + [4, 0], + ], + }, + { + line: [ + [0, 0], + [4, 4], + [0, 4], + [4, 0], + [0, 0], + ], + }, + { + line: [ + [0, 0], + [0, 4], + [4, 4], + [4, 0], + [0, 0], + ], + }, + ]) + expect(TerrainBreakNode.safeParse({ ...terrainBreak(), ...invalid }).success).toBe(false) + expect( + TerrainBreakNode.safeParse({ + ...terrainBreak(), + line: [ + [0, 0], + [2, 2], + [4, 4], + ], + }).success, + ).toBe(true) + expect( + TerrainBreakNode.safeParse({ ...terrainBreak(), line: ring, kind: 'retaining' }).success, + ).toBe(true) + }) + + test('positive cross is left, including the line, and a CCW ring has its inside on the left', () => { + const edge = terrainBreak() + expect(terrainBreakSideAt(edge, 4 - 1e-7, 3)).toBe('left') + expect(terrainBreakSideAt(edge, 4, 3)).toBe('left') + expect(terrainBreakSideAt(edge, 4 + 1e-7, 3)).toBe('right') + const closed = terrainBreak({ line: ring }) + expect(terrainBreakSideAt(closed, 4, 4)).toBe('left') + expect(terrainBreakSideAt(closed, 2, 4)).toBe('left') + expect(terrainBreakSideAt(closed, 2 - 1e-7, 4)).toBe('right') + expect(terrainBreakSideAt(closed, 7, 7)).toBe('right') + }) +}) + +describe('terrain break height authority', () => { + test('flatness includes raised lattice posts on the exact rectangle boundary', () => { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 0.5 }) + field.heights[1] = 100 + field.heights[field.cols + 1] = 100 + const edge = terrainBreak({ + line: [ + [3, 0], + [3, 4], + ], + left: 'ground', + right: 2, + }) + const { authority } = scene(field, [edge]) + expect(heightAt(authority, 0.5, 0)).toBe(1) + expect(heightAt(authority, 0.5, 0.5)).toBe(1) + expect(isFlatOver(authority, 0, 0, 1, 0.5)).toBe(false) + }) + + test('flatness detects an enclosed sub-grid pad without rejecting a footprint wholly inside it', () => { + const field = createTerrainField({ cols: 5, rows: 5, spacing: 0.5 }) + const edge = terrainBreak({ + line: [ + [0.2, 0.2], + [0.3, 0.2], + [0.3, 0.3], + [0.2, 0.3], + [0.2, 0.2], + ], + }) + const { authority } = scene(field, [edge]) + expect(isFlatOver(authority, 0.21, 0.21, 0.29, 0.29)).toBe(true) + expect(isFlatOver(authority, 0, 0, 0.5, 0.5)).toBe(false) + expect(isFlatOver(authority, 0.25, 0.21, 0.4, 0.29)).toBe(false) + expect(isFlatOver(authority, 0.4, 0.4, 0.49, 0.49)).toBe(true) + }) + + test('a draped slab wholly inside a sub-grid pad supports items at the exact terrace height', () => { + const field = createTerrainField({ cols: 5, rows: 5, spacing: 0.5 }) + const edge = terrainBreak({ + line: [ + [0.2, 0.2], + [0.3, 0.2], + [0.3, 0.3], + [0.2, 0.3], + [0.2, 0.2], + ], + }) + const base = scene(field, [edge]) + const building = BuildingNode.parse({ + id: 'building_breaks', + parentId: base.site.id, + children: ['level_breaks'], + }) + const level = LevelNode.parse({ + id: 'level_breaks', + parentId: building.id, + level: 0, + children: ['slab_breaks'], + }) + const slab = SlabNode.parse({ + id: 'slab_breaks', + parentId: level.id, + terrainMode: 'draped', + elevation: 0.1, + polygon: [ + [0.21, 0.21], + [0.29, 0.21], + [0.29, 0.29], + [0.21, 0.29], + ], + }) + const site = SiteNode.parse({ ...base.site, children: [edge.id, building.id] }) + const nodes = { + ...base.nodes, + [site.id]: site, + [building.id]: building, + [level.id]: level, + [slab.id]: slab, + } + expect(slabTerrainHeightAt(slab, nodes, 0.25, 0.25)).toBeCloseTo(5.1, 6) + const support = createSceneSpatialGrid(nodes).getSlabSupportForItem( + level.id, + [0.25, 0, 0.25], + [0.02, 0.1, 0.02], + [0, 0, 0], + ) + expect(support.slabId).toBe(slab.id) + expect(support.elevation).toBeCloseTo(5.1, 6) + }) + + for (const spacing of [0.5, 0.95]) { + test(`numeric heights stay discontinuous to 1 mm on a ${spacing} m legacy grid`, () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing, origin: [0.13, 0.27] }) + field.heights.fill(1700) + const { authority } = scene(field) + for (const distance of [1e-7, 0.01, 0.25]) { + expect(Math.abs(heightAt(authority, 4 - distance, 3.17) - 5)).toBeLessThanOrEqual(0.001) + expect(Math.abs(heightAt(authority, 4 + distance, 3.17) - 2)).toBeLessThanOrEqual(0.001) + } + expect(heightAt(authority, 4, 3.17)).toBe(5) + }) + + test(`opposite-side sample contamination cannot alter keep-ground at ${spacing} m spacing`, () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing, origin: [0.13, 0.27] }) + field.heights.fill(125) + const polluted = { ...field, heights: field.heights.slice() } + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + if (field.origin[0] + col * spacing > 4) polluted.heights[row * field.cols + col] = 3000 + const edge = terrainBreak({ left: 'ground', right: -2 }) + const clean = scene(field, [edge]).authority + const dirty = scene(polluted, [edge]).authority + for (const x of [4 - 1e-7, 3.9, 3.5, 4]) { + expect(Math.abs(heightAt(clean, x, 3.17) - 1.25)).toBeLessThanOrEqual(0.001) + expect(heightAt(dirty, x, 3.17)).toBe(heightAt(clean, x, 3.17)) + expect(terrainBreakHeightAt(polluted, edge, 'left', x, 3.17)).toBe(1.25) + expect(slopeAt(dirty, x, 3.17)).toBeCloseTo(0, 8) + const [nx, ny, nz] = normalAt(dirty, x, 3.17) + expect(nx).toBeCloseTo(0, 8) + expect(ny).toBeCloseTo(1, 8) + expect(nz).toBeCloseTo(0, 8) + } + }) + } + + test('normals and slopes use the selected side, not a finite difference across the drop', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.5 }) + const { authority } = scene(field) + for (const x of [4 - 1e-7, 4, 4 + 1e-7]) { + expect(slopeAt(authority, x, 3.17)).toBeCloseTo(0, 8) + const [nx, ny, nz] = normalAt(authority, x, 3.17) + expect(nx).toBeCloseTo(0, 8) + expect(ny).toBeCloseTo(1, 8) + expect(nz).toBeCloseTo(0, 8) + } + }) + + test('a bounded ground preview preserves numeric break sides and leaves distant ground unchanged', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.5 }) + field.heights.fill(125) + const { authority } = scene(field, [terrainBreak({ left: 5, right: 'ground' })]) + const preview = createTerrainField({ origin: [2, 2], cols: 9, rows: 9, spacing: 0.5 }) + preview.heights.fill(900) + const live = terrainPreviewField(preview, authority) + expect(heightAt(live, 4 - 1e-7, 3)).toBe(5) + expect(heightAt(live, 4, 3)).toBe(5) + expect(heightAt(live, 4 + 1e-7, 3)).toBe(9) + expect(heightAt(live, 5, 3)).toBe(9) + expect(heightAt(live, 7, 3)).toBe(1.25) + expect(heightAt(authority, 5, 3)).toBe(1.25) + }) + + test('a preview is made once for an edit and a ground, however many readers ask', () => { + const field = createTerrainField({ cols: 17, rows: 17, spacing: 0.5 }) + field.heights.fill(125) + const { authority } = scene(field, [terrainBreak({ left: 5, right: 'ground' })]) + const edit = createTerrainField({ origin: [2, 2], cols: 9, rows: 9, spacing: 0.5 }) + edit.heights.fill(900) + const live = terrainPreviewField(edit, authority) + // Every ground mesh, the skirt and each break read the stroke's preview on every dab. + expect(terrainPreviewField(edit, authority)).toBe(live) + // The next dab is another edit field, and another ground another preview. + const next = { ...edit, heights: new Int16Array(edit.heights).fill(950) } + const dabbed = terrainPreviewField(next, authority) + expect(dabbed).not.toBe(live) + expect(heightAt(dabbed, 5, 3)).toBe(9.5) + expect(heightAt(live, 5, 3)).toBe(9) + expect(terrainPreviewField(edit, null)).not.toBe(live) + expect(terrainPreviewField(edit, null)).toBe(terrainPreviewField(edit, null)) + }) + + test('ending a preview restores tile-only ground instead of sampling an empty virtual buffer', () => { + const samples = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + samples.heights.fill(200) + const edge = terrainBreak({ right: 'ground' }) + const tile = TerrainTileNode.parse({ + id: 'terrain-tile_preview', + parentId: 'site_breaks', + ix: 0, + iz: 0, + heights: encodeTerrainField(samples).heights, + }) + const site = SiteNode.parse({ id: 'site_breaks', children: [edge.id, tile.id] }) + const authority = persistedTerrainFieldOf(site, { + [site.id]: site, + [tile.id]: tile, + [edge.id]: edge, + }) + if (!authority) throw new Error('Expected tile-only terrain authority') + const restored = terrainPreviewField(authority, authority) + expect(heightAt(restored, 3, 3)).toBe(5) + expect(heightAt(restored, 5, 3)).toBe(2) + expect(heightAt(restored, 4 + 1e-7, 3)).toBe(2) + expect(heightAt(authority, 5, 3)).toBe(2) + }) + + test('a distant break preserves the nonplanar source continuation on its keep-ground side', () => { + const field = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = 200 + row * row + col * col + const original = scene(field, []).authority + const edge = terrainBreak({ + line: [ + [-16, 40], + [48, 40], + ], + left: 5, + right: 'ground', + }) + const withBreak = scene(field, [edge]).authority + // The complete curved source occupies [0,32]², strictly below the break. + // Its existing continuation is the oracle; adding a feature on the other + // side must not replace that continuation with one triangle's tangent plane. + for (const x of [0.25, 12.25, 31.75]) + for (const z of [32.1, 34, 39.5, 40 - 1e-7]) + expect(Math.abs(heightAt(withBreak, x, z) - heightAt(original, x, z))).toBeLessThanOrEqual( + 0.001, + ) + expect(heightAt(withBreak, 12.25, 40)).toBe(5) + expect(heightAt(withBreak, 12.25, 40 + 1e-7)).toBe(5) + }) + + test('a nested terrace overrides the upper cliff region and keeps composed ground independent of IDs', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.5 }) + field.heights.fill(125) + for (const [openId, closedId] of [ + ['z', 'a'], + ['a', 'z'], + ] as const) { + const cliff = terrainBreak({ id: `terrain-break_${openId}` }) + const terrace = terrainBreak({ + id: `terrain-break_${closedId}`, + line: [ + [1, 2], + [3, 2], + [3, 6], + [1, 6], + [1, 2], + ], + kind: 'retaining', + left: 7, + right: 'ground', + }) + for (const edges of [ + [cliff, terrace], + [terrace, cliff], + ]) { + const { authority } = scene(field, edges) + expect(heightAt(authority, 2, 4)).toBe(7) + expect(heightAt(authority, 3 - 1e-7, 4)).toBe(7) + expect(heightAt(authority, 3 + 1e-7, 4)).toBe(5) + expect(heightAt(authority, 4 - 1e-7, 4)).toBe(5) + expect(heightAt(authority, 4 + 1e-7, 4)).toBe(2) + expect(terrainBreakFacts(terrace, authority)).toMatchObject({ + lengthM: 12, + left: { minM: 7, maxM: 7 }, + right: { minM: 5, maxM: 5 }, + dropMinM: 2, + dropMaxM: 2, + faceAreaM2: 24, + }) + } + } + }) + + test('an old no-break scene keeps its sampled field and serialized bytes unchanged', () => { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 0.95, origin: [0.13, 0.27] }) + for (let i = 0; i < field.heights.length; i++) field.heights[i] = ((i * 37) % 211) - 100 + const { site, nodes, authority } = scene(field, []) + const frozen = JSON.stringify(nodes) + expect(terrainBreaksOf(site, nodes)).toEqual([]) + for (const [x, z] of [ + [0.13, 0.27], + [2.31, 4.71], + [5.95, 2.77], + ] as const) { + expect(heightAt(authority, x, z)).toBe(heightAt(field, x, z)) + } + // B1's virtual authority uses 0.5 m derivative probes, not the native grid + // spacing. Interior probes avoid conflating continuation with dense clamping. + const reference: TerrainField = { + ...field, + spacing: 0.5, + readHeightAt: (x, z) => heightAt(field, x, z), + } + for (const [x, z] of [ + [2.31, 4.71], + [5.95, 2.77], + ] as const) { + expect(normalAt(authority, x, z)).toEqual(normalAt(reference, x, z)) + expect(slopeAt(authority, x, z)).toBe(slopeAt(reference, x, z)) + } + // The composed query authority is virtual; persistence belongs to Site. + expect(site.terrain).toEqual(encodeTerrainField(field)) + expect(JSON.stringify(nodes)).toBe(frozen) + }) +}) + +describe('terrain break measurable facts', () => { + test('measures a varying ground side instead of replacing its range by a midpoint sample', () => { + const field = createTerrainField({ cols: 17, rows: 17, spacing: 0.5 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) field.heights[row * field.cols + col] = row * 50 + // Ground is y=z. Along the 8 m edge, drop is 10-z, hence integral 48 m². + const edge = terrainBreak({ left: 10, right: 'ground' }) + const facts = terrainBreakFacts(edge, field) + expect(facts.lengthM).toBe(8) + expect(facts.left).toEqual({ minM: 10, maxM: 10 }) + expect(facts.right.minM).toBeCloseTo(0, 6) + expect(facts.right.maxM).toBeCloseTo(8, 6) + expect(facts.dropMinM).toBeCloseTo(2, 6) + expect(facts.dropMaxM).toBeCloseTo(10, 6) + expect(facts.faceAreaM2).toBeCloseTo(48, 6) + // Ground crosses the other side at the sampled midpoint z=4. Absolute + // exposed area is two 4×4 right triangles, not a cancelling signed integral. + const crossing = terrainBreakFacts(terrainBreak({ left: 4, right: 'ground' }), field) + expect(crossing.dropMinM).toBeCloseTo(0, 6) + expect(crossing.dropMaxM).toBeCloseTo(4, 6) + expect(crossing.faceAreaM2).toBeCloseTo(16, 6) + }) + + test('reports exact length, side ranges, drop magnitude and face area in either direction', () => { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + for (const [left, right] of [ + [5, 2], + [2, 5], + ] as const) { + const edge = terrainBreak({ + line: [ + [1, 0], + [4, 4], + ], + left, + right, + }) + expect(terrainBreakFacts(edge, field)).toMatchObject({ + lengthM: 5, + left: { minM: left, maxM: left }, + right: { minM: right, maxM: right }, + dropMinM: 3, + dropMaxM: 3, + faceAreaM2: 15, + }) + } + }) + + test('a closed retaining edge measures the whole perimeter, not its closing chord', () => { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + field.heights.fill(100) + const edge = terrainBreak({ line: ring, kind: 'retaining', left: 4, right: 'ground' }) + expect(terrainBreakFacts(edge, field)).toMatchObject({ + lengthM: 16, + left: { minM: 4, maxM: 4 }, + right: { minM: 1, maxM: 1 }, + dropMinM: 3, + dropMaxM: 3, + faceAreaM2: 48, + }) + }) +}) + +describe('terrain break ray intersections', () => { + test('vertical rays immediately beside a break hit the authored side, not an interpolated ramp', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.95 }) + const { authority } = scene(field) + for (const [x, y] of [ + [4 - 1e-7, 5], + [4, 5], + [4 + 1e-7, 2], + ] as const) { + const hit = raycastTerrain(authority, [x, 10, 3], [0, -1, 0]) + expect(hit).not.toBeNull() + expect(hit?.x).toBeCloseTo(x, 8) + expect(hit?.z).toBeCloseTo(3, 8) + expect(hit?.y).toBeCloseTo(y, 3) + expect(hit?.t).toBeCloseTo(10 - y, 3) + } + }) + + test('a horizontal ray hits the vertical face at its own height, with unnormalized ray parameter', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.95 }) + const { authority } = scene(field) + const hit = raycastTerrain(authority, [6, 3.5, 3], [-2, 0, 0]) + expect(hit).not.toBeNull() + expect(hit?.x).toBeCloseTo(4, 6) + expect(hit?.y).toBeCloseTo(3.5, 6) + expect(hit?.z).toBeCloseTo(3, 6) + expect(hit?.t).toBeCloseTo(1, 6) + }) + + test('a sub-grid closed terrace cannot be skipped by horizontal or oblique ray marching', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.95 }) + const edge = terrainBreak({ + kind: 'retaining', + line: [ + [4.13, 2], + [4.17, 2], + [4.17, 6], + [4.13, 6], + [4.13, 2], + ], + }) + const { authority } = scene(field, [edge]) + const horizontal = raycastTerrain(authority, [3, 3, 4], [2, 0, 0]) + expect(horizontal).not.toBeNull() + expect(horizontal?.x).toBeCloseTo(4.13, 6) + expect(horizontal?.y).toBeCloseTo(3, 6) + expect(horizontal?.z).toBeCloseTo(4, 6) + expect(horizontal?.t).toBeCloseTo(0.565, 6) + const oblique = raycastTerrain(authority, [3, 4, 3], [1, -0.25, 0.5]) + expect(oblique).not.toBeNull() + expect(oblique?.x).toBeCloseTo(4.13, 6) + expect(oblique?.y).toBeCloseTo(3.7175, 6) + expect(oblique?.z).toBeCloseTo(3.565, 6) + expect(oblique?.t).toBeCloseTo(1.13, 6) + // The nearest surface still wins if the ray meets the top before a face. + const top = raycastTerrain(authority, [4.15, 10, 3], [0, -1, 0]) + expect(top?.y).toBeCloseTo(5, 3) + expect(top?.t).toBeCloseTo(5, 3) + }) +}) + +describe('terrain break contour sampling', () => { + test('a raised ring contained in one contour cell cannot be crossed by the lower ground contour', () => { + const field = createTerrainField({ cols: 5, rows: 5, spacing: 0.5 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) field.heights[row * field.cols + col] = col * 50 + const edge = terrainBreak({ + line: [ + [0.2, 0.2], + [0.3, 0.2], + [0.3, 0.3], + [0.2, 0.3], + [0.2, 0.2], + ], + right: 'ground', + }) + const { authority } = scene(field, [edge]) + const contours = terrainContours(authority, 0.25, [ + [0, 0], + [2, 0], + [2, 2], + [0, 2], + ]).filter((contour) => contour.levelM === 0.25) + expect(contours.length).toBeGreaterThan(0) + expect(contours.some((contour) => contour.points.some((point) => point[1] >= 1.5))).toBe(true) + for (const contour of contours) { + for (const [x] of contour.points) expect(x).toBeCloseTo(0.25, 6) + for (let i = 1; i < contour.points.length; i++) { + const a = contour.points[i - 1] + const b = contour.points[i] + if (!a || !b) throw new Error('Expected consecutive contour points') + const minZ = Math.min(a[1], b[1]) + const maxZ = Math.max(a[1], b[1]) + expect(maxZ <= 0.2 || minZ >= 0.3).toBe(true) + } + } + }) + + test('two flat sides do not invent intermediate sloping contours across a vertical face', () => { + const field = createTerrainField({ cols: 20, rows: 20, spacing: 0.95 }) + const { authority } = scene(field) + const contours = terrainContours(authority, 1, [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ]) + // Neither open horizontal surface contains elevation 3 or 4. The vertical + // face is reported as a break, never as a marching-squares ramp contour. + expect(contours.filter((contour) => contour.levelM > 2 && contour.levelM < 5)).toEqual([]) + }) +}) diff --git a/packages/core/src/lib/terrain-breaks.ts b/packages/core/src/lib/terrain-breaks.ts new file mode 100644 index 0000000000..e710ebf512 --- /dev/null +++ b/packages/core/src/lib/terrain-breaks.ts @@ -0,0 +1,537 @@ +import { refuse } from '../agent-tools/refusal' +import type { TerrainBreakNode } from '../schema/nodes/terrain-break' +import { pointInPolygon, segmentsIntersect } from './polygon-relations' +import type { TerrainField } from './terrain-field' +import type { TerrainNodes, TerrainSite } from './terrain-tiles' + +export type TerrainBreakSide = 'left' | 'right' +type Point = [number, number] +type BreakShape = { line: Point[]; left: number | 'ground'; right: number | 'ground' } +const EPS = 1e-10 + +function cross(a: Point, b: Point, p: Point): number { + return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) +} + +export function terrainBreakIsClosed(boundary: Pick): boolean { + const a = boundary.line[0] + const b = boundary.line.at(-1) + return !!a && !!b && a[0] === b[0] && a[1] === b[1] +} + +const edgeCache = new WeakMap() + +/** A break's edges, built once per line: every height read tests them, and a line is immutable. */ +function edgesOf(boundary: Pick): [Point, Point][] { + const line = boundary.line + let edges = edgeCache.get(line) + if (!edges) { + edges = line.slice(1).map((to, i) => [line[i] as Point, to]) + edgeCache.set(line, edges) + } + return edges +} + +export function validateTerrainBreak(boundary: BreakShape): void { + const line = boundary.line + if ( + !Array.isArray(line) || + line.length < 2 || + line.length > 513 || + line.some((p) => !Array.isArray(p) || p.length !== 2 || !p.every(Number.isFinite)) + ) + refuse('invalid_input', 'A terrain break needs 2 to 513 finite [x,z] points.') + if (boundary.left === 'ground' && boundary.right === 'ground') + refuse('invalid_input', 'At least one terrain-break side must have a numeric height.') + if ( + [boundary.left, boundary.right].some((value) => value !== 'ground' && !Number.isFinite(value)) + ) + refuse('invalid_input', 'Terrain-break side heights must be finite numbers or ground.') + const edges = edgesOf(boundary) + if (edges.some(([a, b]) => !Number.isFinite(Math.hypot(b[0] - a[0], b[1] - a[1])))) + refuse('invalid_input', 'Terrain-break edge lengths must be finite.') + if (edges.some(([a, b]) => Math.hypot(b[0] - a[0], b[1] - a[1]) <= EPS)) + refuse('unsupported_geometry', 'A terrain break cannot have a collapsed edge.') + const first = line[0] as Point + const second = line[1] as Point + if (!terrainBreakIsClosed(boundary)) { + const dx = second[0] - first[0] + const dz = second[1] - first[1] + let previous = 0 + for (const point of line.slice(1)) { + const along = (point[0] - first[0]) * dx + (point[1] - first[1]) * dz + if (Math.abs(cross(first, second, point)) > EPS * Math.hypot(dx, dz) || along <= previous) + refuse( + 'unsupported_geometry', + 'Open terrain breaks must be straight, collinear and ordered.', + ) + previous = along + } + return + } + if (line.length < 4) + refuse('unsupported_geometry', 'A closed terrain break needs a simple convex CCW ring.') + for (const [a, b] of edges) { + if (line.some((point) => cross(a, b, point) < -EPS)) + refuse('unsupported_geometry', 'Closed terrain breaks must be convex and counterclockwise.') + } + if (!line.some((point) => cross(first, second, point) > EPS)) + refuse('unsupported_geometry', 'A closed terrain break must enclose area.') + for (let i = 0; i < edges.length; i++) { + for (let j = i + 2; j < edges.length; j++) { + if (i === 0 && j === edges.length - 1) continue + const a = edges[i] + const b = edges[j] + if (a && b && segmentsIntersect(a[0], a[1], b[0], b[1])) + refuse('unsupported_geometry', 'A terrain break cannot intersect itself.') + } + } +} + +function breaksCross(a: TerrainBreakNode, b: TerrainBreakNode): boolean { + const ae = edgesOf(a) + const be = edgesOf(b) + if (!terrainBreakIsClosed(a) && !terrainBreakIsClosed(b)) { + const [p, q] = ae[0] as [Point, Point] + const [r, s] = be[0] as [Point, Point] + const determinant = (q[0] - p[0]) * (s[1] - r[1]) - (q[1] - p[1]) * (s[0] - r[0]) + return Math.abs(determinant) > EPS || Math.abs(cross(p, q, r)) <= EPS + } + const open = !terrainBreakIsClosed(a) ? a : !terrainBreakIsClosed(b) ? b : null + if (open) { + const ring = open === a ? b : a + const [p, q] = edgesOf(open)[0] as [Point, Point] + const signs = ring.line.map((point) => cross(p, q, point)) + return Math.min(...signs) <= EPS && Math.max(...signs) >= -EPS + } + return ae.some(([p, q]) => be.some(([r, s]) => segmentsIntersect(p, q, r, s))) +} + +function ringArea(boundary: TerrainBreakNode): number { + return Math.abs(edgesOf(boundary).reduce((sum, [a, b]) => sum + a[0] * b[1] - b[0] * a[1], 0)) / 2 +} + +export function terrainLinePolygonCrossings(from: Point, to: Point, polygon: Point[]): number[] { + const dx = to[0] - from[0] + const dz = to[1] - from[1] + const length2 = dx * dx + dz * dz + const result: number[] = [] + for (let i = 0; i < polygon.length; i++) { + const a = polygon[i] + const b = polygon[(i + 1) % polygon.length] + if (!a || !b) refuse('invalid_polygon', 'The property has a missing corner.') + const ex = b[0] - a[0] + const ez = b[1] - a[1] + const ax = a[0] - from[0] + const az = a[1] - from[1] + const det = dx * ez - dz * ex + if (Math.abs(det) <= EPS) { + if (Math.abs(dx * az - dz * ax) <= EPS) + result.push( + (ax * dx + az * dz) / length2, + ((b[0] - from[0]) * dx + (b[1] - from[1]) * dz) / length2, + ) + continue + } + const u = (ax * dz - az * dx) / det + if (u >= -EPS && u <= 1 + EPS) result.push((ax * ez - az * ex) / det) + } + return result.sort((a, b) => a - b) +} + +export function validateTerrainBreakLotSpan(boundary: TerrainBreakNode, polygon: Point[]): void { + if (terrainBreakIsClosed(boundary)) return + if (polygon.length < 3 || polygon.some((point) => !point.every(Number.isFinite))) + refuse('invalid_polygon', 'The site needs a finite property polygon.') + const from = boundary.line[0] + const to = boundary.line.at(-1) + if (!from || !to) refuse('invalid_input', 'A terrain break needs two endpoints.') + const crossings = terrainLinePolygonCrossings(from, to, polygon) + if (crossings.some((t) => t < -EPS || t > 1 + EPS)) + refuse( + 'unsupported_geometry', + 'An open terrain break must cover the whole lot crossing; extend its endpoints before enlarging the property.', + ) +} + +export function terrainBreaksOf( + site: Pick | null | undefined, + nodes?: TerrainNodes, +): TerrainBreakNode[] { + if (!site?.id || !nodes) return [] + const breaks = Object.values(nodes).filter( + (node): node is TerrainBreakNode => node.type === 'terrain-break' && node.parentId === site.id, + ) + for (const boundary of breaks) validateTerrainBreak(boundary) + breaks.sort( + (a, b) => + Number(terrainBreakIsClosed(a)) - Number(terrainBreakIsClosed(b)) || + ringArea(b) - ringArea(a) || + (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), + ) + for (const [i, boundary] of breaks.entries()) { + if (breaks.slice(0, i).some((other) => breaksCross(boundary, other))) + refuse( + 'crossing_breaks', + 'Terrain breaks may not cross, touch or share a supporting open line.', + ) + } + if (breaks.filter((boundary) => !terrainBreakIsClosed(boundary)).length > 1) + refuse('unsupported_geometry', 'This increment supports at most one open terrain break.') + if ( + breaks.length > 1 && + breaks.some((boundary) => terrainBreakIsClosed(boundary) && boundary.right !== 'ground') + ) + refuse( + 'conflicting_breaks', + 'A closed break with a numeric exterior cannot be combined with other breaks.', + ) + return breaks +} + +export function terrainBreakSideAt( + boundary: Pick, + x: number, + z: number, +): TerrainBreakSide { + const edges = edgesOf(boundary) + if (terrainBreakIsClosed(boundary)) { + for (const [a, b] of edges) + if ((b[0] - a[0]) * (z - a[1]) - (b[1] - a[1]) * (x - a[0]) < -EPS) return 'right' + return 'left' + } + const [a, b] = edges[0] as [Point, Point] + return (b[0] - a[0]) * (z - a[1]) - (b[1] - a[1]) * (x - a[0]) >= -EPS ? 'left' : 'right' +} + +function planeHeight(points: Point[], heights: number[], x: number, z: number): number { + const [a, b, c] = points as [Point, Point, Point] + const [ha, hb, hc] = heights as [number, number, number] + const det = cross(a, b, c) + return ( + ha + + ((hb - ha) * ((x - a[0]) * (c[1] - a[1]) - (z - a[1]) * (c[0] - a[0])) + + (hc - ha) * ((b[0] - a[0]) * (z - a[1]) - (b[1] - a[1]) * (x - a[0]))) / + det + ) +} + +function triangleAvoidsBreaks(points: Point[], breaks: readonly TerrainBreakNode[]): boolean { + const first = points[0] + if (!first) return false + return breaks.every((boundary) => { + if ( + !terrainBreakIsClosed(boundary) || + terrainBreakSideAt(boundary, first[0], first[1]) === 'left' + ) + return true + const corner = boundary.line[0] + if (corner && pointInPolygon(corner, points)) return false + return points.every((a, i) => { + const b = points[(i + 1) % points.length] + return b && !edgesOf(boundary).some(([c, d]) => segmentsIntersect(a, b, c, d)) + }) + }) +} + +/** Extend the nearest wholly same-region source triangle, never a straddling triangle. */ +export function isolatedTerrainPlane( + field: TerrainField, + accepts: (x: number, z: number) => boolean, + x: number, + z: number, + sample?: (col: number, row: number) => number, + breaks: readonly TerrainBreakNode[] = [], +): ((x: number, z: number) => number) | null { + if (field.cols < 2 || field.rows < 2) return null + const read = sample ?? ((col, row) => (field.heights[row * field.cols + col] ?? 0) * field.step) + const u = Math.max(0, Math.min(field.cols - 1, (x - field.origin[0]) / field.spacing)) + const v = Math.max(0, Math.min(field.rows - 1, (z - field.origin[1]) / field.spacing)) + const col = Math.min(field.cols - 2, Math.floor(u)) + const row = Math.min(field.rows - 2, Math.floor(v)) + const point = (c: number, r: number): Point => [ + field.origin[0] + c * field.spacing, + field.origin[1] + r * field.spacing, + ] + const containing: [number, number][] = + u - col + v - row <= 1 + ? [ + [col, row], + [col + 1, row], + [col, row + 1], + ] + : [ + [col + 1, row + 1], + [col, row + 1], + [col + 1, row], + ] + const original = containing.map(([c, r]) => point(c, r)) + if (original.every(([px, pz]) => accepts(px, pz)) && triangleAvoidsBreaks(original, breaks)) { + const heights = containing.map(([c, r]) => read(c, r)) + return (px, pz) => planeHeight(original, heights, px, pz) + } + for (let radius = 0; radius <= 32; radius++) { + let best: { points: Point[]; indices: [number, number][]; distance: number } | undefined + for (let r = Math.max(0, row - radius); r <= Math.min(field.rows - 2, row + radius); r++) { + for (let c = Math.max(0, col - radius); c <= Math.min(field.cols - 2, col + radius); c++) { + if (radius > 0 && Math.max(Math.abs(c - col), Math.abs(r - row)) !== radius) continue + const triangles: [number, number][][] = [ + [ + [c, r], + [c + 1, r], + [c, r + 1], + ], + [ + [c + 1, r + 1], + [c, r + 1], + [c + 1, r], + ], + ] + for (const indices of triangles) { + const points = indices.map(([pc, pr]) => point(pc, pr)) + if (!points.every(([px, pz]) => accepts(px, pz)) || !triangleAvoidsBreaks(points, breaks)) + continue + const distance = points.reduce((sum, [px, pz]) => sum + (px - x) ** 2 + (pz - z) ** 2, 0) + if (!best || distance < best.distance) best = { points, indices, distance } + } + } + } + if (best) { + const points = best.points + const heights = best.indices.map(([c, r]) => read(c, r)) + return (px, pz) => planeHeight(points, heights, px, pz) + } + } + return null +} + +/** + * Which of a grid's triangles the search of `isolatedTerrainPlane` may take, for one region: + * triangle `2 * (row * (cols - 1) + col) + t` (t = 0 the lower, 1 the upper one of a cell) has + * all its corners accepted and avoids the breaks. It is a property of the grid, the breaks and + * the region alone, so one table serves every read in that region. + */ +export function isolatedTriangleFlags( + field: TerrainField, + accepts: (x: number, z: number) => boolean, + breaks: readonly TerrainBreakNode[], +): Uint8Array { + const cols = field.cols - 1 + const rows = field.rows - 1 + const flags = new Uint8Array(Math.max(0, cols * rows * 2)) + const accepted = new Uint8Array(field.cols * field.rows) + for (let r = 0; r < field.rows; r++) + for (let c = 0; c < field.cols; c++) + accepted[r * field.cols + c] = accepts( + field.origin[0] + c * field.spacing, + field.origin[1] + r * field.spacing, + ) + ? 1 + : 0 + const point = (c: number, r: number): Point => [ + field.origin[0] + c * field.spacing, + field.origin[1] + r * field.spacing, + ] + const at = (c: number, r: number) => accepted[r * field.cols + c] === 1 + for (let r = 0; r < rows; r++) + for (let c = 0; c < cols; c++) { + const base = 2 * (r * cols + c) + if (at(c, r) && at(c + 1, r) && at(c, r + 1)) { + if (triangleAvoidsBreaks([point(c, r), point(c + 1, r), point(c, r + 1)], breaks)) + flags[base] = 1 + } + if (at(c + 1, r + 1) && at(c, r + 1) && at(c + 1, r)) { + if (triangleAvoidsBreaks([point(c + 1, r + 1), point(c, r + 1), point(c + 1, r)], breaks)) + flags[base + 1] = 1 + } + } + return flags +} + +/** + * `isolatedTerrainPlane` read from a table of the triangles it may take (see + * `isolatedTriangleFlags`): the same triangle, in the same order of search and tie-break, so the + * same plane, without testing a triangle against the breaks again. + */ +export function isolatedTerrainPlaneFlagged( + field: TerrainField, + flags: Uint8Array, + x: number, + z: number, + sample?: (col: number, row: number) => number, +): ((x: number, z: number) => number) | null { + if (field.cols < 2 || field.rows < 2) return null + const read = sample ?? ((col, row) => (field.heights[row * field.cols + col] ?? 0) * field.step) + const u = Math.max(0, Math.min(field.cols - 1, (x - field.origin[0]) / field.spacing)) + const v = Math.max(0, Math.min(field.rows - 1, (z - field.origin[1]) / field.spacing)) + const col = Math.min(field.cols - 2, Math.floor(u)) + const row = Math.min(field.rows - 2, Math.floor(v)) + const cols = field.cols - 1 + const lower = u - col + v - row <= 1 + const point = (c: number, r: number): Point => [ + field.origin[0] + c * field.spacing, + field.origin[1] + r * field.spacing, + ] + const plane = (c: number, r: number, upper: boolean) => { + const indices: [number, number][] = upper + ? [ + [c + 1, r + 1], + [c, r + 1], + [c + 1, r], + ] + : [ + [c, r], + [c + 1, r], + [c, r + 1], + ] + const points = indices.map(([pc, pr]) => point(pc, pr)) + const heights = indices.map(([pc, pr]) => read(pc, pr)) + return (px: number, pz: number) => planeHeight(points, heights, px, pz) + } + if (flags[2 * (row * cols + col) + (lower ? 0 : 1)] === 1) return plane(col, row, !lower) + for (let radius = 0; radius <= 32; radius++) { + let best: { c: number; r: number; upper: boolean; distance: number } | undefined + const take = (c: number, r: number) => { + for (const upper of [false, true]) { + if (flags[2 * (r * cols + c) + (upper ? 1 : 0)] !== 1) continue + const corners: [number, number][] = upper + ? [ + [c + 1, r + 1], + [c, r + 1], + [c + 1, r], + ] + : [ + [c, r], + [c + 1, r], + [c, r + 1], + ] + let distance = 0 + for (const [pc, pr] of corners) { + const [px, pz] = point(pc, pr) + distance += (px - x) ** 2 + (pz - z) ** 2 + } + if (!best || distance < best.distance) best = { c, r, upper, distance } + } + } + // The cells at exactly this Chebyshev radius, in the order a row-by-row scan of the square + // meets them: the whole row at the top and bottom of the ring, its two ends between. + const rowLo = Math.max(0, row - radius) + const rowHi = Math.min(field.rows - 2, row + radius) + const colLo = Math.max(0, col - radius) + const colHi = Math.min(field.cols - 2, col + radius) + for (let r = rowLo; r <= rowHi; r++) { + if (radius === 0 || Math.abs(r - row) === radius) { + for (let c = colLo; c <= colHi; c++) take(c, r) + } else { + if (col - radius >= 0) take(col - radius, r) + if (col + radius <= field.cols - 2) take(col + radius, r) + } + } + if (best) return plane(best.c, best.r, best.upper) + } + return null +} + +export function isolatedTerrainHeight( + field: TerrainField, + accepts: (x: number, z: number) => boolean, + x: number, + z: number, + breaks: readonly TerrainBreakNode[] = [], + sample?: (col: number, row: number) => number, +): number { + const read = isolatedTerrainPlane(field, accepts, x, z, sample, breaks) + if (read) return read(x, z) + refuse( + 'unsupported_geometry', + 'Keep-ground needs a same-side source triangle within 32 grid cells; widen the ground region or give a numeric side.', + ) +} + +export function terrainBreakHeightAt( + field: TerrainField, + boundary: TerrainBreakNode, + side: TerrainBreakSide, + x: number, + z: number, +): number { + const value = boundary[side] + if (typeof value === 'number') return value + if (field.readHeightOnSide) return field.readHeightOnSide(boundary, side, x, z) + if (!field.heights.length) + refuse('unsupported_geometry', 'A virtual ground trace needs an explicit side-isolated reader.') + return isolatedTerrainHeight( + field, + (px, pz) => terrainBreakSideAt(boundary, px, pz) === side, + x, + z, + [boundary], + ) +} + +export function terrainBreakFacts(boundary: TerrainBreakNode, field: TerrainField) { + validateTerrainBreak(boundary) + const exact = typeof boundary.left === 'number' && typeof boundary.right === 'number' + let lengthM = 0 + let faceAreaM2 = 0 + let dropMinM = Number.POSITIVE_INFINITY + let dropMaxM = Number.NEGATIVE_INFINITY + const left = { minM: Number.POSITIVE_INFINITY, maxM: Number.NEGATIVE_INFINITY } + const right = { minM: Number.POSITIVE_INFINITY, maxM: Number.NEGATIVE_INFINITY } + let sampleCount = 0 + for (const [a, b] of edgesOf(boundary)) { + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + lengthM += length + const count = exact ? 1 : Math.max(1, Math.ceil(length / field.spacing)) + if (sampleCount + count + 1 > 20_000) + refuse('sampling_limit', 'Terrain-break facts exceed 20,000 samples.') + let previous = 0 + for (let i = 0; i <= count; i++) { + const x = a[0] + (b[0] - a[0]) * (i / count) + const z = a[1] + (b[1] - a[1]) * (i / count) + const lh = terrainBreakHeightAt(field, boundary, 'left', x, z) + const rh = terrainBreakHeightAt(field, boundary, 'right', x, z) + if (!Number.isFinite(lh) || !Number.isFinite(rh)) + refuse('no_terrain', 'Terrain-break traces must be finite.') + left.minM = Math.min(left.minM, lh) + left.maxM = Math.max(left.maxM, lh) + right.minM = Math.min(right.minM, rh) + right.maxM = Math.max(right.maxM, rh) + const drop = lh - rh + dropMinM = Math.min(dropMinM, Math.abs(drop)) + dropMaxM = Math.max(dropMaxM, Math.abs(drop)) + if (i > 0) { + const span = length / count + if (previous * drop < 0) dropMinM = 0 + faceAreaM2 += + previous * drop < 0 + ? (span * (previous * previous + drop * drop)) / + (2 * (Math.abs(previous) + Math.abs(drop))) + : (span * (Math.abs(previous) + Math.abs(drop))) / 2 + } + previous = drop + sampleCount++ + } + } + return { + breakId: boundary.id, + line: boundary.line, + kind: boundary.kind, + lengthM, + left, + right, + dropMinM, + dropMaxM, + faceAreaM2, + ...(!exact + ? { + sampling: { + approximate: true as const, + method: 'side_isolated_trace_trapezoids', + spacingM: field.spacing, + sampleCount, + }, + } + : {}), + } +} diff --git a/packages/core/src/lib/terrain-brush.test.ts b/packages/core/src/lib/terrain-brush.test.ts index 22f284cbc1..9bf5274bc9 100644 --- a/packages/core/src/lib/terrain-brush.test.ts +++ b/packages/core/src/lib/terrain-brush.test.ts @@ -4,6 +4,7 @@ import { beginStroke, DEFAULT_BRUSH_SETTINGS, detachStrokeAnchor, + diffuseHeights, highestOver, MIN_BRUSH_RADIUS_IN_SPACINGS, maxCoverage, @@ -363,6 +364,32 @@ describe('smooth', () => { }) }) +describe('diffuseHeights', () => { + test('is the target a smooth dab reaches at its centre', () => { + // The exported diffusion is what both the brush and shape_site_terrain's + // smooth verb lerp toward; at a dab's centre the coverage is full, so the + // stroke lands exactly on it. + const base = field() + const heights = base.heights.slice() + const centre = 16 * 33 + 16 + heights[centre] = quantize(base, 2) + const spiked = { ...base, heights } + const diffused = diffuseHeights(spiked) + const smoothed = stroke( + spiked, + { verb: 'smooth', settings: { radius: 3, strength: 1, falloff: 0.2 } }, + [[0, 0]], + ) + expect(smoothed.heights[centre]).toBe(diffused[centre]) + expect(diffused[centre]).toBeLessThan(heights[centre] ?? 0) + }) + + test('leaves flat ground untouched', () => { + const flat = field() + expect(Array.from(diffuseHeights(flat))).toEqual(Array.from(flat.heights)) + }) +}) + describe('field bounds', () => { test('a stroke entirely off the field returns no patch', () => { const active = beginStroke({ verb: 'raise', field: field(), settings: { radius: 1 } }) diff --git a/packages/core/src/lib/terrain-brush.ts b/packages/core/src/lib/terrain-brush.ts index 5c2e4c6e09..ea94cbe17d 100644 --- a/packages/core/src/lib/terrain-brush.ts +++ b/packages/core/src/lib/terrain-brush.ts @@ -286,8 +286,18 @@ function resolveSample(stroke: TerrainStroke, index: number, col: number, row: n * that is 4 225 entries at the default 65² size. */ function smoothedSnapshot(stroke: TerrainStroke): Int16Array { - if (stroke.smoothed) return stroke.smoothed - const field = stroke.snapshot + if (!stroke.smoothed) stroke.smoothed = diffuseHeights(stroke.snapshot) + return stroke.smoothed +} + +/** + * The whole field diffused in quantized units: `SMOOTH_ITERATIONS` Jacobi + * passes at λ = `SMOOTH_LAMBDA` on a 4-neighbour stencil, borders clamped. + * The one definition of "smoothed ground" — the brush's smooth dabs lerp + * toward it per stroke, and `shape_site_terrain`'s smooth verb lerps the + * samples in its area toward the same target, so the two cannot drift apart. + */ +export function diffuseHeights(field: TerrainField): Int16Array { let current = new Int16Array(field.heights) let next = new Int16Array(current.length) for (let iteration = 0; iteration < SMOOTH_ITERATIONS; iteration++) { @@ -308,7 +318,6 @@ function smoothedSnapshot(stroke: TerrainStroke): Int16Array { current = next next = swap } - stroke.smoothed = current return current } diff --git a/packages/core/src/lib/terrain-codec.ts b/packages/core/src/lib/terrain-codec.ts index 39fc209a4d..9bde2a645f 100644 --- a/packages/core/src/lib/terrain-codec.ts +++ b/packages/core/src/lib/terrain-codec.ts @@ -136,6 +136,7 @@ export function decodeHeightPatch(value: unknown): HeightPatch | null { } export function encodeTerrainField(field: TerrainField): TerrainData { + if (field.readHeightAt) throw new Error('Virtual terrain cannot be persisted as a legacy field') return { type: 'heightfield', origin: [field.origin[0], field.origin[1]], @@ -201,6 +202,7 @@ export function decodeTerrainField(data: unknown): TerrainField | null { * undefined` instead of carrying ~11 KB of base64 zeroes in every saved scene. */ export function isDatumField(field: TerrainField): boolean { + if (field.readHeightAt) return false for (let i = 0; i < field.heights.length; i++) { if (field.heights[i] !== 0) return false } diff --git a/packages/core/src/lib/terrain-contours.test.ts b/packages/core/src/lib/terrain-contours.test.ts new file mode 100644 index 0000000000..f0c5ead0ac --- /dev/null +++ b/packages/core/src/lib/terrain-contours.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, test } from 'bun:test' +import { createTerrainField, type TerrainField, terrainContours } from '@pascal-app/core' + +describe('terrain contour sampling', () => { + test('a huge virtual plane keeps analytic contours with bounded authority reads', () => { + let reads = 0 + const field: TerrainField = { + origin: [0, 0], + cols: 20_001, + rows: 20_001, + spacing: 0.5, + step: 0.01, + heights: new Int16Array(0), + heightBounds: [0, 1], + readHeightAt: (x) => { + reads++ + // A safe failure instead of letting the former full-union scan run 400M times. + if (reads > 1_000_000) throw new Error('Unbounded virtual contour sampling') + return x / 10_000 + }, + } + const contours = terrainContours(field, 0.5, [ + [0, 0], + [10_000, 0], + [10_000, 10_000], + [0, 10_000], + ]) + // Three elevation levels on at most 256² cells, plus the range scan, fit + // below 1M reads; a flat/empty shortcut cannot pass the analytical line check. + expect(reads).toBeLessThanOrEqual(1_000_000) + const middle = contours.filter((line) => line.levelM === 0.5) + expect(middle.length).toBeGreaterThan(0) + for (const line of middle) { + expect(line.points.length).toBeGreaterThanOrEqual(2) + for (const [x, z] of line.points) { + expect(x).toBeCloseTo(5000, 6) + expect(Number.isFinite(z)).toBe(true) + } + } + }) + + test('small dense fields retain their known one-metre contours', () => { + const field = createTerrainField({ cols: 5, rows: 5, spacing: 1 }) + for (let row = 0; row < 5; row++) + for (let col = 0; col < 5; col++) field.heights[row * 5 + col] = col * 100 + const contours = terrainContours(field, 1, [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ]) + for (const level of [1, 2, 3]) { + const lines = contours.filter((line) => line.levelM === level) + expect(lines.length).toBeGreaterThan(0) + for (const line of lines) for (const [x] of line.points) expect(x).toBe(level) + } + }) +}) diff --git a/packages/core/src/lib/terrain-contours.ts b/packages/core/src/lib/terrain-contours.ts index 7886135384..2fd1cd928d 100644 --- a/packages/core/src/lib/terrain-contours.ts +++ b/packages/core/src/lib/terrain-contours.ts @@ -12,7 +12,9 @@ * * Drawn on the site plan at a user-selectable contour interval (6", 12", …). */ -import { heightAtSample, type TerrainField } from './terrain-field' +import { segmentsIntersect } from './polygon-relations' +import { terrainBreakIsClosed, terrainBreakSideAt } from './terrain-breaks' +import { heightAt, heightAtSample, type TerrainField } from './terrain-field' export type Pt = readonly [number, number] @@ -52,6 +54,37 @@ function cross( return [ax + (bx - ax) * t, az + (bz - az) * t] } +function cellHasTerrainBreak( + field: TerrainField, + x0: number, + z0: number, + x1: number, + z1: number, +): boolean { + const corners: [number, number][] = [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], + ] + return (field.terrainBreaks ?? []).some((terrainBreak) => { + const side = terrainBreakSideAt(terrainBreak, x0, z0) + if (corners.some(([x, z]) => terrainBreakSideAt(terrainBreak, x, z) !== side)) return true + if (!terrainBreakIsClosed(terrainBreak)) return false + if (terrainBreak.line.some(([x, z]) => x >= x0 && x <= x1 && z >= z0 && z <= z1)) return true + return terrainBreak.line.slice(1).some((to, index) => { + const from = terrainBreak.line[index] + return ( + from && + corners.some((start, corner) => { + const end = corners[(corner + 1) % corners.length] + return end && segmentsIntersect(from, to, start, end) + }) + ) + }) + }) +} + /** The segments of one level across the field (marching squares, 16 cases). */ function levelSegments(field: TerrainField, level: number, lot: readonly Pt[]): Seg[] { const out: Seg[] = [] @@ -59,6 +92,11 @@ function levelSegments(field: TerrainField, level: number, lot: readonly Pt[]): const [ox, oz] = field.origin for (let row = 0; row + 1 < rows; row++) { for (let col = 0; col + 1 < cols; col++) { + const x0 = ox + col * spacing + const x1 = x0 + spacing + const z0 = oz + row * spacing + const z1 = z0 + spacing + if (field.terrainBreaks?.length && cellHasTerrainBreak(field, x0, z0, x1, z1)) continue // corners: a = (col,row) b = (col+1,row) c = (col+1,row+1) d = (col,row+1) const ha = heightAtSample(field, col, row) const hb = heightAtSample(field, col + 1, row) @@ -70,10 +108,6 @@ function levelSegments(field: TerrainField, level: number, lot: readonly Pt[]): (hc >= level ? 2 : 0) | (hd >= level ? 1 : 0) if (code === 0 || code === 15) continue - const x0 = ox + col * spacing - const x1 = x0 + spacing - const z0 = oz + row * spacing - const z1 = z0 + spacing const top = () => cross(x0, z0, ha, x1, z0, hb, level) const right = () => cross(x1, z0, hb, x1, z1, hc, level) const bottom = () => cross(x0, z1, hd, x1, z1, hc, level) @@ -182,7 +216,8 @@ function chain(segments: Seg[]): Pt[][] { /** * The contours of a field at `intervalM`, clipped to the lot. Every fifth - * level (counted from zero) is an index contour. + * level (counted from zero) is an index contour. Large virtual extents use a + * coarser view grid, never more than 256² cells; stored terrain is not resampled. */ export function terrainContours( field: TerrainField, @@ -190,6 +225,7 @@ export function terrainContours( lot: readonly Pt[], ): Contour[] { if (!(intervalM > 0)) return [] + field = contourSampleField(field) let lo = Number.POSITIVE_INFINITY let hi = Number.NEGATIVE_INFINITY for (let row = 0; row < field.rows; row++) { @@ -215,3 +251,31 @@ export function terrainContours( } return out } + +function contourSampleField(field: TerrainField): TerrainField { + const maxCells = 256 * 256 + const cellsX = field.cols - 1 + const cellsZ = field.rows - 1 + if (!field.readHeightAt) return field + let stride = Math.max( + 1, + Math.ceil(Math.sqrt((cellsX * cellsZ) / maxCells)), + Math.ceil(Math.max(cellsX, cellsZ) / maxCells), + ) + while (Math.ceil(cellsX / stride) * Math.ceil(cellsZ / stride) > maxCells) stride *= 2 + const samples = new Map() + return { + ...field, + spacing: field.spacing * stride, + cols: Math.ceil(cellsX / stride) + 1, + rows: Math.ceil(cellsZ / stride) + 1, + readHeightAt: (x, z) => { + const key = `${x},${z}` + const cached = samples.get(key) + if (cached !== undefined) return cached + const height = heightAt(field, x, z) + samples.set(key, height) + return height + }, + } +} diff --git a/packages/core/src/lib/terrain-field-extent.test.ts b/packages/core/src/lib/terrain-field-extent.test.ts new file mode 100644 index 0000000000..b8395d4d91 --- /dev/null +++ b/packages/core/src/lib/terrain-field-extent.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, test } from 'bun:test' +import type { SiteNode } from '../schema' +import { DEFAULT_TERRAIN_SPACING } from './terrain-field' +import { fieldExtentForSite } from './terrain-field-extent' + +function site(points: Array<[number, number]>): SiteNode { + return { + id: 'site_1', + type: 'site', + children: [], + polygon: { type: 'polygon', points }, + } as unknown as SiteNode +} + +describe('fieldExtentForSite', () => { + test('covers the whole polygon with padding to spare', () => { + const extent = fieldExtentForSite( + site([ + [-10, -10], + [10, -10], + [10, 10], + [-10, 10], + ]), + ) + const maxX = extent.origin[0] + (extent.cols - 1) * extent.spacing + const maxZ = extent.origin[1] + (extent.rows - 1) * extent.spacing + + // Strictly outside the lot on all four sides: the field must not end at the + // property line, or the terrain mesh stops exactly where the boundary is + // drawn and leaves a visible cliff. + expect(extent.origin[0]).toBeLessThan(-10) + expect(extent.origin[1]).toBeLessThan(-10) + expect(maxX).toBeGreaterThan(10) + expect(maxZ).toBeGreaterThan(10) + }) + + test('is square and 2ⁿ+1 so a future LOD halving lands on real samples', () => { + for (const half of [4, 12, 30, 80]) { + const extent = fieldExtentForSite( + site([ + [-half, -half], + [half, -half], + [half, half], + [-half, half], + ]), + ) + expect(extent.cols).toBe(extent.rows) + expect([33, 65, 129, 257]).toContain(extent.cols) + } + }) + + test('centres on the lot even when the lot is off-origin', () => { + const extent = fieldExtentForSite( + site([ + [100, 40], + [120, 40], + [120, 60], + [100, 60], + ]), + ) + const centerX = extent.origin[0] + ((extent.cols - 1) / 2) * extent.spacing + const centerZ = extent.origin[1] + ((extent.rows - 1) / 2) * extent.spacing + expect(centerX).toBeCloseTo(110, 6) + expect(centerZ).toBeCloseTo(50, 6) + }) + + test('holds the default spacing while the lot fits in 257 samples', () => { + const extent = fieldExtentForSite( + site([ + [-20, -20], + [20, -20], + [20, 20], + [-20, 20], + ]), + ) + expect(extent.spacing).toBeCloseTo(DEFAULT_TERRAIN_SPACING, 6) + }) + + test('stretches spacing rather than stopping short on a huge lot', () => { + // A 400 m lot needs 801 samples at 0.5 m. Capping the sample count and + // coarsening is the right trade: coarse ground everywhere beats fine ground + // that ends mid-lot. + const extent = fieldExtentForSite( + site([ + [-200, -200], + [200, -200], + [200, 200], + [-200, 200], + ]), + ) + expect(extent.cols).toBe(257) + expect(extent.spacing).toBeGreaterThan(DEFAULT_TERRAIN_SPACING) + const maxX = extent.origin[0] + (extent.cols - 1) * extent.spacing + expect(maxX).toBeGreaterThan(200) + }) + + test('a degenerate polygon still yields a usable field', () => { + for (const points of [[], [[0, 0]] as Array<[number, number]>]) { + const extent = fieldExtentForSite(site(points as Array<[number, number]>)) + expect(extent.cols).toBe(65) + expect(extent.spacing).toBeCloseTo(DEFAULT_TERRAIN_SPACING, 6) + } + }) + + test('a null site does not throw', () => { + expect(fieldExtentForSite(null).cols).toBe(65) + expect(fieldExtentForSite(undefined).cols).toBe(65) + }) +}) diff --git a/packages/core/src/lib/terrain-field-extent.ts b/packages/core/src/lib/terrain-field-extent.ts new file mode 100644 index 0000000000..e41ca02843 --- /dev/null +++ b/packages/core/src/lib/terrain-field-extent.ts @@ -0,0 +1,65 @@ +import type { SiteNode } from '../schema/nodes/site' +import { DEFAULT_TERRAIN_SPACING } from './terrain-field' + +/** + * Field sizes we allow, all `2ⁿ+1` so a future LOD halving lands on existing + * samples instead of interpolating a seam. + */ +const FIELD_SIZES = [33, 65, 129, 257] as const + +/** + * Sample count a fresh field gets, chosen to cover the site polygon at roughly + * `DEFAULT_TERRAIN_SPACING` and never exceeding 257² (66 049 samples — about + * four furnished rooms' worth of vertices). + * + * Sizing from the polygon rather than a fixed extent matters because the extent + * is baked at creation: the field is the ground for the whole session, and a + * grid that stops short of the lot line leaves a visible cliff where the terrain + * mesh ends and the flat fill resumes. Padding by one spacing keeps the boundary + * line itself on interpolated ground rather than on the clamped edge row. + */ +export function fieldExtentForSite(site: Pick | null | undefined): { + origin: [number, number] + cols: number + rows: number + spacing: number +} { + const points = site?.polygon?.points ?? [] + if (points.length < 3) { + const half = ((65 - 1) / 2) * DEFAULT_TERRAIN_SPACING + return { origin: [-half, -half], cols: 65, rows: 65, spacing: DEFAULT_TERRAIN_SPACING } + } + + let minX = Number.POSITIVE_INFINITY + let minZ = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let maxZ = Number.NEGATIVE_INFINITY + for (const [x, z] of points) { + if (x < minX) minX = x + if (x > maxX) maxX = x + if (z < minZ) minZ = z + if (z > maxZ) maxZ = z + } + + // The grid is square: a rectangular field would need two spacings or two + // sample counts, and both make every downstream index calculation branchier + // for no visual gain. + const pad = DEFAULT_TERRAIN_SPACING * 2 + const span = Math.max(maxX - minX, maxZ - minZ) + pad * 2 + const centerX = (minX + maxX) / 2 + const centerZ = (minZ + maxZ) / 2 + + const wanted = Math.ceil(span / DEFAULT_TERRAIN_SPACING) + 1 + const size = FIELD_SIZES.find((candidate) => candidate >= wanted) ?? FIELD_SIZES.at(-1)! + // Spacing stretches when the lot is bigger than 257 samples can cover at the + // default: coarser ground beats ground that stops at the property line. + const spacing = Math.max(DEFAULT_TERRAIN_SPACING, span / (size - 1)) + const half = ((size - 1) / 2) * spacing + + return { + origin: [centerX - half, centerZ - half], + cols: size, + rows: size, + spacing, + } +} diff --git a/packages/core/src/lib/terrain-field.ts b/packages/core/src/lib/terrain-field.ts index edd8dc3c05..512773ca02 100644 --- a/packages/core/src/lib/terrain-field.ts +++ b/packages/core/src/lib/terrain-field.ts @@ -1,10 +1,12 @@ +import type { TerrainBreakNode } from '../schema/nodes/terrain-break' +import { type TerrainBreakSide, terrainBreakHeightAt, terrainBreakIsClosed } from './terrain-breaks' + /** - * The terrain heightfield: one regular grid of quantized heights, and the - * only place terrain geometry is read from. + * Terrain read primitives for authored quantized grids and sparse virtual ground. * * Two invariants carry the whole design: * - * 1. **Quantized to `Int16` multiples of `step`.** Heights are integers, so + * 1. **Authored heights are `Int16` multiples of `step`.** Heights are integers, so * "is this ground flat?" is exact integer equality rather than an epsilon * comparison. That is what lets the support election treat terrain as one * discrete candidate (see `slab-support.ts`) instead of a float soup that @@ -38,8 +40,28 @@ export type TerrainField = { readonly rows: number /** Metres per `heights` unit — the quantization ladder. */ readonly step: number - /** Row-major quantized heights, length `cols * rows`. */ + /** Dense row-major samples; sparse virtual fields may leave this buffer empty. */ readonly heights: Int16Array + /** Virtual authority; its box may span sparse terrain without a dense buffer. */ + readonly readHeightAt?: (x: number, z: number) => number + readonly terrainBreaks?: readonly TerrainBreakNode[] + readonly readHeightOnSide?: ( + boundary: TerrainBreakNode, + side: TerrainBreakSide, + x: number, + z: number, + ) => number + readonly readHeightInRegion?: (originX: number, originZ: number, x: number, z: number) => number + /** + * The stored samples as written, where `readHeightAt` reads the ground beside a graded ramp as + * it was before the grading. A tile write seeds from this, so a write that touches a tile + * never puts the natural ground back under a corridor's edge samples. + */ + readonly readStoredHeightAt?: (x: number, z: number) => number + /** Conservative vertical bounds, including the virtual continuation. */ + readonly heightBounds?: readonly [number, number] + /** Horizontal far-context plane inferred from the frozen legacy base. */ + readonly contextHeight?: number } /** A rectangular sub-block of samples — the unit of every terrain write. */ @@ -81,23 +103,30 @@ export function quantize(field: TerrainField, metres: number): number { return Math.max(-32768, Math.min(32767, raw)) } -/** Sample [c,r] in metres. Out-of-range indices clamp to the edge, so a - * consumer reading just past the boundary gets the border height rather than - * a hole — the same clamp-don't-ask rule the vertical model uses. */ +/** Sample [c,r] in metres. Dense grids clamp at their border; virtual grids + * delegate even out-of-box samples to the continuous authority. */ export function heightAtSample(field: TerrainField, col: number, row: number): number { + if (field.readHeightAt) { + return field.readHeightAt( + field.origin[0] + Math.trunc(col) * field.spacing, + field.origin[1] + Math.trunc(row) * field.spacing, + ) + } const c = Math.max(0, Math.min(field.cols - 1, Math.trunc(col))) const r = Math.max(0, Math.min(field.rows - 1, Math.trunc(row))) return (field.heights[r * field.cols + c] ?? 0) * field.step } /** - * The ground height in metres at a world XZ, on the rendered triangle plane. + * The ground height in metres at a world XZ. * * This is the single read authority named in the plan. Each cell uses the same - * `(c+1,r)`–`(c,r+1)` diagonal as `nodes/src/site/terrain-geometry.ts`, so - * placement, picking, collision, draping, and pixels all answer the same height. + * `(c+1,r)`–`(c,r+1)` diagonal as authored terrain meshes. A virtual field can + * also provide analytic continuation, which presentation meshes approximate + * by sampling this same authority. */ export function heightAt(field: TerrainField, x: number, z: number): number { + if (field.readHeightAt) return field.readHeightAt(x, z) if (field.cols < 2 || field.rows < 2) return heightAtSample(field, 0, 0) const u = Math.min(field.cols - 1, Math.max(0, (x - field.origin[0]) / field.spacing)) @@ -116,10 +145,15 @@ export function heightAt(field: TerrainField, x: number, z: number): number { return h11 + (h01 - h11) * (1 - tc) + (h10 - h11) * (1 - tr) } +/** The ground a tile write starts from: the stored samples, not the ground beside a cut. */ +export function storedHeightAt(field: TerrainField, x: number, z: number): number { + return field.readStoredHeightAt ? field.readStoredHeightAt(x, z) : heightAt(field, x, z) +} + /** * Compatibility name for callers that explicitly describe a rendered surface. - * There is intentionally no second interpolation model: `heightAt` is the - * rendered triangle plane. + * There is intentionally no second read model: this delegates to the authored + * triangle surface or virtual continuation supplied by `heightAt`. */ export function surfaceHeightAt(field: TerrainField, x: number, z: number): number { return heightAt(field, x, z) @@ -132,10 +166,19 @@ export function surfaceHeightAt(field: TerrainField, x: number, z: number): numb * authority, so the normal is a property of the *field* and stays continuous * across triangle boundaries. Returns a unit vector, +Y up. */ -export function normalAt(field: TerrainField, x: number, z: number): [number, number, number] { +function gradientAt(field: TerrainField, x: number, z: number): [number, number] { const d = field.spacing - const dhdx = (heightAt(field, x + d, z) - heightAt(field, x - d, z)) / (2 * d) - const dhdz = (heightAt(field, x, z + d) - heightAt(field, x, z - d)) / (2 * d) + const regionalRead = field.readHeightInRegion + const read = regionalRead + ? (px: number, pz: number) => regionalRead(x, z, px, pz) + : (px: number, pz: number) => heightAt(field, px, pz) + const dhdx = (read(x + d, z) - read(x - d, z)) / (2 * d) + const dhdz = (read(x, z + d) - read(x, z - d)) / (2 * d) + return [dhdx, dhdz] +} + +export function normalAt(field: TerrainField, x: number, z: number): [number, number, number] { + const [dhdx, dhdz] = gradientAt(field, x, z) // Gradient (dh/dx, dh/dz) → normal (-dh/dx, 1, -dh/dz), normalized. const len = Math.hypot(dhdx, 1, dhdz) return [-dhdx / len, 1 / len, -dhdz / len] @@ -143,21 +186,102 @@ export function normalAt(field: TerrainField, x: number, z: number): [number, nu /** Slope in radians from horizontal at a world XZ. 0 = flat, π/2 = vertical. */ export function slopeAt(field: TerrainField, x: number, z: number): number { - const d = field.spacing - const dhdx = (heightAt(field, x + d, z) - heightAt(field, x - d, z)) / (2 * d) - const dhdz = (heightAt(field, x, z + d) - heightAt(field, x, z - d)) / (2 * d) + const [dhdx, dhdz] = gradientAt(field, x, z) return Math.atan(Math.hypot(dhdx, dhdz)) } +type TerrainRect = { minX: number; minZ: number; maxX: number; maxZ: number } +type TerrainPoint = [number, number] + +function clipBreakToRect( + from: TerrainPoint, + to: TerrainPoint, + rect: TerrainRect, + infinite: boolean, +): [TerrainPoint, TerrainPoint] | null { + let lo = infinite ? Number.NEGATIVE_INFINITY : 0 + let hi = infinite ? Number.POSITIVE_INFINITY : 1 + const dx = to[0] - from[0] + const dz = to[1] - from[1] + const axes: [number, number, number, number][] = [ + [from[0], dx, rect.minX, rect.maxX], + [from[1], dz, rect.minZ, rect.maxZ], + ] + for (const [start, delta, min, max] of axes) { + if (delta === 0) { + if (start <= min || start >= max) return null + continue + } + const a = (min - start) / delta + const b = (max - start) / delta + lo = Math.max(lo, Math.min(a, b)) + hi = Math.min(hi, Math.max(a, b)) + if (lo >= hi) return null + } + return [ + [from[0] + lo * dx, from[1] + lo * dz], + [from[0] + hi * dx, from[1] + hi * dz], + ] +} + +function breakTracesAreLevel( + field: TerrainField, + boundary: TerrainBreakNode, + rect: TerrainRect, + level: number, +): boolean { + const infinite = !terrainBreakIsClosed(boundary) + for (let i = 1; i < boundary.line.length; i++) { + const from = boundary.line[i - 1] + const to = boundary.line[i] + if (!from || !to || (infinite && i > 1)) continue + const span = clipBreakToRect(from, to, rect, infinite) + if (!span) continue + const [a, b] = span + const count = Math.max(2, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / field.spacing)) + for (let j = 0; j <= count; j++) { + const x = a[0] + (b[0] - a[0]) * (j / count) + const z = a[1] + (b[1] - a[1]) * (j / count) + if ( + terrainBreakHeightAt(field, boundary, 'left', x, z) !== level || + terrainBreakHeightAt(field, boundary, 'right', x, z) !== level + ) + return false + } + } + return true +} + +function isFlatWithBreaks(field: TerrainField, rect: TerrainRect): boolean { + const { minX, minZ, maxX, maxZ } = rect + if (maxX < minX || maxZ < minZ) return true + const level = heightAt(field, minX, minZ) + if ( + ![ + [maxX, minZ], + [minX, maxZ], + [maxX, maxZ], + ].every(([x, z]) => x !== undefined && z !== undefined && heightAt(field, x, z) === level) + ) + return false + if (!field.terrainBreaks?.every((boundary) => breakTracesAreLevel(field, boundary, rect, level))) + return false + const c0 = Math.ceil((minX - field.origin[0]) / field.spacing) + const r0 = Math.ceil((minZ - field.origin[1]) / field.spacing) + const c1 = Math.floor((maxX - field.origin[0]) / field.spacing) + const r1 = Math.floor((maxZ - field.origin[1]) / field.spacing) + for (let r = r0; r <= r1; r++) + for (let c = c0; c <= c1; c++) if (heightAtSample(field, c, r) !== level) return false + return true +} + /** - * True when every sample under the world-XZ rect is at the identical quantized + * True when every authority sample under the world-XZ rect has the identical * height — the placement predicate for kinds that need level ground. * - * Exact integer equality, which is only meaningful because heights are - * quantized (invariant 1). A float field would need a tolerance here, and that - * tolerance would then have to agree with the support election's own epsilon — - * two tunables that could drift apart. Instead there is one ladder and no - * tolerance. + * Authored grids compare heights on their quantization ladder. Analytic + * continuation uses the same exact equality, so a constant context plane is + * flat while any measured variation remains visible to the predicate. */ export function isFlatOver( field: TerrainField, @@ -166,17 +290,25 @@ export function isFlatOver( maxX: number, maxZ: number, ): boolean { - const c0 = Math.max(0, Math.floor((minX - field.origin[0]) / field.spacing)) - const r0 = Math.max(0, Math.floor((minZ - field.origin[1]) / field.spacing)) - const c1 = Math.min(field.cols - 1, Math.ceil((maxX - field.origin[0]) / field.spacing)) - const r1 = Math.min(field.rows - 1, Math.ceil((maxZ - field.origin[1]) / field.spacing)) + if (field.terrainBreaks?.length) return isFlatWithBreaks(field, { minX, minZ, maxX, maxZ }) + const c0 = field.readHeightAt + ? Math.floor((minX - field.origin[0]) / field.spacing) + : Math.max(0, Math.floor((minX - field.origin[0]) / field.spacing)) + const r0 = field.readHeightAt + ? Math.floor((minZ - field.origin[1]) / field.spacing) + : Math.max(0, Math.floor((minZ - field.origin[1]) / field.spacing)) + const c1 = field.readHeightAt + ? Math.ceil((maxX - field.origin[0]) / field.spacing) + : Math.min(field.cols - 1, Math.ceil((maxX - field.origin[0]) / field.spacing)) + const r1 = field.readHeightAt + ? Math.ceil((maxZ - field.origin[1]) / field.spacing) + : Math.min(field.rows - 1, Math.ceil((maxZ - field.origin[1]) / field.spacing)) if (c1 < c0 || r1 < r0) return true - const first = field.heights[r0 * field.cols + c0] ?? 0 + const first = heightAtSample(field, c0, r0) for (let r = r0; r <= r1; r++) { - const rowBase = r * field.cols for (let c = c0; c <= c1; c++) { - if ((field.heights[rowBase + c] ?? 0) !== first) return false + if (heightAtSample(field, c, r) !== first) return false } } return true @@ -192,6 +324,7 @@ export function isFlatOver( * overhang the site, and clipping is the sane response. */ export function applyHeightPatch(field: TerrainField, patch: HeightPatch): TerrainField { + if (field.readHeightAt) throw new Error('Materialize a bounded terrain edit field before writing') const heights = new Int16Array(field.heights) for (let pr = 0; pr < patch.rows; pr++) { const row = patch.row0 + pr diff --git a/packages/core/src/lib/terrain-hollows.ts b/packages/core/src/lib/terrain-hollows.ts new file mode 100644 index 0000000000..8aaab78610 --- /dev/null +++ b/packages/core/src/lib/terrain-hollows.ts @@ -0,0 +1,167 @@ +/** + * Closed hollows of a ground: places water cannot leave by running downhill. The ground is read on + * a square grid over a rectangle and flooded from its border inward, lowest first (a priority + * flood): each cell's water level is the lowest height it must rise to before it spills toward + * the border. A cell whose water level stands over its ground is in a hollow, by that depth. + * + * `blocked` cells neither hold nor pass water (a house): a pocket between a house and a bank is a + * hollow unless the ground leads round the house. + */ +export type Hollow = { + /** The deepest water would stand, metres, and where. */ + depthM: number + at: [number, number] + /** Ground under more than `minDepthM` of standing water. */ + areaM2: number +} + +export type HollowScan = { + bounds: { minX: number; minZ: number; maxX: number; maxZ: number } + /** Grid step; widened so the scan holds at most `MAX_HOLLOW_CELLS` cells. */ + stepM?: number + /** Standing water shallower than this is the grid's own noise. */ + minDepthM?: number + blocked?: (x: number, z: number) => boolean + /** Only hollows a cell of which lies here are reported (near a house). */ + within?: (x: number, z: number) => boolean +} + +export const MAX_HOLLOW_CELLS = 160_000 + +/** The hollows of `ground` over a rectangle: each connected patch of standing water, deepest first. */ +export function closedHollows( + ground: (x: number, z: number) => number, + { bounds, stepM = 0.25, minDepthM = 0.03, blocked, within }: HollowScan, +): Hollow[] { + const width = bounds.maxX - bounds.minX + const depth = bounds.maxZ - bounds.minZ + if (!(width > 0 && depth > 0) || !Number.isFinite(width * depth)) return [] + const step = Math.max(stepM, Math.sqrt((width * depth) / MAX_HOLLOW_CELLS)) + const cols = Math.max(2, Math.floor(width / step) + 1) + const rows = Math.max(2, Math.floor(depth / step) + 1) + const count = cols * rows + const height = new Float64Array(count) + const wall = new Uint8Array(count) + const xOf = (index: number) => bounds.minX + (index % cols) * step + const zOf = (index: number) => bounds.minZ + Math.floor(index / cols) * step + for (let index = 0; index < count; index++) { + const x = xOf(index) + const z = zOf(index) + if (blocked?.(x, z)) wall[index] = 1 + else height[index] = ground(x, z) + } + // A binary heap of cell indices, lowest water level first. + const level = new Float64Array(count).fill(Number.NaN) + const heap: number[] = [] + const push = (index: number) => { + heap.push(index) + let i = heap.length - 1 + while (i > 0) { + const parent = (i - 1) >> 1 + if ((level[heap[parent] as number] as number) <= (level[heap[i] as number] as number)) break + ;[heap[parent], heap[i]] = [heap[i] as number, heap[parent] as number] + i = parent + } + } + const pop = () => { + const top = heap[0] as number + const last = heap.pop() as number + if (heap.length) { + heap[0] = last + let i = 0 + for (;;) { + const left = 2 * i + 1 + const right = left + 1 + let least = i + if ( + left < heap.length && + (level[heap[left] as number] as number) < (level[heap[least] as number] as number) + ) + least = left + if ( + right < heap.length && + (level[heap[right] as number] as number) < (level[heap[least] as number] as number) + ) + least = right + if (least === i) break + ;[heap[least], heap[i]] = [heap[i] as number, heap[least] as number] + i = least + } + } + return top + } + for (let index = 0; index < count; index++) { + const col = index % cols + const row = Math.floor(index / cols) + if (wall[index] || (col > 0 && col < cols - 1 && row > 0 && row < rows - 1)) continue + level[index] = height[index] as number + push(index) + } + while (heap.length) { + const index = pop() + const col = index % cols + const row = Math.floor(index / cols) + for (const [dc, dr] of [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, 1], + [1, -1], + [-1, 1], + [-1, -1], + ] as const) { + const c = col + dc + const r = row + dr + if (c < 0 || c >= cols || r < 0 || r >= rows) continue + const next = r * cols + c + if (wall[next] || !Number.isNaN(level[next] as number)) continue + level[next] = Math.max(height[next] as number, level[index] as number) + push(next) + } + } + // Patches of standing water, by flood fill over the cells deeper than the floor of noise. + const seen = new Uint8Array(count) + const hollows: Hollow[] = [] + const wet = (index: number) => + !wall[index] && + !Number.isNaN(level[index] as number) && + (level[index] as number) - (height[index] as number) > minDepthM + for (let start = 0; start < count; start++) { + if (seen[start] || !wet(start)) continue + const stack = [start] + seen[start] = 1 + let deepest = 0 + let at = start + let cells = 0 + let near = !within + while (stack.length) { + const index = stack.pop() as number + cells++ + const depthHere = (level[index] as number) - (height[index] as number) + if (depthHere > deepest) { + deepest = depthHere + at = index + } + if (!near && within?.(xOf(index), zOf(index))) near = true + const col = index % cols + const row = Math.floor(index / cols) + for (const [dc, dr] of [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ] as const) { + const c = col + dc + const r = row + dr + if (c < 0 || c >= cols || r < 0 || r >= rows) continue + const next = r * cols + c + if (seen[next] || !wet(next)) continue + seen[next] = 1 + stack.push(next) + } + } + if (near) hollows.push({ depthM: deepest, at: [xOf(at), zOf(at)], areaM2: cells * step * step }) + } + return hollows.sort((a, b) => b.depthM - a.depthM) +} diff --git a/packages/core/src/lib/terrain-lag-equality.test.ts b/packages/core/src/lib/terrain-lag-equality.test.ts new file mode 100644 index 0000000000..e6d2d6d45f --- /dev/null +++ b/packages/core/src/lib/terrain-lag-equality.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from 'bun:test' +import golden from './__fixtures__/terrain-lag-golden.json' +import goldenSides from './__fixtures__/terrain-lag-golden-sides.json' +import { terrainLagPoints, terrainLagScenes } from './__fixtures__/terrain-lag-scenes' +import { terrainBreakHeightAt } from './terrain-breaks' +import { heightAt } from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' + +/* + * Failure modes this file pins (the terrain lag, 15 Oct): the authority's reads were made fast + * without changing a result. The golden heights are what the build before the speed-up read, to + * the last bit, on scenes shaped like the owner's (tiles, closed and open breaks, a legacy field). + * - a read takes a different tile, triangle or region than it did, and a height moves; + * - the cache that keeps one authority per site returns the field of another set of tiles or breaks; + * - a legacy-only scene's bounds change. + */ + +const scenes = terrainLagScenes() + +describe('the authority reads what it read before the speed-up', () => { + test.each(scenes.map((scene) => [scene.name, scene] as const))( + '%s: every sampled height is the same', + (name, scene) => { + const field = persistedTerrainFieldOf(scene.site, scene.nodes) + expect(field).not.toBeNull() + const expected = (golden.heights as Record)[name]! + const points = terrainLagPoints(scene) + expect(points).toHaveLength(expected.length) + const wrong: string[] = [] + points.forEach(([x, z], index) => { + const value = heightAt(field!, x, z) + if (value !== expected[index]) wrong.push(`(${x}, ${z}): ${value} ≠ ${expected[index]}`) + }) + expect(wrong).toEqual([]) + }, + ) + + test.each( + scenes + .filter((scene) => scene.rings.length || scene.open) + .map((scene) => [scene.name, scene] as const), + )('%s: the ground each side of a break reads the same, refusals included', (name, scene) => { + const field = persistedTerrainFieldOf(scene.site, scene.nodes)! + const expected = (goldenSides as Record)[name]! + const points = terrainLagPoints(scene).filter((_, index) => index % 3 === 0) + const read: (number | string)[] = [] + for (const boundary of field.terrainBreaks ?? []) + for (const side of ['left', 'right'] as const) + for (const [x, z] of points) { + try { + read.push(terrainBreakHeightAt(field, boundary, side, x, z)) + } catch (error) { + read.push(`refused: ${(error as Error).message}`) + } + } + expect(read).toEqual(expected) + }) + + test('a legacy-only scene keeps its exact bounds', () => { + const scene = scenes.find((entry) => entry.name === 'legacy only')! + expect(persistedTerrainFieldOf(scene.site, scene.nodes)?.heightBounds).toEqual( + golden.legacyOnlyBounds as [number, number], + ) + }) +}) diff --git a/packages/core/src/lib/terrain-ramp-cut.test.ts b/packages/core/src/lib/terrain-ramp-cut.test.ts new file mode 100644 index 0000000000..6e3ff40d45 --- /dev/null +++ b/packages/core/src/lib/terrain-ramp-cut.test.ts @@ -0,0 +1,235 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + rampOffsetPoint, + rampStations, + storedHeightAt, + terrainEditField, + terrainPreviewField, +} from '@pascal-app/core' +import { AGENT_OPERATIONS, applySceneChanges } from '@pascal-app/core/agent-operations' +import { type AnyNode, type RampNode, SiteNode } from '@pascal-app/core/schema' + +type Nodes = Record +const context = { activeLevelId: null } +const HALF_WIDTH = 1.5 + +/** A 40 × 40 m lot on a 6 % cross-fall with a ramp that turns through a quarter circle. */ +function hillside(): { before: Nodes; after: Nodes; ramp: RampNode; siteId: string } { + const field = createTerrainField({ origin: [-20, -20], spacing: 0.5, cols: 81, rows: 81 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) { + const x = -20 + col * 0.5 + const z = -20 + row * 0.5 + field.heights[row * field.cols + col] = Math.round( + (0.06 * x + 0.04 * z + 0.15 * Math.sin(x / 3)) * 100, + ) + } + const site = SiteNode.parse({ + id: 'site_cut', + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [20, -20], + [20, 20], + [-20, 20], + ], + }, + terrain: encodeTerrainField(field), + }) + const before: Nodes = { [site.id]: site } + const outcome = AGENT_OPERATIONS.add_ramp( + before, + { + siteId: site.id, + start: [-8, -9], + segments: [ + { type: 'line', end: [-8, -4] }, + { type: 'arc', center: [-2, -4], sweep: -Math.PI / 2 }, + ], + width: HALF_WIDTH * 2, + startHeight: 0, + endHeight: -1.5, + thickness: 0.15, + startTransition: 0, + endTransition: 0, + terrainMode: 'cut-fill', + } as never, + context, + ) + const ramp = outcome.changes?.create?.find(({ node }) => node.type === 'ramp')?.node + if (ramp?.type !== 'ramp') throw new Error('The operation did not create a ramp') + return { before, after: applySceneChanges(before, outcome.changes), ramp, siteId: site.id } +} + +function fieldOf(nodes: Nodes, siteId: string) { + const site = nodes[siteId] + const field = site?.type === 'site' ? persistedTerrainFieldOf(site, nodes) : null + if (!field) throw new Error('Missing terrain') + return field +} + +/** Points beside the corridor's true side lines, `outset` metres outside them. */ +function besideTheEdge(ramp: RampNode, outset: number): [number, number][] { + const points: [number, number][] = [] + for (const station of rampStations(ramp, 0.25)) + for (const side of [-1, 1]) + points.push(rampOffsetPoint(station, side * (ramp.width / 2 + outset))) + return points +} + +describe('the ground beside a graded ramp', () => { + test('grading really lowers the corridor, so the cut is there to meet', () => { + const { before, after, ramp, siteId } = hillside() + const natural = fieldOf(before, siteId) + const graded = fieldOf(after, siteId) + const middle = rampStations(ramp, 1).filter((station) => station.distance > 1) + const moved = middle.filter( + (station) => + Math.abs(heightAt(graded, ...station.point) - heightAt(natural, ...station.point)) > 0.05, + ) + expect(moved.length).toBeGreaterThan(middle.length / 2) + }) + + test('is the ground before the grading, right up to the corridor edge', () => { + const { before, after, ramp, siteId } = hillside() + const natural = fieldOf(before, siteId) + const graded = fieldOf(after, siteId) + for (const outset of [0.001, 0.01, 0.1, 0.25, 0.5, 1]) { + for (const [x, z] of besideTheEdge(ramp, outset)) { + expect(heightAt(graded, x, z)).toBeCloseTo(heightAt(natural, x, z), 9) + } + } + }) + + test('is also the natural ground on the corridor edge itself, where a mesh clips', () => { + const { before, after, ramp, siteId } = hillside() + const natural = fieldOf(before, siteId) + const graded = fieldOf(after, siteId) + // A clipped rim vertex lies on a chord of the curve, a few millimetres inside the edge. + for (const inset of [0, 0.002, 0.005, 0.01]) { + for (const [x, z] of besideTheEdge(ramp, -inset)) { + expect(heightAt(graded, x, z)).toBeCloseTo(heightAt(natural, x, z), 9) + } + } + }) + + test('the corridor itself keeps the graded ground', () => { + const { before, after, ramp, siteId } = hillside() + const natural = fieldOf(before, siteId) + const graded = fieldOf(after, siteId) + const length = rampStations(ramp, 1).at(-1)?.distance ?? 0 + // The roadway's two ends are cut edges too, with the ground beyond them natural. + const stations = rampStations(ramp, 1).filter( + (station) => station.distance > 0.5 && station.distance < length - 0.5, + ) + for (const station of stations) + expect(heightAt(graded, ...station.point)).toBeCloseTo(station.height - ramp.thickness, 1) + // 0.2 m inside the edge is still the graded ground. + const inside = besideTheEdge(ramp, -0.2).filter((_, index) => index > 8) + expect( + inside.some(([x, z]) => Math.abs(heightAt(graded, x, z) - heightAt(natural, x, z)) > 0.02), + ).toBe(true) + }) + + test('everywhere else is the ground it was', () => { + const { before, after, ramp, siteId } = hillside() + const natural = fieldOf(before, siteId) + const graded = fieldOf(after, siteId) + const clear = (x: number, z: number) => + rampStations(ramp, 0.5).every( + (station) => Math.hypot(station.point[0] - x, station.point[1] - z) > ramp.width / 2 + 1.2, + ) + let checked = 0 + for (let x = -19.7; x < 19.7; x += 0.73) + for (let z = -19.7; z < 19.7; z += 0.61) { + if (!clear(x, z)) continue + checked++ + // The two fields read tiles and the legacy grid with differently ordered arithmetic. + expect(heightAt(graded, x, z)).toBeCloseTo(heightAt(natural, x, z), 12) + } + expect(checked).toBeGreaterThan(1000) + }) + + test('a tile write still reads every sample exactly as graded', () => { + const { after, ramp, siteId } = hillside() + const graded = fieldOf(after, siteId) + const effect = ramp.terrainEffect + if (!effect) throw new Error('The ramp has no receipt') + expect(effect.samples.length).toBeGreaterThan(20) + for (const [index, , applied] of effect.samples) { + const x = effect.origin[0] + (index % effect.cols) * effect.spacing + const z = effect.origin[1] + Math.floor(index / effect.cols) * effect.spacing + expect(storedHeightAt(graded, x, z)).toBeCloseTo(applied * effect.step, 9) + } + }) + + test('the bounds hold every height the ground reads', () => { + const { before, after, siteId } = hillside() + const natural = fieldOf(before, siteId) + const graded = fieldOf(after, siteId) + const [low, high] = graded.heightBounds ?? [0, 0] + for (let x = -20; x <= 20; x += 0.5) + for (let z = -20; z <= 20; z += 0.5) + for (const field of [graded, natural]) { + const here = heightAt(field, x, z) + expect(here).toBeGreaterThanOrEqual(low - 1e-9) + expect(here).toBeLessThanOrEqual(high + 1e-9) + } + }) + + test('a scene without a graded ramp is the same field object as before', () => { + const { before, siteId } = hillside() + const site = before[siteId] + if (site?.type !== 'site') throw new Error('Missing site') + expect(persistedTerrainFieldOf(site, before)).toBe(persistedTerrainFieldOf(site, before)) + }) +}) + +describe('a live stroke on a site with a ramp cut', () => { + const rect = { minX: 10, minZ: -18, maxX: 16, maxZ: -12 } + + for (const withBreak of [false, true]) { + test(`keeps the ground beside the ramp natural outside the stroke${withBreak ? ', with a break on the lot' : ''}`, () => { + const { before, after, ramp, siteId } = hillside() + let scene = after + if (withBreak) { + // A closed break far from the ramp puts the lot on the break authority's preview branch. + const pad = [ + [12, 8], + [16, 8], + [16, 12], + [12, 12], + ] + const outcome = (AGENT_OPERATIONS as never as Record never>) + .carve_terrain_pad as unknown as ( + nodes: Nodes, + input: unknown, + context: unknown, + ) => { changes: Parameters[1] } + scene = applySceneChanges( + after, + outcome(after, { pad, padHeightM: -0.4, edges: 'retaining' }, context).changes, + ) + } + const site = scene[siteId] + if (site?.type !== 'site') throw new Error('Missing site') + const persisted = persistedTerrainFieldOf(site, scene) + if (!persisted) throw new Error('Missing terrain') + const preview = terrainEditField(site, scene, rect) + const natural = fieldOf(before, siteId) + const live = terrainPreviewField(preview, persisted) + for (const outset of [0.001, 0.01, 0.1, 0.5]) { + for (const [x, z] of besideTheEdge(ramp, outset)) { + expect(heightAt(live, x, z)).toBeCloseTo(heightAt(natural, x, z), 9) + } + } + // Inside the rectangle the stroke's own samples are read. + expect(heightAt(live, 13, -15)).toBeCloseTo(heightAt(preview, 13, -15), 9) + }) + } +}) diff --git a/packages/core/src/lib/terrain-ramp-cut.ts b/packages/core/src/lib/terrain-ramp-cut.ts new file mode 100644 index 0000000000..83fb396c65 --- /dev/null +++ b/packages/core/src/lib/terrain-ramp-cut.ts @@ -0,0 +1,97 @@ +import type { RampNode } from '../schema' +import { rampBounds, rampLength, rampProjectPoint } from './ramp' +import type { TerrainNodes, TerrainSite } from './terrain-tiles' + +/** + * A ramp's graded corridor, seen from the ground around it. + * + * Grading writes the corridor's lattice samples, so a lattice triangle that straddles the + * corridor's edge reads a mix of lowered and natural samples and the ground beside the cut dips + * toward the roadway by up to a cell. The ground outside the corridor is the natural ground: the + * authority reads it from the tiles with the ramp's graded samples put back (see + * `terrainAuthorityField`), and the corridor itself keeps the graded samples. + */ +export type RampCut = { + ramp: RampNode + bounds: { minX: number; minZ: number; maxX: number; maxZ: number } + /** The centreline's length: the roadway's two ends are cut edges like its sides. */ + length: number +} + +/** + * How far inside the corridor's edge, along a side or at an end, still reads as the ground beside + * it, metres. The edge a mesh clips on is a chord of the true curve, up to a few millimetres + * inside it. + */ +export const RAMP_EDGE_BAND_M = 0.02 + +/** The ramps whose grading the ground under `site` carries: cut-fill with a receipt of samples. */ +export function rampsGradingOf( + site: Pick | null | undefined, + nodes?: TerrainNodes, +): RampNode[] { + if (!site?.id || !nodes) return [] + return Object.values(nodes) + .filter( + (node): node is RampNode => + node.type === 'ramp' && + node.parentId === site.id && + node.terrainMode === 'cut-fill' && + (node.terrainEffect?.samples.length ?? 0) > 0, + ) + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) +} + +const cutCache = new WeakMap() + +/** A ramp that cannot be measured has no corridor to protect: the ground never fails for it. */ +export function rampCutOf(ramp: RampNode): RampCut | null { + if (cutCache.has(ramp)) return cutCache.get(ramp) ?? null + let cut: RampCut | null = null + try { + cut = { ramp, bounds: rampBounds(ramp), length: rampLength(ramp) } + } catch { + cut = null + } + cutCache.set(ramp, cut) + return cut +} + +/** + * Whether the graded samples decide the height at a point: inside the corridor, clear of the + * band along its edge. The band and everything beyond it is the ground beside the cut, a lattice + * sample on the edge included: a tile write reads the stored samples through `readStoredHeightAt`. + */ +export function insideRampCut(cut: RampCut, x: number, z: number): boolean { + const { bounds } = cut + if (x < bounds.minX || x > bounds.maxX || z < bounds.minZ || z > bounds.maxZ) return false + const projected = rampProjectPoint(cut.ramp, [x, z]) + return ( + projected.inside && + cut.ramp.width / 2 - projected.lateral > RAMP_EDGE_BAND_M && + projected.distance > RAMP_EDGE_BAND_M && + projected.distance < cut.length - RAMP_EDGE_BAND_M + ) +} + +export type GradedSample = { x: number; z: number; previousM: number; appliedM: number } + +/** Every lattice sample the ramps' receipts recorded, with the height before and after. */ +export function gradedSamplesOf(ramps: readonly RampNode[]): GradedSample[] { + const samples: GradedSample[] = [] + for (const ramp of ramps) { + const effect = ramp.terrainEffect + if (!effect) continue + const count = effect.cols * effect.rows + for (const [index, previous, applied] of effect.samples) { + if (!Number.isInteger(index) || index < 0 || index >= count) continue + samples.push({ + x: effect.origin[0] + (index % effect.cols) * effect.spacing, + z: effect.origin[1] + Math.floor(index / effect.cols) * effect.spacing, + previousM: previous * effect.step, + appliedM: applied * effect.step, + }) + } + } + return samples +} diff --git a/packages/core/src/lib/terrain-raycast.ts b/packages/core/src/lib/terrain-raycast.ts index bd3eb6a104..104fc2fb99 100644 --- a/packages/core/src/lib/terrain-raycast.ts +++ b/packages/core/src/lib/terrain-raycast.ts @@ -21,7 +21,9 @@ * `heightAt` reports. */ -import { heightAt, type TerrainField } from './terrain-field' +import { TERRAIN_CONTINUATION_DISTANCE } from './terrain-authority' +import { terrainBreakHeightAt, terrainBreakIsClosed } from './terrain-breaks' +import { heightAt, heightAtSample, type TerrainField } from './terrain-field' export type TerrainHit = { /** Distance along the (unnormalized) direction vector. */ @@ -55,16 +57,17 @@ function fieldBounds(field: TerrainField): { maxX: number maxZ: number } { + const apron = field.readHeightAt ? TERRAIN_CONTINUATION_DISTANCE : 0 return { - minX: field.origin[0], - minZ: field.origin[1], - maxX: field.origin[0] + (field.cols - 1) * field.spacing, - maxZ: field.origin[1] + (field.rows - 1) * field.spacing, + minX: field.origin[0] - apron, + minZ: field.origin[1] - apron, + maxX: field.origin[0] + (field.cols - 1) * field.spacing + apron, + maxZ: field.origin[1] + (field.rows - 1) * field.spacing + apron, } } /** - * Min/max height in metres, cached per `heights` buffer. + * Min/max height in metres, cached per field version. * * The vertical extent is what bounds the march for rays that never leave the * field in XZ — a straight-down pointer ray, which is the single most common @@ -72,30 +75,26 @@ function fieldBounds(field: TerrainField): { * such a ray relies on `MAX_STEPS` to terminate, and an *upward* one burns all * 8192 steps before returning null. * - * The scan is O(samples), so it is cached on the buffer rather than repeated per - * ray. `applyHeightPatch` allocates a new `Int16Array` for every mutation, which - * makes the buffer identity a correct version key: a patched field misses the - * cache and rescans exactly once, and a stale entry is unreachable. `WeakMap` - * keeps it from retaining fields past their use. + * Sparse fields provide conservative bounds from their authored sources and + * continuation. Dense fields scan once per immutable field version. */ -const heightRangeCache = new WeakMap() +const heightRangeCache = new WeakMap() function heightRange(field: TerrainField): { minY: number; maxY: number } { - const cached = heightRangeCache.get(field.heights) + if (field.heightBounds) return { minY: field.heightBounds[0], maxY: field.heightBounds[1] } + const cached = heightRangeCache.get(field) if (cached) return cached let min = 0 let max = 0 - if (field.heights.length > 0) { - min = field.heights[0] ?? 0 - max = min - for (let i = 1; i < field.heights.length; i++) { - const h = field.heights[i] ?? 0 + for (let row = 0; row < field.rows; row++) { + for (let col = 0; col < field.cols; col++) { + const h = heightAtSample(field, col, row) if (h < min) min = h if (h > max) max = h } } - const range = { minY: min * field.step, maxY: max * field.step } - heightRangeCache.set(field.heights, range) + const range = { minY: min, maxY: max } + heightRangeCache.set(field, range) return range } @@ -154,13 +153,18 @@ function clipToField( * basement finds the surface it exits through. A ray whose origin is already * exactly on the surface returns `t = 0`. */ -export function raycastTerrain( +function raycastGroundSurface( field: TerrainField, origin: readonly [number, number, number], direction: readonly [number, number, number], ): TerrainHit | null { const dirLength = Math.hypot(direction[0], direction[1], direction[2]) if (dirLength < 1e-12) return null + if (field.readHeightAt && direction[0] === 0 && direction[2] === 0) { + const y = heightAt(field, origin[0], origin[2]) + const t = (y - origin[1]) / direction[1] + return t >= 0 ? { t, x: origin[0], y, z: origin[2] } : null + } const clip = clipToField(field, origin, direction) if (!clip) return null @@ -181,7 +185,7 @@ export function raycastTerrain( } const hitAt = (t: number): TerrainHit => { const p = at(t) - return { t, x: p.x, y: heightAt(field, p.x, p.z), z: p.z } + return { t, x: p.x, y: field.terrainBreaks?.length ? p.y : heightAt(field, p.x, p.z), z: p.z } } let prevT = tEnter @@ -214,3 +218,49 @@ export function raycastTerrain( return null } + +function raycastBreakFaces( + field: TerrainField, + origin: readonly [number, number, number], + direction: readonly [number, number, number], +): TerrainHit | null { + const clip = clipToField(field, origin, direction) + if (!clip) return null + let nearest: TerrainHit | null = null + for (const terrainBreak of field.terrainBreaks ?? []) { + const closed = terrainBreakIsClosed(terrainBreak) + for (let index = 1; index < terrainBreak.line.length; index++) { + const from = terrainBreak.line[index - 1] + const to = terrainBreak.line[index] + if (!from || !to) continue + const edgeX = to[0] - from[0] + const edgeZ = to[1] - from[1] + const denominator = direction[0] * edgeZ - direction[2] * edgeX + if (Math.abs(denominator) < 1e-12) continue + const offsetX = from[0] - origin[0] + const offsetZ = from[1] - origin[2] + const t = (offsetX * edgeZ - offsetZ * edgeX) / denominator + const u = (offsetX * direction[2] - offsetZ * direction[0]) / denominator + if (t < clip.tEnter || t > clip.tExit || (nearest && t >= nearest.t)) continue + if (closed && (u < 0 || u > 1)) continue + const x = origin[0] + direction[0] * t + const y = origin[1] + direction[1] * t + const z = origin[2] + direction[2] * t + const leftM = terrainBreakHeightAt(field, terrainBreak, 'left', x, z) + const rightM = terrainBreakHeightAt(field, terrainBreak, 'right', x, z) + if (y >= Math.min(leftM, rightM) && y <= Math.max(leftM, rightM)) nearest = { t, x, y, z } + } + } + return nearest +} + +export function raycastTerrain( + field: TerrainField, + origin: readonly [number, number, number], + direction: readonly [number, number, number], +): TerrainHit | null { + const surface = raycastGroundSurface(field, origin, direction) + if (!field.terrainBreaks?.length) return surface + const face = raycastBreakFaces(field, origin, direction) + return face && (!surface || face.t <= surface.t + 1e-6) ? face : surface +} diff --git a/packages/core/src/lib/terrain-source-cache.test.ts b/packages/core/src/lib/terrain-source-cache.test.ts new file mode 100644 index 0000000000..49215f49a0 --- /dev/null +++ b/packages/core/src/lib/terrain-source-cache.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, test } from 'bun:test' +import type { AnyNode, SiteNode } from '../schema' +import { RING_A, RING_C, terrainLagScene } from './__fixtures__/terrain-lag-scenes' +import { heightAt } from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' + +/* + * Failure modes this file pins (the terrain lag, 15 Oct): the persisted authority was rebuilt, as a + * new field object every consumer re-reads, whenever the site node object changed, which it does + * each time a child (a ramp, a rock, a tile, a fence) is added under the site. + * - a child appended to the site gives a new field, and every tile mesh is rebuilt for nothing; + * - the cache then answers with a field of other tiles, breaks or lot after a real edit. + */ + +const scene = () => + terrainLagScene('rings', { + breaks: [ + { line: RING_A, left: -3.8, right: 'ground' }, + { line: RING_C, left: -3.6, right: 'ground' }, + ], + }) + +const withSite = (nodes: Record, site: SiteNode) => ({ ...nodes, [site.id]: site }) + +describe('the persisted authority is one field per set of inputs', () => { + test('a child appended to the site, or its metadata, keeps the field', () => { + const { site, nodes } = scene() + const before = persistedTerrainFieldOf(site, nodes) + const appended = { ...site, children: [...site.children, 'ramp_new'] } as SiteNode + const named = { ...site, metadata: { note: 'x' } } as SiteNode + expect(persistedTerrainFieldOf(appended, withSite(nodes, appended))).toBe(before) + expect(persistedTerrainFieldOf(named, withSite(nodes, named))).toBe(before) + }) + + test('a moved lot corner, an edited tile and an edited break each give the field they should', () => { + const { site, nodes } = scene() + const before = persistedTerrainFieldOf(site, nodes)! + const probe: [number, number][] = [ + [-30, -30], + [-12, 14], + [0, 0], + [13, 7], + [40, 40], + [-60, 20], + ] + + const polygon = { + ...site.polygon, + points: site.polygon.points.map(([x, z], i) => (i === 0 ? [x - 30, z - 30] : [x, z])), + } + const resized = { ...site, polygon } as SiteNode + const bigger = persistedTerrainFieldOf(resized, withSite(nodes, resized))! + expect(bigger).not.toBe(before) + expect(bigger.origin[0]).toBeLessThan(before.origin[0]) + + const tile = Object.values(nodes).find((node) => node.type === 'terrain-tile') as AnyNode & { + heights: string + } + const edited = { ...tile, heights: `${tile.heights.slice(0, -8)}QUFBQQ==` } + const tileNodes = { ...nodes, [tile.id]: edited as AnyNode } + const tileField = persistedTerrainFieldOf(site, tileNodes)! + expect(tileField).not.toBe(before) + expect(persistedTerrainFieldOf(site, tileNodes)).toBe(tileField) + + const boundary = Object.values(nodes).find( + (node) => node.type === 'terrain-break', + ) as AnyNode & { + left: number + } + const lowered = { ...boundary, left: boundary.left - 1 } + const breakNodes = { ...nodes, [boundary.id]: lowered as AnyNode } + const breakField = persistedTerrainFieldOf(site, breakNodes)! + expect(breakField).not.toBe(before) + // Inside the lowered ring the height is the new numeric side; the unedited field says the old. + const [a, , c] = RING_A as [number, number][] + const inside: [number, number] = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2] + expect(heightAt(breakField, ...inside)).toBe(boundary.left - 1) + expect(heightAt(before, ...inside)).toBe(boundary.left) + + // The reused field reads what a field built from nothing reads. + const fresh = scene() + const rebuilt = persistedTerrainFieldOf( + { ...fresh.site, children: [...fresh.site.children, 'x'] } as SiteNode, + fresh.nodes, + )! + for (const [x, z] of probe) expect(heightAt(rebuilt, x, z)).toBe(heightAt(before, x, z)) + }) +}) diff --git a/packages/core/src/lib/terrain-source-persisted.ts b/packages/core/src/lib/terrain-source-persisted.ts index 7eb1b079fa..e10ed5e337 100644 --- a/packages/core/src/lib/terrain-source-persisted.ts +++ b/packages/core/src/lib/terrain-source-persisted.ts @@ -13,15 +13,21 @@ * No invalidation call, no version counter, nothing to forget to bump. * * `commitTerrainField` closes the loop: it encodes a field *and* primes the cache - * with the field it just encoded. That is what makes a sculpt stroke free — after - * the commit, the next read is a cache hit, so a stroke never decodes base64 even - * once, let alone per dab. + * with the field it just encoded. The virtual authority can reuse that decoded + * base without decoding it again. */ +import type { RampNode } from '../schema/nodes/ramp' import type { SiteNode } from '../schema/nodes/site' +import type { TerrainBreakNode } from '../schema/nodes/terrain-break' +import type { TerrainTileNode } from '../schema/nodes/terrain-tile' import type { TerrainData } from '../schema/terrain' +import { terrainAuthorityField } from './terrain-authority' +import { terrainBreaksOf } from './terrain-breaks' import { decodeTerrainField, encodeTerrainField } from './terrain-codec' import { createTerrainField, type TerrainField } from './terrain-field' +import { rampsGradingOf } from './terrain-ramp-cut' +import { type TerrainNodes, type TerrainSite, terrainTilesOf } from './terrain-tiles' const fieldCache = new WeakMap() @@ -31,10 +37,7 @@ const fieldCache = new WeakMap() */ const failedDecodes = new WeakSet() -export function persistedTerrainFieldOf( - site: Pick | null | undefined, -): TerrainField | null { - const data = site?.terrain +function legacyFieldOf(data: TerrainData | undefined): TerrainField | null { if (!data) return null const cached = fieldCache.get(data) if (cached) return cached @@ -49,6 +52,95 @@ export function persistedTerrainFieldOf( return field } +const emptyNodes: TerrainNodes = {} +const authorityCache = new WeakMap>() + +type AuthorityInputs = { + polygon: TerrainSite['polygon'] + points: string + terrain: TerrainData | undefined + tiles: TerrainTileNode[] + breaks: TerrainBreakNode[] + ramps: RampNode[] + field: TerrainField | null +} +/** The last authority built for a site id: one entry per site, a handful at most. */ +const authorityByInputs = new Map() +const AUTHORITY_ENTRIES = 16 + +const pointsOf = (site: TerrainSite) => JSON.stringify(site.polygon?.points ?? []) + +/** + * The authority is a function of the lot's outline, the legacy field and the tiles, breaks and + * graded ramps, and of nothing else about the site node: a child added under the site, or a + * rename, replaces the site object and must not replace the field every mesh, raycast and cache is + * keyed on. + */ +function reusableAuthority( + site: TerrainSite, + tiles: TerrainTileNode[], + breaks: TerrainBreakNode[], + ramps: RampNode[], +): AuthorityInputs | undefined { + if (!site.id) return undefined + const previous = authorityByInputs.get(site.id) + if ( + previous && + previous.terrain === site.terrain && + breaks.length === previous.breaks.length && + breaks.every((boundary, index) => boundary === previous.breaks[index]) && + tiles.length === previous.tiles.length && + tiles.every((tile, index) => tile === previous.tiles[index]) && + ramps.length === previous.ramps.length && + ramps.every((ramp, index) => ramp === previous.ramps[index]) && + (previous.polygon === site.polygon || previous.points === pointsOf(site)) + ) + return previous + return undefined +} + +export function persistedTerrainFieldOf( + site: TerrainSite | null | undefined, + nodes?: TerrainNodes, +): TerrainField | null { + if (!site) return null + const version = nodes ?? emptyNodes + let fields = authorityCache.get(version) + if (!fields) { + fields = new WeakMap() + authorityCache.set(version, fields) + } + const key = !site.polygon && !nodes && site.terrain ? site.terrain : site + if (fields.has(key)) return fields.get(key) ?? null + const tiles = terrainTilesOf(site, nodes) + const breaks = terrainBreaksOf(site, nodes) + const ramps = rampsGradingOf(site, nodes) + const reusable = reusableAuthority(site, tiles, breaks, ramps) + if (reusable) { + fields.set(key, reusable.field) + return reusable.field + } + const base = legacyFieldOf(site.terrain) + const field = + site.terrain && !base && breaks.length ? null : terrainAuthorityField(site, base, nodes) + fields.set(key, field) + if (site.id) { + authorityByInputs.delete(site.id) + authorityByInputs.set(site.id, { + polygon: site.polygon, + points: pointsOf(site), + terrain: site.terrain, + tiles, + breaks, + ramps, + field, + }) + if (authorityByInputs.size > AUTHORITY_ENTRIES) + authorityByInputs.delete(authorityByInputs.keys().next().value as string) + } + return field +} + /** * The field a site *would* sculpt into: its existing terrain, or a fresh flat * field sized to `options`. @@ -61,7 +153,7 @@ export function terrainFieldForEdit( site: Pick | null | undefined, options?: Parameters[0], ): TerrainField { - return persistedTerrainFieldOf(site) ?? createTerrainField(options) + return legacyFieldOf(site?.terrain) ?? createTerrainField(options) } /** @@ -69,8 +161,7 @@ export function terrainFieldForEdit( * * Call this instead of `encodeTerrainField` whenever the result is going into the * scene. The returned data is what to write to `site.terrain`; the cache priming - * means the very next `terrainFieldOf` on the updated node returns this exact - * field object without decoding. + * means the next virtual read reuses this base without decoding. */ export function commitTerrainField(field: TerrainField): TerrainData { const data = encodeTerrainField(field) diff --git a/packages/core/src/lib/terrain-source.test.ts b/packages/core/src/lib/terrain-source.test.ts index 6a1579532b..282cd7f9d2 100644 --- a/packages/core/src/lib/terrain-source.test.ts +++ b/packages/core/src/lib/terrain-source.test.ts @@ -84,12 +84,13 @@ describe('terrainFieldForEdit', () => { }) describe('commitTerrainField', () => { - test('the encoded data reads back as the same field, without decoding', () => { + test('committed data retains sample storage and repeated reads share the cached authority', () => { const field = sculptedField() const data = commitTerrainField(field) - // Cache primed: the very next read is the identical object, so a stroke never - // pays for base64 at all. - expect(terrainFieldOf({ terrain: data })).toBe(field) + const resolved = terrainFieldOf({ terrain: data }) + expect(resolved?.heights).toBe(field.heights) + expect(terrainFieldOf({ terrain: data })).toBe(resolved) + expect(heightAt(resolved as never, 3, 3)).toBe(2.5) }) test('the encoded data is still independently decodable', () => { diff --git a/packages/core/src/lib/terrain-source.ts b/packages/core/src/lib/terrain-source.ts index 8e3327922f..fd2d3e7269 100644 --- a/packages/core/src/lib/terrain-source.ts +++ b/packages/core/src/lib/terrain-source.ts @@ -1,8 +1,8 @@ -import type { SiteNode } from '../schema/nodes/site' -import { livePreviewsVisible } from '../store/live-previews' -import useLiveTerrain from '../store/use-live-terrain' +import { livePreviewsVisible } from '../lib/live-previews' +import { terrainPreviewField } from './terrain-authority' import type { TerrainField } from './terrain-field' import { persistedTerrainFieldOf } from './terrain-source-persisted' +import type { TerrainNodes, TerrainSite } from './terrain-tiles' export { commitTerrainField, @@ -10,6 +10,35 @@ export { terrainFieldForEdit, } from './terrain-source-persisted' +const previewCache = new WeakMap>() +let sceneNodesOf: (() => TerrainNodes) | undefined +let liveFieldOf: ((siteId: string) => TerrainField | undefined) | undefined + +/** The live store installs its reader so persisted migration queries stay headless. */ +export function setTerrainLiveSource(source: (siteId: string) => TerrainField | undefined): void { + liveFieldOf = source +} + +/** The package entry installs the live store without making schema readers import it. */ +export function setTerrainSceneSource(source: () => TerrainNodes): void { + sceneNodesOf = source +} + +function previewOf(live: TerrainField, persisted: TerrainField | null): TerrainField { + let fields = previewCache.get(live) + if (!fields) { + fields = new WeakMap() + previewCache.set(live, fields) + } + const key = persisted ?? live + let field = fields.get(key) + if (!field) { + field = terrainPreviewField(live, persisted) + fields.set(key, field) + } + return field +} + /** * The terrain field for a site, or `null` when the site has no sculpted terrain. * @@ -27,11 +56,14 @@ export { * showing a hill the raycast cannot hit. */ export function terrainFieldOf( - site: (Pick & { id?: string }) | null | undefined, + site: TerrainSite | null | undefined, + nodes?: TerrainNodes, ): TerrainField | null { + const sceneNodes = nodes ?? (site?.id ? sceneNodesOf?.() : undefined) + const persisted = persistedTerrainFieldOf(site, sceneNodes) if (site?.id && livePreviewsVisible()) { - const live = useLiveTerrain.getState().fieldOf(site.id) - if (live) return live + const live = liveFieldOf?.(site.id) + if (live) return previewOf(live, persisted) } - return persistedTerrainFieldOf(site) + return persisted } diff --git a/packages/core/src/lib/terrain-support-query.ts b/packages/core/src/lib/terrain-support-query.ts index 51a9f82822..94e28d9352 100644 --- a/packages/core/src/lib/terrain-support-query.ts +++ b/packages/core/src/lib/terrain-support-query.ts @@ -123,6 +123,13 @@ export function levelLocalToWorldXZ( * level at grade and its ground floor a storey up. When genuine below-grade * stacking lands, this rule tracks it with no change here — an excavated basement * will stop being at the datum, and stop being draped, on its own. + * + * **A building that names its ground level (`groundLevelId`) has said which storey + * stands on the ground, wherever it is seated.** Seating a house on a slope moves + * the building in height, so that storey's base leaves the datum; it is still the + * one the ground carries, and its lift is still measured from its own base. Without + * this, the steps, fences and posts around a seated house fell back to its flat + * plane, under the ground on one side of the slope and over it on the other. */ function levelDatum( nodes: Record, @@ -136,7 +143,7 @@ function levelDatum( : null const datum = building?.position?.[1] ?? 0 const baseWorldY = datum + elevation.baseY - if (!isSiteDatum(baseWorldY)) return null + if (!isSiteDatum(baseWorldY) && building?.groundLevelId !== levelId) return null return { building, baseWorldY } } @@ -174,10 +181,13 @@ export function terrainSupportLift( levelId: string, x: number, z: number, - fieldOf: (site: SiteNode) => ReturnType = persistedTerrainFieldOf, + fieldOf: ( + site: SiteNode, + nodes: Record, + ) => ReturnType = persistedTerrainFieldOf, ): number | null { const site = siteOf(nodes) - const field = site ? fieldOf(site) : null + const field = site ? fieldOf(site, nodes) : null if (!field) return null const datum = levelDatum(nodes, levelId) @@ -189,6 +199,35 @@ export function terrainSupportLift( return heightAt(field, worldX, worldZ) - datum.baseWorldY } +/** + * Where the ground is under a level-local point, in building-local metres: the frame a level's base + * is measured in. The sculpted terrain where the site has any, the flat datum elsewhere. Unlike + * {@link terrainSupportLift}, which says whether the ground *carries* what stands on a level (only + * the storey at the datum), this is answered for every level: a building on a plinth, an upper + * storey. What the ground does not carry still stands some distance from it, and that is a fact. + * Null when the level is unknown. + */ +export function groundHeightAt( + nodes: Record, + levelId: string, + x: number, + z: number, + fieldOf: ( + site: SiteNode, + nodes: Record, + ) => ReturnType = persistedTerrainFieldOf, +): number | null { + const elevation = cachedLevelElevations(nodes).get(levelId) + if (!elevation) return null + const building = elevation.buildingId + ? ((nodes[elevation.buildingId] ?? null) as BuildingNode | null) + : null + const site = siteOf(nodes) + const field = site ? fieldOf(site, nodes) : null + const [worldX, worldZ] = levelLocalToWorldXZ(building, x, z) + return (field ? heightAt(field, worldX, worldZ) : SITE_DATUM_Y) - (building?.position?.[1] ?? 0) +} + /** * **The level base, in level-local metres, at level-local `x`/`z`** — the surface * a node rests on when nothing built is under it. Sculpted ground where terrain diff --git a/packages/core/src/lib/terrain-support.test.ts b/packages/core/src/lib/terrain-support.test.ts index 07fd0b46b5..9291547390 100644 --- a/packages/core/src/lib/terrain-support.test.ts +++ b/packages/core/src/lib/terrain-support.test.ts @@ -112,6 +112,24 @@ describe('terrainSupportLift', () => { expect(terrainSupportLift(nodes, LEVEL_ID, 3, 3)).toBeNull() }) + test('a building that names its ground level is carried by the ground wherever it is seated', () => { + // Seated 2.5 m up with the ground level named: the plateau is level with its base, the rest + // of the ground 2.5 m under it. An upper storey of the same building is still not carried. + const nodes = scene( + makeSite(), + makeBuilding({ + position: [0, 2.5, 0], + groundLevelId: LEVEL_ID, + children: [LEVEL_ID, 'level_upper'], + }), + makeLevel(0), + makeLevel(1, 'level_upper'), + ) + expect(terrainSupportLift(nodes, LEVEL_ID, 3, 3)).toBeCloseTo(0, 6) + expect(terrainSupportLift(nodes, LEVEL_ID, 0, 0)).toBeCloseTo(-2.5, 6) + expect(terrainSupportLift(nodes, 'level_upper', 3, 3)).toBeNull() + }) + test('level-local XZ goes through the building transform', () => { // Translated: local (0,0) sits over world (3,3) — on the plateau. const translated = scene(makeSite(), makeBuilding({ position: [3, 0, 3] }), makeLevel(0)) diff --git a/packages/core/src/lib/terrain-support.ts b/packages/core/src/lib/terrain-support.ts index 97005d73a5..96c1548cb4 100644 --- a/packages/core/src/lib/terrain-support.ts +++ b/packages/core/src/lib/terrain-support.ts @@ -1,6 +1,9 @@ import type { AnyNode } from '../schema' import { terrainFieldOf } from './terrain-source' -import { terrainSupportLift as queryTerrainSupportLift } from './terrain-support-query' +import { + groundHeightAt as queryGroundHeightAt, + terrainSupportLift as queryTerrainSupportLift, +} from './terrain-support-query' export { isLevelAtSiteDatum, @@ -18,6 +21,15 @@ export function terrainSupportLift( return queryTerrainSupportLift(nodes, levelId, x, z, terrainFieldOf) } +export function groundHeightAt( + nodes: Record, + levelId: string, + x: number, + z: number, +): number | null { + return queryGroundHeightAt(nodes, levelId, x, z, terrainFieldOf) +} + export function levelBaseElevationAt( nodes: Record, levelId: string, diff --git a/packages/core/src/lib/terrain-tile-changes.ts b/packages/core/src/lib/terrain-tile-changes.ts new file mode 100644 index 0000000000..61e31c0ce0 --- /dev/null +++ b/packages/core/src/lib/terrain-tile-changes.ts @@ -0,0 +1,18 @@ +import type { SceneChanges, SceneNodes } from '../agent-operations/types' +import type { SiteNode } from '../schema' +import type { TerrainField } from './terrain-field' +import { planTerrainTileWrites } from './terrain-tile-write' + +/** Adapt the shared tile planner to the scene authority's atomic history edit. */ +export function planTerrainTileChanges( + site: SiteNode, + nodes: SceneNodes, + before: TerrainField, + after: TerrainField, +): SceneChanges { + const writes = planTerrainTileWrites(site, nodes, before, after) + return { + create: writes.creates.map((node) => ({ node, parentId: site.id })), + update: writes.updates.map(({ id, heights, step }) => ({ id, data: { heights, step } })), + } +} diff --git a/packages/core/src/lib/terrain-tile-write.ts b/packages/core/src/lib/terrain-tile-write.ts new file mode 100644 index 0000000000..5fb6894d25 --- /dev/null +++ b/packages/core/src/lib/terrain-tile-write.ts @@ -0,0 +1,174 @@ +import type { SiteNode } from '../schema/nodes/site' +import { + TERRAIN_TILE_SAMPLES, + TERRAIN_TILE_SIZE, + TERRAIN_TILE_SPACING, + TerrainTileNode, +} from '../schema/nodes/terrain-tile' +import { encodeTerrainField } from './terrain-codec' +import { createTerrainField, quantize, storedHeightAt, type TerrainField } from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' +import { type TerrainNodes, terrainTilesOf } from './terrain-tiles' + +export type TerrainEditBounds = { minX: number; minZ: number; maxX: number; maxZ: number } +export type TerrainTileWrites = { + creates: TerrainTileNode[] + updates: { id: TerrainTileNode['id']; heights: string; step: number }[] +} + +export function terrainEditField( + site: SiteNode, + nodes: TerrainNodes, + bounds: TerrainEditBounds, +): TerrainField { + if ( + ![bounds.minX, bounds.minZ, bounds.maxX, bounds.maxZ].every(Number.isFinite) || + bounds.maxX < bounds.minX || + bounds.maxZ < bounds.minZ + ) { + throw new Error('Terrain edit bounds must be a finite ordered rectangle') + } + const spacing = TERRAIN_TILE_SPACING + const minX = Math.floor(bounds.minX / spacing) + const minZ = Math.floor(bounds.minZ / spacing) + const maxX = Math.ceil(bounds.maxX / spacing) + const maxZ = Math.ceil(bounds.maxZ / spacing) + const authority = persistedTerrainFieldOf(site, nodes) + const field = createTerrainField({ + origin: [minX * spacing, minZ * spacing], + spacing, + cols: maxX - minX + 1, + rows: maxZ - minZ + 1, + step: authority?.step, + }) + sampleAuthority(field, authority) + return field +} + +function sampleAuthority(field: TerrainField, authority: TerrainField | null): void { + if (!authority) return + for (let row = 0; row < field.rows; row++) { + for (let col = 0; col < field.cols; col++) { + field.heights[row * field.cols + col] = quantize( + field, + storedHeightAt( + authority, + field.origin[0] + col * field.spacing, + field.origin[1] + row * field.spacing, + ), + ) + } + } +} + +function validateEditFields(before: TerrainField, after: TerrainField): void { + if ( + before.readHeightAt || + after.readHeightAt || + before.spacing !== TERRAIN_TILE_SPACING || + after.spacing !== before.spacing || + before.cols !== after.cols || + before.rows !== after.rows || + before.origin[0] !== after.origin[0] || + before.origin[1] !== after.origin[1] || + !before.origin.every((value) => Number.isInteger(value / TERRAIN_TILE_SPACING)) || + before.heights.length !== before.cols * before.rows || + after.heights.length !== after.cols * after.rows || + !Number.isFinite(after.step) || + after.step <= 0 + ) { + throw new Error('Terrain tile writes require matching materialized 0.5 metre edit grids') + } +} + +function ownersOfSample(coordinate: number): number[] { + const index = Math.floor(coordinate / TERRAIN_TILE_SIZE) + return coordinate === index * TERRAIN_TILE_SIZE ? [index - 1, index] : [index] +} + +function changedSamples(before: TerrainField, after: TerrainField) { + const changed = new Map() + const tiles = new Map() + for (let row = 0; row < after.rows; row++) { + for (let col = 0; col < after.cols; col++) { + const index = row * after.cols + col + const metres = (after.heights[index] ?? 0) * after.step + if (metres === (before.heights[index] ?? 0) * before.step) continue + const x = after.origin[0] + col * after.spacing + const z = after.origin[1] + row * after.spacing + changed.set(`${x},${z}`, metres) + for (const ix of ownersOfSample(x)) { + for (const iz of ownersOfSample(z)) tiles.set(`${ix},${iz}`, { ix, iz }) + } + } + } + return { changed, tiles } +} + +function editedTileField( + ix: number, + iz: number, + step: number, + authority: TerrainField | null, + changed: Map, +): TerrainField { + const field = createTerrainField({ + origin: [ix * TERRAIN_TILE_SIZE, iz * TERRAIN_TILE_SIZE], + cols: TERRAIN_TILE_SAMPLES, + rows: TERRAIN_TILE_SAMPLES, + spacing: TERRAIN_TILE_SPACING, + step, + }) + sampleAuthority(field, authority) + for (let row = 0; row < field.rows; row++) { + for (let col = 0; col < field.cols; col++) { + const value = changed.get( + `${field.origin[0] + col * field.spacing},${field.origin[1] + row * field.spacing}`, + ) + if (value !== undefined) field.heights[row * field.cols + col] = quantize(field, value) + } + } + return field +} + +/** Seed only touched tiles from the pre-edit authority, then mirror changed edge posts. + * Off-lattice legacy ground is sampled, not rewritten; untouched points within + * a seeded tile can change through quantization and triangle resampling. */ +export function planTerrainTileWrites( + site: SiteNode, + nodes: TerrainNodes, + before: TerrainField, + after: TerrainField, +): TerrainTileWrites { + validateEditFields(before, after) + const writes: TerrainTileWrites = { creates: [], updates: [] } + const { changed, tiles } = changedSamples(before, after) + if (changed.size === 0) return writes + const authority = persistedTerrainFieldOf(site, nodes) + const existing = terrainTilesOf(site, nodes) + const ordered = [...tiles.values()].sort( + (left, right) => left.ix - right.ix || left.iz - right.iz, + ) + for (const { ix, iz } of ordered) { + const field = editedTileField(ix, iz, after.step, authority, changed) + const heights = encodeTerrainField(field).heights + const owners = existing.filter((tile) => tile.ix === ix && tile.iz === iz) + if (owners.length === 0) + writes.creates.push( + TerrainTileNode.parse({ + parentId: site.id, + ix, + iz, + step: field.step, + heights, + }), + ) + else + for (const owner of owners) { + if (owner.heights !== heights || owner.step !== field.step) { + writes.updates.push({ id: owner.id, heights, step: field.step }) + } + } + } + return writes +} diff --git a/packages/core/src/lib/terrain-tiles.test.ts b/packages/core/src/lib/terrain-tiles.test.ts new file mode 100644 index 0000000000..6f4354c313 --- /dev/null +++ b/packages/core/src/lib/terrain-tiles.test.ts @@ -0,0 +1,302 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + planTerrainTileWrites, + terrainEditField, + terrainFieldOf, + tileFieldOf, +} from '@pascal-app/core' +import { type AnyNode, SiteNode, TerrainTileNode, WallNode } from '@pascal-app/core/schema' + +function tile(ix: number, iz: number, metres: number) { + const field = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + field.heights.fill(Math.round(metres / field.step)) + return TerrainTileNode.parse({ + id: `terrain-tile_${ix}_${iz}`, + parentId: 'site_tiles', + level: 0, + ix, + iz, + step: field.step, + heights: encodeTerrainField(field).heights, + }) +} + +// B1's persisted contract: no conversion on load; the tile lattice is independent +// of an imported legacy grid. Expected heights are fixture values, not tile outputs. +describe('terrain tile persistence', () => { + test('round-trips one 65² Int16 tile at a signed 32 m lattice coordinate', () => { + const authored = tile(-2, 3, 1.23) + const restored = TerrainTileNode.parse(JSON.parse(JSON.stringify(authored))) + expect(restored).toEqual(authored) + const field = tileFieldOf(restored) + if (!field) throw new Error('Valid tile did not decode') + expect(field).toMatchObject({ origin: [-64, 96], cols: 65, rows: 65, spacing: 0.5 }) + expect(heightAt(field, -48, 112)).toBe(1.23) + }) + + test('rejects unsupported levels, fractional indices, invalid steps and wrong sample payloads', () => { + const valid = tile(0, 0, 0) + const short = createTerrainField({ cols: 33, rows: 33, spacing: 0.5 }) + for (const invalid of [ + { level: 1 }, + { level: -1 }, + { ix: 0.5 }, + { iz: Number.NaN }, + { step: 0 }, + { step: -0.01 }, + { step: Number.POSITIVE_INFINITY }, + { heights: encodeTerrainField(short).heights }, + { heights: 'not base64' }, + ]) + expect(TerrainTileNode.safeParse({ ...valid, ...invalid }).success).toBe(false) + }) + + test('old scenes with and without a legacy field still load without creating tile data', () => { + const plain = SiteNode.parse({ id: 'site_tiles' }) + expect(plain.terrain).toBeUndefined() + expect(terrainFieldOf(plain, { [plain.id]: plain })).toBeNull() + const legacy = createTerrainField({ cols: 5, rows: 5, origin: [-1.3, -0.7], spacing: 0.8 }) + legacy.heights.set([0, 11, -5, 39, 100]) + const encoded = encodeTerrainField(legacy) + const site = SiteNode.parse(JSON.parse(JSON.stringify({ ...plain, terrain: encoded }))) + expect(site.terrain).toEqual(encoded) + expect(site.children).toEqual(plain.children) + }) +}) + +describe('legacy terrain tile seeding', () => { + function legacySite(crease = false) { + const field = createTerrainField({ + cols: 69, + rows: 69, + spacing: 0.95, + origin: crease ? [0.15, 0.2] : [0.13, 0.27], + }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = crease + ? Math.abs(col - 1) * 95 + : 113 + 19 * col + 38 * row + return SiteNode.parse({ id: 'site_tiles', terrain: encodeTerrainField(field) }) + } + + test('an off-lattice plane seeds only the edited tile, within centimetre quantization', () => { + // The stored integers describe y = .996 + .2x + .4z exactly. + const site = legacySite() + const nodes: Record = { [site.id]: site } + const frozen = JSON.stringify(nodes) + const authority = persistedTerrainFieldOf(site, nodes) + if (!authority) throw new Error('Missing legacy terrain') + const before = terrainEditField(site, nodes, { minX: 4, minZ: 4, maxX: 40, maxZ: 40 }) + const heights = before.heights.slice() + heights[8 * before.cols + 8] = 1234 // (8,8), well inside tile (0,0). + const writes = planTerrainTileWrites(site, nodes, before, { ...before, heights }) + expect(writes.updates).toEqual([]) + expect(writes.creates).toHaveLength(1) + const created = writes.creates[0] + if (!created) throw new Error('The edit must create a tile') + expect(created).toMatchObject({ parentId: site.id, ix: 0, iz: 0 }) + const after = persistedTerrainFieldOf(site, { ...nodes, [created.id]: created }) + if (!after) throw new Error('Missing edited terrain') + expect(heightAt(after, 8, 8)).toBe(12.34) + for (const [x, z] of [ + [2.13, 3.27], + [16.25, 12.75], + [30.4, 30.1], + ] as const) { + const expected = 0.996 + 0.2 * x + 0.4 * z + expect(heightAt(authority, x, z)).toBeCloseTo(expected, 10) + expect(Math.abs(heightAt(after, x, z) - heightAt(authority, x, z))).toBeLessThanOrEqual(0.01) + // The half-metre samples round this particular plane upward by 4 mm. + expect(heightAt(after, x, z) - expected).toBeCloseTo(0.004, 10) + } + for (const [x, z] of [ + [32.01, 12.27], + [48.13, 48.27], + [60, 12], + ] as const) + expect(heightAt(after, x, z)).toBe(heightAt(authority, x, z)) + expect(JSON.stringify(nodes)).toBe(frozen) + }) + + test('an unchanged edit window creates no tiles on an arbitrary legacy grid', () => { + const site = legacySite() + const nodes = { [site.id]: site } + const frozen = JSON.stringify(nodes) + const before = terrainEditField(site, nodes, { minX: 4, minZ: 4, maxX: 40, maxZ: 40 }) + expect( + planTerrainTileWrites(site, nodes, before, { ...before, heights: before.heights.slice() }), + ).toEqual({ creates: [], updates: [] }) + expect(JSON.stringify(nodes)).toBe(frozen) + }) + + test('editing an existing overlay seeds from its current heights, not the frozen legacy', () => { + const site = legacySite() + const existing = tile(0, 0, 7) + const distant = tile(2, 0, 9) + const nodes = { [site.id]: site, [existing.id]: existing, [distant.id]: distant } + const frozen = JSON.stringify(nodes) + const before = terrainEditField(site, nodes, { minX: 8, minZ: 8, maxX: 9, maxZ: 9 }) + const heights = before.heights.slice() + heights[0] = 825 + const writes = planTerrainTileWrites(site, nodes, before, { ...before, heights }) + expect(writes.creates).toEqual([]) + expect(writes.updates).toHaveLength(1) + const update = writes.updates.find((entry) => entry.id === existing.id) + if (!update) throw new Error('The edited overlay must be updated in place') + const updated = TerrainTileNode.parse({ ...existing, ...update }) + const after = persistedTerrainFieldOf(site, { ...nodes, [updated.id]: updated }) + if (!after) throw new Error('Missing updated terrain') + expect(heightAt(after, 8, 8)).toBe(8.25) + expect(heightAt(after, 16.25, 12.75)).toBe(7) + expect(heightAt(after, 80, 16)).toBe(9) + expect(JSON.stringify(nodes)).toBe(frozen) + }) + + test('a legacy crease can move untouched interior reads by more than quantization', () => { + // y = |x - 1.1| has a legacy vertex at the crease. The new lattice's + // x=1 and x=1.5 heights are .1 and .4: at x=1.1 their chord is .16 m. + const site = legacySite(true) + const nodes = { [site.id]: site } + const frozen = JSON.stringify(nodes) + const authority = persistedTerrainFieldOf(site, nodes) + if (!authority) throw new Error('Missing legacy crease') + const before = terrainEditField(site, nodes, { minX: 8, minZ: 8, maxX: 9, maxZ: 9 }) + const heights = before.heights.slice() + heights[0] = 200 + const writes = planTerrainTileWrites(site, nodes, before, { ...before, heights }) + expect(writes.creates).toHaveLength(1) + expect(writes.updates).toEqual([]) + const created = writes.creates[0] + if (!created) throw new Error('The edit must create a tile') + expect(created).toMatchObject({ ix: 0, iz: 0 }) + const after = persistedTerrainFieldOf(site, { ...nodes, [created.id]: created }) + if (!after) throw new Error('Missing seeded crease') + expect(heightAt(after, 8, 8)).toBe(2) + expect(heightAt(authority, 1.1, 2)).toBeCloseTo(0, 10) + expect(heightAt(after, 1.1, 2)).toBeCloseTo(0.16, 10) + expect(heightAt(after, 1.1, 2) - heightAt(authority, 1.1, 2)).toBeGreaterThan(0.01) + // The same crease outside the seeded tile remains exactly authoritative. + expect(heightAt(after, 1.1, 40)).toBe(heightAt(authority, 1.1, 40)) + expect(JSON.stringify(nodes)).toBe(frozen) + }) +}) + +describe('virtual terrain authority', () => { + test('unrelated scene edits reuse terrain identity while a replaced tile invalidates it', () => { + const site = SiteNode.parse({ id: 'site_tiles' }) + const authored = tile(0, 0, 2) + const wall = WallNode.parse({ + id: 'wall_unrelated', + start: [0, 0], + end: [4, 0], + height: 3, + }) + const nodes: Record = { + [site.id]: site, + [authored.id]: authored, + [wall.id]: wall, + } + const original = persistedTerrainFieldOf(site, nodes) + if (!original) throw new Error('Missing tiled terrain') + const wallEdit = { + ...nodes, + [wall.id]: WallNode.parse({ ...wall, height: 4 }), + } + // E-010: unrelated construction edits must not invalidate every terrain mesh. + expect(persistedTerrainFieldOf(site, wallEdit)).toBe(original) + expect(terrainFieldOf(site, nodes)).toBe(original) + expect(terrainFieldOf(site, wallEdit)).toBe(original) + const changedTile = TerrainTileNode.parse({ ...authored, heights: tile(0, 0, 3).heights }) + const terrainEdit = { ...wallEdit, [authored.id]: changedTile } + const changed = persistedTerrainFieldOf(site, terrainEdit) + if (!changed) throw new Error('Updated tile lost terrain') + expect(changed).not.toBe(original) + expect(terrainFieldOf(site, terrainEdit)).toBe(changed) + expect(heightAt(changed, 16, 16)).toBe(3) + expect(heightAt(original, 16, 16)).toBe(2) + }) + + test('legacy samples and interpolated interior heights remain exactly equal on an unaligned grid', () => { + const legacy = createTerrainField({ cols: 5, rows: 5, origin: [-1.3, -0.7], spacing: 0.8 }) + for (let i = 0; i < legacy.heights.length; i++) legacy.heights[i] = ((i * 137) % 503) - 251 + const site = SiteNode.parse({ id: 'site_tiles', terrain: encodeTerrainField(legacy) }) + const distant = tile(2, -1, 7) + const nodes: Record = { [site.id]: site, [distant.id]: distant } + const virtual = persistedTerrainFieldOf(site, nodes) + if (!virtual) throw new Error('Missing virtual field') + const frozen = JSON.stringify(site.terrain) + for (let row = 0; row <= 16; row++) { + for (let col = 0; col <= 16; col++) { + const x = legacy.origin[0] + col * 0.2 + const z = legacy.origin[1] + row * 0.2 + // The pre-existing legacy sampler is the independent reference for E-003. + expect(heightAt(virtual, x, z)).toBe(heightAt(legacy, x, z)) + } + } + expect(JSON.stringify(site.terrain)).toBe(frozen) + expect(virtual.origin[0]).toBeLessThanOrEqual(-1.3) + expect(virtual.origin[1]).toBeLessThanOrEqual(-32) + expect(virtual.origin[0] + (virtual.cols - 1) * virtual.spacing).toBeGreaterThanOrEqual(96) + expect(virtual.origin[1] + (virtual.rows - 1) * virtual.spacing).toBeGreaterThanOrEqual(2.5) + }) + + test('a tile overrides the base, uncovered base stays authoritative, far context reaches the plane', () => { + const legacy = createTerrainField({ cols: 129, rows: 65, spacing: 0.5 }) + legacy.heights.fill(200) + const authored = tile(0, 0, 5) + const unrelated = TerrainTileNode.parse({ + ...tile(0, 0, 9), + id: 'terrain-tile_other', + parentId: 'site_other', + }) + const site = SiteNode.parse({ id: 'site_tiles', terrain: encodeTerrainField(legacy) }) + const field = persistedTerrainFieldOf(site, { + [site.id]: site, + [authored.id]: authored, + [unrelated.id]: unrelated, + }) + if (!field) throw new Error('Missing virtual field') + expect(heightAt(field, 16, 16)).toBe(5) + expect(heightAt(field, 48, 16)).toBe(2) + expect(heightAt(field, 200, 16)).toBe(0) + }) + + test('continuation leaves the border with its falling slope, then settles at the context plane', () => { + // y = 8 - x / 2 on [0,8]². Clamping would leave a visible 4 m plateau. + const legacy = createTerrainField({ cols: 17, rows: 17, spacing: 0.5 }) + for (let row = 0; row < 17; row++) + for (let col = 0; col < 17; col++) legacy.heights[row * 17 + col] = 800 - col * 25 + const site = SiteNode.parse({ id: 'site_tiles', terrain: encodeTerrainField(legacy) }) + const field = persistedTerrainFieldOf(site, { [site.id]: site }) + if (!field) throw new Error('Missing virtual field') + expect(heightAt(field, 8, 4)).toBe(4) + expect(heightAt(field, 8.01, 4)).toBeCloseTo(3.995, 4) + expect(heightAt(field, 9, 4)).toBeLessThan(4) + expect(heightAt(field, 72, 4)).toBe(0) + expect(heightAt(field, 100, 4)).toBe(0) + expect(heightAt(field, 71.99, 4)).toBeCloseTo(0, 4) + }) + + test('zero legacy padding descends toward the frozen negative minimum, not a flat datum', () => { + const legacy = createTerrainField({ cols: 65, rows: 65, spacing: 0.5, origin: [-16, -16] }) + legacy.heights[32 * 65 + 32] = -780 + const site = SiteNode.parse({ id: 'site_tiles', terrain: encodeTerrainField(legacy) }) + const nodes = { [site.id]: site } + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error('Missing legacy ground') + expect(heightAt(field, 0, 16)).toBe(0) + expect(heightAt(field, 0, 20)).toBeLessThan(0) + expect(heightAt(field, 0, 30)).toBeLessThan(heightAt(field, 0, 20)) + expect(heightAt(field, 0, 80)).toBe(-7.8) + const distant = tile(4, 4, -20) + const withTile = persistedTerrainFieldOf(site, { ...nodes, [distant.id]: distant }) + if (!withTile) throw new Error('Missing tiled ground') + expect(heightAt(withTile, 0, 30)).toBe(heightAt(field, 0, 30)) + expect(heightAt(withTile, 0, 80)).toBe(-7.8) + }) +}) diff --git a/packages/core/src/lib/terrain-tiles.ts b/packages/core/src/lib/terrain-tiles.ts new file mode 100644 index 0000000000..46a6cb979b --- /dev/null +++ b/packages/core/src/lib/terrain-tiles.ts @@ -0,0 +1,52 @@ +import type { SiteNode } from '../schema/nodes/site' +import { + TERRAIN_TILE_SAMPLES, + TERRAIN_TILE_SIZE, + TERRAIN_TILE_SPACING, + type TerrainTileNode, +} from '../schema/nodes/terrain-tile' +import type { AnyNode } from '../schema/types' +import { decodeTerrainField } from './terrain-codec' +import type { TerrainField } from './terrain-field' + +export type TerrainNodes = Readonly> +export type TerrainSite = Pick & Partial> + +const tileFields = new WeakMap() + +export function tileFieldOf(tile: TerrainTileNode): TerrainField | null { + if (tileFields.has(tile)) return tileFields.get(tile) ?? null + const field = + tile.level === 0 && Number.isInteger(tile.ix) && Number.isInteger(tile.iz) + ? decodeTerrainField({ + type: 'heightfield', + origin: [tile.ix * TERRAIN_TILE_SIZE, tile.iz * TERRAIN_TILE_SIZE], + spacing: TERRAIN_TILE_SPACING, + cols: TERRAIN_TILE_SAMPLES, + rows: TERRAIN_TILE_SAMPLES, + step: tile.step, + heights: tile.heights, + }) + : null + tileFields.set(tile, field) + return field +} + +/** Coordinates, then id, own duplicated edges regardless of graph insertion order. */ +export function terrainTilesOf( + site: Pick | null | undefined, + nodes?: TerrainNodes, +): TerrainTileNode[] { + if (!site?.id || !nodes) return [] + return Object.values(nodes) + .filter( + (node): node is TerrainTileNode => + node.type === 'terrain-tile' && node.parentId === site.id && tileFieldOf(node) !== null, + ) + .sort( + (left, right) => + left.ix - right.ix || + left.iz - right.iz || + (left.id < right.id ? -1 : left.id > right.id ? 1 : 0), + ) +} diff --git a/packages/core/src/procedural-items/query.ts b/packages/core/src/procedural-items/query.ts index fc8f46da80..939c72417b 100644 --- a/packages/core/src/procedural-items/query.ts +++ b/packages/core/src/procedural-items/query.ts @@ -7,6 +7,7 @@ import { polygonsOverlap, } from '../lib/polygon-relations' import { getRenderableSlabPolygon } from '../lib/slab-polygon' +import { slabTerrainHeightAt } from '../lib/slab-terrain' import { levelBaseElevationAt } from '../lib/terrain-support-query' import { nodeRegistry } from '../registry/registry' import { getBlockFaceFrame } from '../schema/nodes/block' @@ -113,12 +114,14 @@ function floorLift(node: AnyNode | ProceduralItemNode, nodes: QueryNodes): numbe ) if (supportSlabId === 'ground') return ground const supportSlabs = slabs.map((slab) => liftedManualSlab(nodes as Record, slab)) + const elevationOf = (slab: SlabNode) => + slabTerrainHeightAt(slab, nodes as Record, position[0], position[2]) const supportFor = (footprint: { position: Vec3; dimensions: Vec3; rotation: Vec3 }) => selectSlabSupportForItem( supportSlabs, footprint, (slab) => getRenderableSlabPolygon(slab, { walls, siblingSlabs: supportSlabs }), - { preferredSlabId: supportSlabId }, + { preferredSlabId: supportSlabId, elevationOf }, ) if (capability || node.type === 'cabinet' || node.type === 'cabinet-module') { const footprints = capability @@ -133,9 +136,9 @@ function floorLift(node: AnyNode | ProceduralItemNode, nodes: QueryNodes): numbe (slab) => slab && (slab.id === supportSlabId || (prefersBase && slab.plateRole === 'platform')), ) - if (pinned) return pinned.elevation ?? 0.05 + if (pinned) return elevationOf(pinned) return supports.length - ? Math.max(...supports.map((slab) => (slab ? (slab.elevation ?? 0.05) : ground))) + ? Math.max(...supports.map((slab) => (slab ? elevationOf(slab) : ground))) : ground } if (!(isProceduralItem(node) || node.type === 'item' || node.type === 'shelf')) return 0 @@ -150,7 +153,7 @@ function floorLift(node: AnyNode | ProceduralItemNode, nodes: QueryNodes): numbe rotation: node.rotation, } const support = supportFor(footprint) - return support ? (support.elevation ?? 0.05) : ground + return support ? elevationOf(support) : ground } function nodeParentFrame( node: AnyNode | ProceduralItemNode, diff --git a/packages/core/src/registry/validate-relations.ts b/packages/core/src/registry/validate-relations.ts index 385df6dacd..92d60c349e 100644 --- a/packages/core/src/registry/validate-relations.ts +++ b/packages/core/src/registry/validate-relations.ts @@ -1,3 +1,4 @@ +import { validateTerrainBreakRelations } from '../lib/terrain-break-validation' import type { AnyNode, AnyNodeId } from '../schema/types' import { nodeRegistry } from './registry' @@ -12,6 +13,7 @@ export function validateNodeRelations( changedIds: Iterable, ) { const affected = new Set(changedIds) + validateTerrainBreakRelations(before, next, affected) for (const id of [...affected]) { for (const node of [before[id], next[id]]) { if (node?.parentId) affected.add(node.parentId as AnyNodeId) diff --git a/packages/core/src/runtime/scene-runtime.ts b/packages/core/src/runtime/scene-runtime.ts index 8b75d777df..aa9448a7c3 100644 --- a/packages/core/src/runtime/scene-runtime.ts +++ b/packages/core/src/runtime/scene-runtime.ts @@ -12,6 +12,7 @@ import { supportIndexOf, withSpatialGrid, } from '../hooks/spatial-grid/spatial-grid-manager' +import { withoutLivePreviews } from '../lib/live-previews' import { resolveLevelId } from '../lib/node-ancestry' import { getNodePluginId, nodeRegistry } from '../registry/registry' import type { AnyNode, AnyNodeId, Collection } from '../schema' @@ -22,7 +23,6 @@ import { } from '../store/actions/node-actions' import { runSettlingDocument } from '../store/document-settling' import { pauseSceneHistory, resumeSceneHistory, type SceneSnapshot } from '../store/history-control' -import { withoutLivePreviews } from '../store/live-previews' import { createSceneEnvironment, type SceneEnvironment } from '../store/scene-environment' import useScene, { createSceneStore, diff --git a/packages/core/src/schema/__fixtures__/node-fixtures.ts b/packages/core/src/schema/__fixtures__/node-fixtures.ts index 4be280e6ea..b4efadc8ab 100644 --- a/packages/core/src/schema/__fixtures__/node-fixtures.ts +++ b/packages/core/src/schema/__fixtures__/node-fixtures.ts @@ -1,4 +1,6 @@ import { z } from 'zod' +import { encodeTerrainField } from '../../lib/terrain-codec' +import { createTerrainField } from '../../lib/terrain-field' import { shelfRecipe } from '../../procedural-items/fixtures' import * as schema from '../index' import { AnyNode, type AnyNodeType, nodeKindOf } from '../types' @@ -13,6 +15,18 @@ import { AnyNode, type AnyNodeType, nodeKindOf } from '../types' /** Fields a kind requires beyond the defaults its own schema fills in. */ export const NODE_REQUIRED_FIELDS: Record> = { beam: { start: [0, 0], end: [4, 0] }, + 'terrain-break': { + parentId: 'site_terrain', + line: [[-15, 0], [15, 0]], + kind: 'cliff', + left: 2, + right: 'ground', + }, + 'terrain-tile': { + ix: 0, + iz: 0, + heights: encodeTerrainField(createTerrainField({ cols: 65, rows: 65, spacing: 0.5 })).heights, + }, ceiling: { polygon: [ [0, 0], @@ -66,6 +80,11 @@ export const NODE_REQUIRED_FIELDS: Record> = { ], }, 'procedural-item': { recipe: shelfRecipe }, + ramp: { + start: [0, 0], + segments: [{ type: 'line', end: [10, 0] }], + endHeight: -1, + }, slab: { polygon: [ [0, 0], diff --git a/packages/core/src/schema/host-children.test.ts b/packages/core/src/schema/host-children.test.ts index 1f0dd09d30..731d8f1941 100644 --- a/packages/core/src/schema/host-children.test.ts +++ b/packages/core/src/schema/host-children.test.ts @@ -42,7 +42,10 @@ test('frozen pre-slice corpus covers every kind predating separators', () => { kind !== 'floor-opening' && kind !== 'fence-gate' && kind !== 'fence-opening' && - kind !== 'beam', + kind !== 'beam' && + kind !== 'ramp' && + kind !== 'terrain-break' && + kind !== 'terrain-tile', ).sort(), ) }) diff --git a/packages/core/src/schema/index.ts b/packages/core/src/schema/index.ts index 675ff11c45..9073d27d13 100644 --- a/packages/core/src/schema/index.ts +++ b/packages/core/src/schema/index.ts @@ -320,6 +320,7 @@ export { railingWallDefaults, railingWallSlotDefault, } from './nodes/railing-wall' +export { RampNode, RampSegment } from './nodes/ramp' // Nodes export { createDefaultRidgeVentsForSegment, @@ -476,6 +477,15 @@ export { export { StructuralGridNode } from './nodes/structural-grid' export { SurfaceHoleMetadata } from './nodes/surface-hole-metadata' export { SurfacePaintRegion } from './nodes/surface-paint-region' +export { TerrainBreakNode, type TerrainBreakNodeId } from './nodes/terrain-break' +export { + TERRAIN_TILE_SAMPLES, + TERRAIN_TILE_SIZE, + TERRAIN_TILE_SPACING, + TerrainTileNode, + type TerrainTileNodeId, + TerrainTileNodeSchema, +} from './nodes/terrain-tile' export { TurbineVentMaterialRole, TurbineVentNode } from './nodes/turbine-vent' export { DEFAULT_UNIT_COLOR, UNIT_KINDS, type UnitKind, UnitNode } from './nodes/unit' export type { diff --git a/packages/core/src/schema/nodes/ramp.ts b/packages/core/src/schema/nodes/ramp.ts new file mode 100644 index 0000000000..9eea4e3b6b --- /dev/null +++ b/packages/core/src/schema/nodes/ramp.ts @@ -0,0 +1,43 @@ +import { z } from 'zod' +import { BaseNode, nodeType, objectId } from '../base' + +const Point = z.tuple([z.number().finite(), z.number().finite()]) +const HeightUnit = z.number().int().min(-32768).max(32767) +const TerrainEffect = z.object({ + siteId: z.string(), + origin: Point, + spacing: z.number().finite().positive(), + cols: z.number().int().positive(), + rows: z.number().int().positive(), + step: z.number().finite().positive(), + samples: z.array(z.tuple([z.number().int().nonnegative(), HeightUnit, HeightUnit])), +}) + +export const RampSegment = z.discriminatedUnion('type', [ + z.object({ type: z.literal('line'), end: Point }), + z.object({ type: z.literal('arc'), center: Point, sweep: z.number().finite() }), +]) +export type RampSegment = z.infer + +/** Centreline and surface heights are in the owning Site's frame, in metres. */ +export const RampNode = BaseNode.extend({ + id: objectId('ramp'), + type: nodeType('ramp'), + start: Point, + segments: z.array(RampSegment).min(1).max(128), + width: z.number().finite().positive().default(3), + startHeight: z.number().finite().default(0), + endHeight: z.number().finite(), + thickness: z.number().finite().positive().default(0.15), + startTransition: z.number().finite().nonnegative().default(0), + endTransition: z.number().finite().nonnegative().default(0), + maxSlopePercent: z.number().finite().positive().default(18), + use: z.enum(['vehicle', 'pedestrian']).default('vehicle'), + startTargetId: z.string().optional(), + endTargetId: z.string().optional(), + terrainMode: z.enum(['cut-fill', 'none']).default('cut-fill'), + retainingHeight: z.number().finite().nonnegative().default(0), + terrainEffect: TerrainEffect.optional(), + slots: z.record(z.string(), z.string()).default({}), +}) +export type RampNode = z.infer diff --git a/packages/core/src/schema/nodes/slab.ts b/packages/core/src/schema/nodes/slab.ts index 309dcb0c93..2d689d4e7a 100644 --- a/packages/core/src/schema/nodes/slab.ts +++ b/packages/core/src/schema/nodes/slab.ts @@ -9,6 +9,7 @@ import { ZoneFloorScript } from './zone' // −0.01 underside offset. Applies to edits only; migration writes legacy // intervals verbatim (including degenerate zero-thickness slabs). export const MIN_SLAB_THICKNESS = 0.02 +export const DEFAULT_SLAB_THICKNESS = 0.05 // A ground-bearing base plate has no ceiling under it, so it may be thinner; // it is never zero (a zero-thickness plate renders as a hole). export const MIN_GROUND_FLOOR_THICKNESS = 0.01 @@ -27,6 +28,12 @@ export const SlabNode = BaseNode.extend({ holes: z.array(z.array(z.tuple([z.number(), z.number()]))).default([]), holeMetadata: z.array(SurfaceHoleMetadata).default([]), elevation: z.number().default(DEFAULT_SLAB_ELEVATION), // Walking surface (slab top), meters above the level plane + terrainMode: z + .enum(['flat', 'draped']) + .optional() + .describe( + 'Manual outdoor surfaces only: draped follows Site terrain with elevation as clearance; absent or flat keeps the authored plane.', + ), floorHeight: z .number() .finite() @@ -47,7 +54,7 @@ export const SlabNode = BaseNode.extend({ material: z.union([z.string(), MaterialSchema]).optional(), }) .optional(), - thickness: z.number().default(0.05), // Grows downward from the surface + thickness: z.number().default(DEFAULT_SLAB_THICKNESS), // Grows downward from the surface recessed: z.boolean().default(false), recessedRimElevation: z.number().finite().optional(), fillToTerrain: z.boolean().optional(), diff --git a/packages/core/src/schema/nodes/terrain-break.ts b/packages/core/src/schema/nodes/terrain-break.ts new file mode 100644 index 0000000000..900bf0b546 --- /dev/null +++ b/packages/core/src/schema/nodes/terrain-break.ts @@ -0,0 +1,45 @@ +import { z } from 'zod' +import { validateTerrainBreak } from '../../lib/terrain-breaks' +import { BaseNode, nodeType, objectId } from '../base' + +const SideHeight = z.union([z.number().finite(), z.literal('ground')]) + +export const TerrainBreakNode = BaseNode.extend({ + id: objectId('terrain-break'), + type: nodeType('terrain-break'), + line: z + .array(z.tuple([z.number().finite(), z.number().finite()])) + .min(2) + .max(513), + kind: z.enum(['cliff', 'retaining', 'soil']), + left: SideHeight, + right: SideHeight, +}) + .refine((node) => node.left !== 'ground' || node.right !== 'ground', { + message: 'At least one terrain-break side must have a numeric height.', + path: ['left'], + }) + .refine((node) => node.left !== 'ground' || node.right !== 'ground', { + message: 'At least one terrain-break side must have a numeric height.', + path: ['right'], + }) + .refine( + (node) => { + if (node.left === 'ground' && node.right === 'ground') return true + try { + validateTerrainBreak(node) + return true + } catch { + return false + } + }, + { + message: 'Terrain-break geometry must be straight open or a simple convex CCW closed ring.', + path: ['line'], + }, + ) + .describe('Vertical terrain boundary in site XZ metres; directed left is the positive cross side') + .meta({ strictMutations: true }) + +export type TerrainBreakNode = z.infer +export type TerrainBreakNodeId = TerrainBreakNode['id'] diff --git a/packages/core/src/schema/nodes/terrain-tile.ts b/packages/core/src/schema/nodes/terrain-tile.ts new file mode 100644 index 0000000000..a20742c9b1 --- /dev/null +++ b/packages/core/src/schema/nodes/terrain-tile.ts @@ -0,0 +1,23 @@ +import { z } from 'zod' +import { BaseNode, nodeType, objectId } from '../base' + +export const TERRAIN_TILE_SIZE = 32 +export const TERRAIN_TILE_SAMPLES = 65 +export const TERRAIN_TILE_SPACING = 0.5 + +// 65² little-endian Int16 samples: 8,450 bytes with one canonical padding byte. +const TileHeights = z.string().regex(/^[A-Za-z0-9+/]{11266}[AEIMQUYcgkosw048]=$/) + +export const TerrainTileNode = BaseNode.extend({ + id: objectId('terrain-tile'), + type: nodeType('terrain-tile'), + level: z.literal(0).default(0), + ix: z.number().int(), + iz: z.number().int(), + step: z.number().finite().positive().default(0.01), + heights: TileHeights, +}).describe('Authored terrain: a 32 metre tile with 65 × 65 quantized height samples') + +export type TerrainTileNode = z.infer +export type TerrainTileNodeId = TerrainTileNode['id'] +export const TerrainTileNodeSchema = TerrainTileNode diff --git a/packages/core/src/schema/types.ts b/packages/core/src/schema/types.ts index c12af374d6..328f315b80 100644 --- a/packages/core/src/schema/types.ts +++ b/packages/core/src/schema/types.ts @@ -34,6 +34,7 @@ import { MeasurementNode } from './nodes/measurement' import { PipeFittingNode } from './nodes/pipe-fitting' import { PipeSegmentNode } from './nodes/pipe-segment' import { PipeTrapNode } from './nodes/pipe-trap' +import { RampNode } from './nodes/ramp' import { RidgeVentNode } from './nodes/ridge-vent' import { RoofNode } from './nodes/roof' import { RoofSegmentNode } from './nodes/roof-segment' @@ -48,6 +49,8 @@ import { SpawnNode } from './nodes/spawn' import { StairNode } from './nodes/stair' import { StairSegmentNode } from './nodes/stair-segment' import { StructuralGridNode } from './nodes/structural-grid' +import { TerrainBreakNode } from './nodes/terrain-break' +import { TerrainTileNode } from './nodes/terrain-tile' import { TurbineVentNode } from './nodes/turbine-vent' import { UnitNode } from './nodes/unit' import { WallNode } from './nodes/wall' @@ -90,6 +93,8 @@ export const nodeUnion = , + electedBase: number, +): number { + return Math.min( + getWallTop(wall, levelId, nodes, electedBase, 0), + getWallTop(wall, levelId, nodes, electedBase, 1), + ) +} + /** * The lowest point of {@link getWallTop} over arc-length stations `[left, right]`. A sloped top is * linear along the chord (the frame the viewer slopes the extrusion in), so it is lowest at one end. diff --git a/packages/core/src/store/actions/node-update-children.test.ts b/packages/core/src/store/actions/node-update-children.test.ts index 85ca2668b2..02b3f0ca66 100644 --- a/packages/core/src/store/actions/node-update-children.test.ts +++ b/packages/core/src/store/actions/node-update-children.test.ts @@ -8,6 +8,7 @@ import { enableCompiledNodeParsers, } from '../../schema/compiled-node-parsers' import { ItemNode } from '../../schema/nodes/item' +import { SiteNode } from '../../schema/nodes/site' import { SlabNode } from '../../schema/nodes/slab' import type { AnyNode } from '../../schema/types' import useScene from '../use-scene' @@ -50,6 +51,18 @@ const child = ItemNode.parse({ asset: { id: 'child', name: 'Child', category: 'decor', thumbnail: '', src: '/child.glb' }, }) function seed(node: AnyNode) { + if (node.type === 'terrain-break') { + const site = SiteNode.parse({ id: 'site_children', children: [node.id] }) + useScene.setState({ + nodes: { + [site.id]: site, + [node.id]: { ...node, parentId: site.id }, + [child.id]: { ...child, parentId: node.id }, + }, + rootNodeIds: [site.id], + }) + return + } useScene.setState({ nodes: { [node.id]: node, [child.id]: { ...child, parentId: node.id } }, rootNodeIds: [node.id], diff --git a/packages/core/src/store/derived-node-guard.ts b/packages/core/src/store/derived-node-guard.ts index 8513cea22e..3a612a46a4 100644 --- a/packages/core/src/store/derived-node-guard.ts +++ b/packages/core/src/store/derived-node-guard.ts @@ -3,6 +3,7 @@ import { floorPlateAtGroundContact, floorPlateHoldsUnderside, supportDerivedFloorHeight, + upperFloorTopWrite, } from '../lib/floor-foundation-datum' import { expandFloorIntentChanges, floorIntentConflicts } from '../lib/floor-intent-changes' import { ownFloorIntentChanges } from '../lib/own-floor-intent' @@ -124,11 +125,8 @@ export function derivedFieldViolations( floorPlateHoldsUnderside(nodes, current) && typeof patch.elevation === 'number' && typeof patch.thickness === 'number' && - Math.abs( - patch.elevation - - patch.thickness - - ((current.floorHeight ?? current.elevation) - current.thickness), - ) <= 1e-6 + // The top moved over a held underside, or put under it with the plate moved whole. + Math.abs(patch.thickness - upperFloorTopWrite(current, patch.elevation).thickness) <= 1e-6 const violations = PROTECTED_FIELDS[current.type].filter( (field) => Object.hasOwn(patch, field) && diff --git a/packages/core/src/store/terrain-break-mutations.test.ts b/packages/core/src/store/terrain-break-mutations.test.ts new file mode 100644 index 0000000000..052dd3064d --- /dev/null +++ b/packages/core/src/store/terrain-break-mutations.test.ts @@ -0,0 +1,201 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { + clearSceneHistory, + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + useScene, +} from '@pascal-app/core' +import { type AnyNode, SiteNode, TerrainBreakNode, TerrainTileNode } from '@pascal-app/core/schema' + +const crossing: [number, number][] = [ + [3, 2], + [5, 2], + [5, 6], + [3, 6], + [3, 2], +] +const collapsed: [number, number][] = [ + [1, 2], + [1, 2], +] + +function fixture() { + const cliff = TerrainBreakNode.parse({ + id: 'terrain-break_cliff', + parentId: 'site_mutations', + line: [ + [4, 0], + [4, 8], + ], + kind: 'cliff', + left: 5, + right: 2, + }) + const pad = TerrainBreakNode.parse({ + id: 'terrain-break_pad', + parentId: 'site_mutations', + line: [ + [1, 2], + [3, 2], + [3, 6], + [1, 6], + [1, 2], + ], + kind: 'retaining', + left: 7, + right: 'ground', + }) + const site = SiteNode.parse({ + id: 'site_mutations', + children: [cliff.id, pad.id], + polygon: { + type: 'polygon', + points: [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ], + }, + }) + return { site, pad, nodes: { [site.id]: site, [cliff.id]: cliff, [pad.id]: pad } } +} + +let previous: ReturnType +let previousRaf: typeof requestAnimationFrame +let previousCancelRaf: typeof cancelAnimationFrame + +beforeEach(() => { + previous = useScene.getState() + previousRaf = globalThis.requestAnimationFrame + previousCancelRaf = globalThis.cancelAnimationFrame + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} + const { site, nodes } = fixture() + useScene.setState({ nodes, rootNodeIds: [site.id], dirtyNodes: new Set(), readOnly: false }) + clearSceneHistory() +}) + +afterEach(() => { + useScene.setState(previous) + clearSceneHistory() + globalThis.requestAnimationFrame = previousRaf + globalThis.cancelAnimationFrame = previousCancelRaf +}) + +function expectAtomicRefusal(write: () => unknown) { + const before = JSON.stringify(useScene.getState().nodes) + expect(write).toThrow() + expect(JSON.stringify(useScene.getState().nodes)).toBe(before) + expect(useScene.getState().dirtyNodes.size).toBe(0) +} + +describe('raw terrain-break mutations', () => { + test('a raw keep-ground ring without same-side tile samples is refused before publication', () => { + const samples = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + samples.heights.fill(500) + const tile = TerrainTileNode.parse({ + id: 'terrain-tile_raw', + parentId: 'site_mutations', + ix: 0, + iz: 0, + heights: encodeTerrainField(samples).heights, + }) + const site = SiteNode.parse({ ...fixture().site, children: [tile.id] }) + useScene.setState({ nodes: { [site.id]: site, [tile.id]: tile } }) + clearSceneHistory() + const tiny = TerrainBreakNode.parse({ + id: 'terrain-break_tiny', + parentId: site.id, + kind: 'retaining', + line: [ + [0.2, 0.2], + [0.3, 0.2], + [0.3, 0.3], + [0.2, 0.3], + [0.2, 0.2], + ], + left: 'ground', + right: 2, + }) + expectAtomicRefusal(() => useScene.getState().createNode(tiny, site.id)) + const field = persistedTerrainFieldOf(site, useScene.getState().nodes) + if (!field) throw new Error('Expected the untouched tile authority') + expect(heightAt(field, 0.25, 0.25)).toBe(5) + }) + + test('enlarging the lot cannot leave an existing open break with internal endpoints', () => { + const { site } = fixture() + expectAtomicRefusal(() => + useScene.getState().updateNode(site.id, { + polygon: { + type: 'polygon', + points: [ + [0, 0], + [8, 0], + [8, 12], + [0, 12], + ], + }, + }), + ) + }) + + test('single-node updates cannot publish crossing breaks', () => { + const { pad } = fixture() + expectAtomicRefusal(() => useScene.getState().updateNode(pad.id, { line: crossing })) + }) + + test('batch updates reject crossing geometry before applying an earlier unrelated edit', () => { + const { site, pad } = fixture() + expectAtomicRefusal(() => + useScene.getState().updateNodes([ + { id: site.id, data: { name: 'Must not be committed' } }, + { id: pad.id, data: { line: crossing } }, + ]), + ) + }) + + test('mixed scene changes reject the entire batch before publishing a conflicting break', () => { + const { site, pad } = fixture() + const extra = TerrainBreakNode.parse({ ...pad, id: 'terrain-break_extra', line: crossing }) + expectAtomicRefusal(() => + useScene.getState().applyNodeChanges({ + update: [{ id: site.id, data: { name: 'Must not be committed' } }], + create: [{ node: extra, parentId: site.id }], + }), + ) + }) + + test('raw creation refuses crossings without adding a node or parent-child reference', () => { + const { site, pad } = fixture() + const extra = TerrainBreakNode.parse({ ...pad, id: 'terrain-break_extra', line: crossing }) + expectAtomicRefusal(() => useScene.getState().createNode(extra, site.id)) + }) + + for (const [label, data] of [ + ['collapsed line', { line: collapsed }], + ['both sides ground', { left: 'ground' }], + ] satisfies [string, Partial][]) { + test(`strict mutation validation keeps the original scene after a ${label} update`, () => { + const { pad } = fixture() + expectAtomicRefusal(() => useScene.getState().updateNode(pad.id, data as Partial)) + }) + } + + test('strict mutation validation also refuses a collapsed raw create', () => { + const { site, pad } = fixture() + expectAtomicRefusal(() => + useScene.getState().createNode( + { + ...pad, + id: 'terrain-break_collapsed', + line: collapsed, + }, + site.id, + ), + ) + }) +}) diff --git a/packages/core/src/store/use-live-node-overrides.ts b/packages/core/src/store/use-live-node-overrides.ts index 4ca2abe779..28370250da 100644 --- a/packages/core/src/store/use-live-node-overrides.ts +++ b/packages/core/src/store/use-live-node-overrides.ts @@ -1,5 +1,5 @@ import { create } from 'zustand' -import { livePreviewsVisible } from './live-previews' +import { livePreviewsVisible } from '../lib/live-previews' export type LiveNodeOverrides = Record diff --git a/packages/core/src/store/use-live-terrain.ts b/packages/core/src/store/use-live-terrain.ts index 0ea486c4ea..4480a6458b 100644 --- a/packages/core/src/store/use-live-terrain.ts +++ b/packages/core/src/store/use-live-terrain.ts @@ -1,5 +1,6 @@ import { create } from 'zustand' import type { HeightPatch, TerrainField } from '../lib/terrain-field' +import { setTerrainLiveSource } from '../lib/terrain-source' /** * In-progress terrain edits, held as a live `TerrainField` rather than as node @@ -24,6 +25,14 @@ import type { HeightPatch, TerrainField } from '../lib/terrain-field' */ export type LiveTerrainStroke = { + /** + * Identity of this stroke, unique per `begin`. This is how a caller holding + * a stroke across an async gap (the sculpt tool between pointer-down and + * pointer-up) tells "my stroke is still the live one" from "my stroke was + * ended or superseded meanwhile" — the difference between committing and + * silently overwriting the write that replaced it. + */ + readonly id: number /** The field as it was at pointer-down. Never mutated during the stroke. */ readonly snapshot: TerrainField /** The field as of the most recent dab — what the renderer and readers see. */ @@ -61,7 +70,7 @@ type LiveTerrainState = { * only ever comes from a deliberate stroke boundary. Callers own the boundary — * `end` first, or don't begin. */ - begin(siteId: string, field: TerrainField): void + begin(siteId: string, field: TerrainField): number /** Record a dab. `field` must be the result of applying `patch`. */ advance(siteId: string, field: TerrainField, patch: HeightPatch): void /** The live field for a site, or undefined when no stroke is in flight. */ @@ -76,16 +85,21 @@ type LiveTerrainState = { endAll(): void } +let nextStrokeId = 1 + const useLiveTerrain = create((set, get) => ({ strokes: new Map(), remoteStrokes: new Map(), - begin: (siteId, field) => + begin: (siteId, field) => { + const id = nextStrokeId++ set((state) => { const next = new Map(state.strokes) - next.set(siteId, { snapshot: field, field, lastPatch: null }) + next.set(siteId, { id, snapshot: field, field, lastPatch: null }) return { strokes: next } - }), + }) + return id + }, advance: (siteId, field, patch) => set((state) => { @@ -95,7 +109,7 @@ const useLiveTerrain = create((set, get) => ({ // model and reintroduce compounding. if (!current) return state const next = new Map(state.strokes) - next.set(siteId, { snapshot: current.snapshot, field, lastPatch: patch }) + next.set(siteId, { id: current.id, snapshot: current.snapshot, field, lastPatch: patch }) return { strokes: next } }), @@ -143,4 +157,6 @@ const useLiveTerrain = create((set, get) => ({ ), })) +setTerrainLiveSource((siteId) => useLiveTerrain.getState().fieldOf(siteId)) + export default useLiveTerrain diff --git a/packages/core/src/systems/document-reconcile.ts b/packages/core/src/systems/document-reconcile.ts index f3d754ce56..41f047c310 100644 --- a/packages/core/src/systems/document-reconcile.ts +++ b/packages/core/src/systems/document-reconcile.ts @@ -4,6 +4,7 @@ import { supportIndexOf, withSpatialGrid, } from '../hooks/spatial-grid/spatial-grid-manager' +import { withoutLivePreviews } from '../lib/live-previews' import { resolveLevelId } from '../lib/node-ancestry' import { structureLevelsForChange } from '../lib/space-detection' import { applyStructureReconciliation } from '../lib/structure-commit' @@ -12,7 +13,6 @@ import type { AnyNode, AnyNodeId } from '../schema' import { generateId } from '../schema/base' import { roofsKeptOverStorey } from '../services/roof-move' import { pauseSceneHistory, resumeSceneHistory } from '../store/history-control' -import { withoutLivePreviews } from '../store/live-previews' import type { SceneStore } from '../store/use-scene' import { planOwnedFloorOpenings } from './owned-floor-openings' import { reconcileOwnedFloorOpeningChanges } from './reconcile-owned-floor-openings' diff --git a/packages/core/src/systems/stair/stair-base-elevation.ts b/packages/core/src/systems/stair/stair-base-elevation.ts index 50eeb12d16..1054858cbb 100644 --- a/packages/core/src/systems/stair/stair-base-elevation.ts +++ b/packages/core/src/systems/stair/stair-base-elevation.ts @@ -2,6 +2,7 @@ import { GROUND_SUPPORT_ID } from '../../hooks/spatial-grid/support-host-id' import { itemOverlapsPolygon } from '../../lib/item-polygon-overlap' import { resolveLevelId } from '../../lib/node-ancestry' import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import { slabTerrainHeightAt } from '../../lib/slab-terrain' import { levelBaseElevationAt } from '../../lib/terrain-support-query' import type { AnyNode, SlabNode, StairNode, WallNode } from '../../schema' import { pointInPolygon } from '../slab/slab-support' @@ -48,8 +49,10 @@ export function stairBaseElevation( ) && !(slab.holes ?? []).some((hole) => pointInPolygon(position[0], position[2], hole)) ) } - const elevation = (slab: SlabNode) => - Number.isFinite(slab.elevation ?? 0.05) ? (slab.elevation ?? 0.05) : 0 + const elevation = (slab: SlabNode) => { + const sampled = slabTerrainHeightAt(slab, nodes, stair.position[0], stair.position[2]) + return Number.isFinite(sampled) ? sampled : 0 + } const host = slabs.find((slab) => slab.id === stair.supportSlabId) if (host && footprints.some((footprint) => supports(host, footprint))) return stair.position[1] + elevation(host) diff --git a/packages/core/src/systems/stair/stair-rise-query.ts b/packages/core/src/systems/stair/stair-rise-query.ts index 6244b5585f..fab3e900f6 100644 --- a/packages/core/src/systems/stair/stair-rise-query.ts +++ b/packages/core/src/systems/stair/stair-rise-query.ts @@ -1,4 +1,5 @@ import { containsPoint } from '../../lib/polygon-boolean' +import { slabTerrainHeightAt } from '../../lib/slab-terrain' import { queryNodes } from '../../runtime/node-queries' import type { AnyNode, AnyNodeId, LevelNode, StairNode, StairSegmentNode } from '../../schema' import { StairDesignTargets } from '../../schema/nodes/stair-design-targets' @@ -40,12 +41,25 @@ export function resolveStairTotalRise( // systems do (persisted `supportSlabId` honored, uncapped election // otherwise) keeps base + rise landing precisely on the destination surface. const baseElevation = baseElevationFor(stair, nodes, level?.id ?? null) + const arrivalPoint = (): [number, number] => { + const opening = stairArrivalOpening(stair, nodes) + return opening.length + ? [ + opening.reduce((sum, vertex) => sum + vertex[0], 0) / opening.length, + opening.reduce((sum, vertex) => sum + vertex[1], 0) / opening.length, + ] + : [stair.position[0], stair.position[2]] + } if (stair.deckSlabId) { - // The deck's `elevation` IS its walking surface (level-local). A stale + // Sample the deck's walking surface at the arrival, not the stair's base. A stale // reference (deck gone) falls through to the level-derived rise. const deck = nodes[stair.deckSlabId] - if (deck?.type === 'slab') return (deck.elevation ?? 0.05) - baseElevation + if (deck?.type === 'slab') { + const point: [number, number] = + deck.terrainMode === 'draped' ? arrivalPoint() : [stair.position[0], stair.position[2]] + return slabTerrainHeightAt(deck, nodes, point[0], point[1]) - baseElevation + } } if (!level) return DEFAULT_LEVEL_HEIGHT @@ -63,13 +77,7 @@ export function resolveStairTotalRise( : findLevelAboveId(level.id, elevations) if (!destinationId) return getLevelFloorToFloorHeight(level.id, nodes as Record) - baseElevation - const opening = stairArrivalOpening(stair, nodes) - const point: [number, number] = opening.length - ? [ - opening.reduce((sum, vertex) => sum + vertex[0], 0) / opening.length, - opening.reduce((sum, vertex) => sum + vertex[1], 0) / opening.length, - ] - : [stair.position[0], stair.position[2]] + const point = arrivalPoint() const covers = (polygon: [number, number][], holes: [number, number][][]) => containsPoint([{ outer: polygon, holes }], point) const room = Object.values(nodes).find( From b0e3deda1b1e3bd467ca5c8e9072780302422c53 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 16 Nov 2026 21:07:02 +0100 Subject: [PATCH 02/11] core: the terrain agent operations and tools Sixteen shared tools in AGENT_TOOL_CONTRACTS, with their operations: - reads: read_site_terrain, sample_terrain_line, read_terrain_contours, describe_terrain_under_house, read_terrain_facts; - writes: set_site_lot, shape_site_terrain, carve_terrain_pad, grade_around_house, add_terrain_break, add_ramp, seat_house (strategies: balance, walk-out, hillside, areaway, retaining), set_terrain_plane, grade_along_line, add_steps_to_ground, add_terraces. verify_scene reports terrain_break_straddled (a slab or a wall across a break, with both sides' heights and the drop); get_node on a break or a site adds the break facts; delete_node of a ramp gives its ground back. A walk-out's ground level is no longer called unseated by verify_scene. No switch: the in-page panel lists core's contracts, so it serves these tools as soon as they are here. The lab's tool switch is not in this repository. Differs from the lab: the roof-wall guards are left out of the unguarded-drop reading (they need the lab's roof body), the zone-along-wall stretches the terrain facts read are a small file of their own, six tools read lengths in metres only (METRES_ONLY_TOOLS: the one notation, N1, is owed on them), and five tests that need add_site_surface or add_steps (siblings not carried) are skipped with the reason. get_site past a far-off field reads the field's context plane, as the lab changed that case. Co-Authored-By: Claude Opus 5.5 --- .../__fixtures__/notation-cases.ts | 22 + .../__fixtures__/site-cases.ts | 7 +- .../__fixtures__/sloped-lots.ts | 292 +++ .../__fixtures__/terraforming-cases.ts | 205 ++ .../__fixtures__/terrain-cases.ts | 238 +++ .../agent-operations/circulation-geometry.ts | 10 +- .../agent-operations/circulation-spaces.ts | 15 +- .../core/src/agent-operations/delete-node.ts | 19 +- .../core/src/agent-operations/get-node.ts | 10 + packages/core/src/agent-operations/index.ts | 45 + .../src/agent-operations/layout-clearance.ts | 10 +- packages/core/src/agent-operations/ramp.ts | 56 + .../src/agent-operations/set-site-lot.test.ts | 168 ++ .../core/src/agent-operations/set-site-lot.ts | 98 + .../src/agent-operations/terraces.test.ts | 276 +++ .../core/src/agent-operations/terraces.ts | 354 ++++ .../src/agent-operations/terraforming.test.ts | 1346 +++++++++++++ .../core/src/agent-operations/terraforming.ts | 1374 +++++++++++++ .../agent-operations/terrain-break-facts.ts | 18 + .../terrain-break-observations.test.ts | 166 ++ .../terrain-break-observations.ts | 182 ++ .../src/agent-operations/terrain-break.ts | 89 + .../agent-operations/terrain-breaks.test.ts | 317 +++ .../agent-operations/terrain-facts.test.ts | 498 +++++ .../src/agent-operations/terrain-facts.ts | 1437 ++++++++++++++ .../terrain-flat-ground.test.ts | 223 +++ .../terrain-flat-writes.test.ts | 146 ++ .../terrain-grade-stacked.test.ts | 80 + .../agent-operations/terrain-grade.test.ts | 878 ++++++++ .../src/agent-operations/terrain-grade.ts | 729 +++++++ .../terrain-seated-ground.test.ts | 54 + .../agent-operations/terrain-shaping.test.ts | 850 ++++++++ .../agent-operations/terrain-soil-pad.test.ts | 278 +++ .../core/src/agent-operations/terrain.test.ts | 352 ++++ packages/core/src/agent-operations/terrain.ts | 1763 +++++++++++++++++ .../unguarded-drop-observations.ts | 693 +++++++ .../core/src/agent-operations/verify-scene.ts | 16 +- packages/core/src/agent-tools/index.ts | 39 + .../core/src/agent-tools/notation.test.ts | 12 +- packages/core/src/agent-tools/ramp.ts | 67 + packages/core/src/agent-tools/terraforming.ts | 643 ++++++ packages/core/src/agent-tools/terrain.ts | 526 +++++ .../core/src/building/zone-wall-stretches.ts | 26 + 43 files changed, 14612 insertions(+), 15 deletions(-) create mode 100644 packages/core/src/agent-operations/__fixtures__/sloped-lots.ts create mode 100644 packages/core/src/agent-operations/__fixtures__/terraforming-cases.ts create mode 100644 packages/core/src/agent-operations/__fixtures__/terrain-cases.ts create mode 100644 packages/core/src/agent-operations/ramp.ts create mode 100644 packages/core/src/agent-operations/set-site-lot.test.ts create mode 100644 packages/core/src/agent-operations/set-site-lot.ts create mode 100644 packages/core/src/agent-operations/terraces.test.ts create mode 100644 packages/core/src/agent-operations/terraces.ts create mode 100644 packages/core/src/agent-operations/terraforming.test.ts create mode 100644 packages/core/src/agent-operations/terraforming.ts create mode 100644 packages/core/src/agent-operations/terrain-break-facts.ts create mode 100644 packages/core/src/agent-operations/terrain-break-observations.test.ts create mode 100644 packages/core/src/agent-operations/terrain-break-observations.ts create mode 100644 packages/core/src/agent-operations/terrain-break.ts create mode 100644 packages/core/src/agent-operations/terrain-breaks.test.ts create mode 100644 packages/core/src/agent-operations/terrain-facts.test.ts create mode 100644 packages/core/src/agent-operations/terrain-facts.ts create mode 100644 packages/core/src/agent-operations/terrain-flat-ground.test.ts create mode 100644 packages/core/src/agent-operations/terrain-flat-writes.test.ts create mode 100644 packages/core/src/agent-operations/terrain-grade-stacked.test.ts create mode 100644 packages/core/src/agent-operations/terrain-grade.test.ts create mode 100644 packages/core/src/agent-operations/terrain-grade.ts create mode 100644 packages/core/src/agent-operations/terrain-seated-ground.test.ts create mode 100644 packages/core/src/agent-operations/terrain-shaping.test.ts create mode 100644 packages/core/src/agent-operations/terrain-soil-pad.test.ts create mode 100644 packages/core/src/agent-operations/terrain.test.ts create mode 100644 packages/core/src/agent-operations/terrain.ts create mode 100644 packages/core/src/agent-operations/unguarded-drop-observations.ts create mode 100644 packages/core/src/agent-tools/ramp.ts create mode 100644 packages/core/src/agent-tools/terraforming.ts create mode 100644 packages/core/src/agent-tools/terrain.ts create mode 100644 packages/core/src/building/zone-wall-stretches.ts diff --git a/packages/core/src/agent-operations/__fixtures__/notation-cases.ts b/packages/core/src/agent-operations/__fixtures__/notation-cases.ts index 46cf272a66..776951214e 100644 --- a/packages/core/src/agent-operations/__fixtures__/notation-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/notation-cases.ts @@ -321,6 +321,19 @@ export const NOTATION_CASES: NotationCase[] = [ }, ] +/** + * The terrain and ramp tools whose lengths still read their own unit only (metres): the one notation (N1) + * is owed on them. Their bare numbers are not listed one by one. + */ +export const METRES_ONLY_TOOLS = new Set([ + 'add_ramp', + 'add_terrain_break', + 'read_site_terrain', + 'read_terrain_contours', + 'sample_terrain_line', + 'shape_site_terrain', +]) + /** * Every other number a shared tool takes by name, none of them a length or an angle. Numbers in * an array are coordinates (points, outlines, vectors) and whole numbers are counts, indices or @@ -365,6 +378,15 @@ export const NOT_LENGTHS = new Set([ 'create_room.doors[].t', 'create_room.windows[].t', // Ratios, a material's own properties, a duration. + // A batter's run: horizontal metres per metre of height (2 is 1:2), a ratio. + 'grade_around_house.run', + 'seat_house.run', + 'grade_along_line.run', + 'add_terraces.run', + 'add_terraces.stepsAt', + // A fall or a grade, in percent. + 'seat_house.padFallPercent', + 'grade_along_line.maxSlopePercent', 'view_scene.camera.aspect', 'paint.material.properties.roughness', 'paint.material.properties.metalness', diff --git a/packages/core/src/agent-operations/__fixtures__/site-cases.ts b/packages/core/src/agent-operations/__fixtures__/site-cases.ts index 7832a3b9cc..a1b7be2925 100644 --- a/packages/core/src/agent-operations/__fixtures__/site-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/site-cases.ts @@ -292,8 +292,9 @@ export const GET_SITE_CASES: AgentToolCase[] = [ { name: 'a terrain far off the lot, its samples 10 nm apart: read over the field’s own lines', tool: 'get_site', - // past the field heightAt holds its edge, so the lot's lines cross only the field's few grid - // lines, not the 10^24 between the lot and the field; the field's west column rises 2 m + // the lot's lines cross only the field's few grid lines, not the 10^24 between the lot and + // the field. Past the field the ground continues as the field's own context plane (virtual + // ground, not its edge held), which is flat: the lot far from the field reads 0 m of fall. scene: () => { const field = createTerrainField({ origin: [1e16, 0], spacing: 1e-8, cols: 2, rows: 2 }) field.heights[2] = quantize(field, 2) @@ -301,7 +302,7 @@ export const GET_SITE_CASES: AgentToolCase[] = [ return scene(site({ polygon: STRAIGHT.polygon, terrain }), building(), level()) }, input: {}, - expect: { result: { ground: { state: 'sloped', reliefM: 2 } } }, + expect: { result: { ground: { state: 'sloped', reliefM: 0 } } }, }, { name: 'a terrain finer than the coordinates can hold: the fall heightAt shows, not its samples', diff --git a/packages/core/src/agent-operations/__fixtures__/sloped-lots.ts b/packages/core/src/agent-operations/__fixtures__/sloped-lots.ts new file mode 100644 index 0000000000..5f78b323e2 --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/sloped-lots.ts @@ -0,0 +1,292 @@ +import { encodeTerrainField } from '../../lib/terrain-codec' +import { createTerrainField, heightAt } from '../../lib/terrain-field' +import { persistedTerrainFieldOf } from '../../lib/terrain-source-persisted' +import { + type AnyNode, + BuildingNode, + DoorNode, + LevelNode, + SiteNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../schema' +import { generateId } from '../../schema/base' +import { reconcileSceneStructure } from '../../lib/structure-reconcile' +import { filterDerivedNodeWrites } from '../../store/derived-node-guard' +import { applySceneChanges } from '../apply-changes' +import { applyAgentOutcome } from '../apply-outcome' +import { AGENT_OPERATIONS } from '../index' +import type { AgentOperation, SceneChanges, SceneNodes } from '../types' + +/** + * Sloped lots and a small house on them, for the rules of seating a house on the ground. The lot is + * 30 x 40 m (x -15..15, z -20..20), its street on +z; the house is a 12 x 8 m plate (building-local + * x -6..6, z -4..4) whose front wall (z = +4) faces the street, with a front and a rear door. + */ + +export type Pt = [number, number] +export type Ground = (x: number, z: number) => number + +export const LOT: Pt[] = [ + [-15, -20], + [15, -20], + [15, 20], + [-15, 20], +] +export const PLATE: Pt[] = [ + [-6, -4], + [6, -4], + [6, 4], + [-6, 4], +] + +/** Natural grounds, metres above the datum at site-frame (x, z). `null` is a site nobody shaped. */ +export const GROUNDS = { + flat: null, + /** 2 m of fall from the street to the rear, the datum at the street: -1 m under the house. */ + fallToRear: ((_x, z) => (z - 20) / 20) as Ground, + /** 2 m of rise from the street to the rear, the datum at the street: +1 m under the house. */ + riseToRear: ((_x, z) => (20 - z) / 20) as Ground, + /** A cross slope: +1 m at x = +15, -1 m at x = -15, the datum under the house. */ + cross: ((x) => x / 15) as Ground, + /** A hillside, 20 %, rising to the rear, the datum under the house. */ + steep: ((_x, z) => -z * 0.2) as Ground, +} as const + +export type SlopedHouse = { + ground?: Ground | null + /** The building's place on the site and its turn about the vertical, radians. */ + at?: [number, number, number] + turn?: number + /** Top of the floor slab over the level's plane. */ + slabElevation?: number + /** Leave the house out: the lot alone. */ + house?: boolean + doors?: boolean + extra?: AnyNode[] +} + +function link(nodes: AnyNode[]): Record { + const byId = Object.fromEntries(nodes.map((node) => [node.id, { ...node }])) as Record< + string, + AnyNode & { children?: string[] } + > + for (const node of Object.values(byId)) { + const parent = node.parentId ? byId[node.parentId] : undefined + if (parent && Array.isArray(parent.children) && !parent.children.includes(node.id)) + parent.children = [...parent.children, node.id] + } + return byId +} + +export function slopedLot({ + ground = null, + at = [0, 0, 0], + turn = 0, + slabElevation = 0.15, + house = true, + doors = true, + extra = [], +}: SlopedHouse = {}): Record { + let terrain: ReturnType | undefined + if (ground) { + const field = createTerrainField({ origin: [-20, -24], spacing: 0.5, cols: 81, rows: 97 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = Math.round( + ground(-20 + col * 0.5, -24 + row * 0.5) / field.step, + ) + terrain = encodeTerrainField(field) + } + const site = SiteNode.parse({ + id: 'site_lot', + polygon: { type: 'polygon', points: LOT }, + frontEdge: 2, + ...(terrain ? { terrain } : {}), + }) + if (!house) return link([site, ...extra]) + const names = ['rear', 'right', 'front', 'left'] + return link([ + site, + BuildingNode.parse({ + id: 'building_house', + parentId: site.id, + position: at, + rotation: [0, turn, 0], + }), + LevelNode.parse({ + id: 'level_ground', + parentId: 'building_house', + level: 0, + name: 'Ground floor', + height: 2.7, + }), + ...PLATE.map((start, i) => + WallNode.parse({ + id: `wall_${names[i]}`, + parentId: 'level_ground', + start, + end: PLATE[(i + 1) % 4], + height: 2.7, + frontSide: 'exterior', + }), + ), + SlabNode.parse({ + id: 'slab_floor', + parentId: 'level_ground', + polygon: PLATE, + elevation: slabElevation, + }), + ZoneNode.parse({ + id: 'zone_living', + parentId: 'level_ground', + name: 'Living', + spaceRole: 'room', + polygon: PLATE, + }), + ...(doors + ? [ + // The front wall runs from [6, 4] to [-6, 4]: 6 m along it is x = 0. + DoorNode.parse({ + id: 'door_front', + parentId: 'wall_front', + wallId: 'wall_front', + position: [6, 1.05, 0], + }), + // The rear wall runs from [-6, -4] to [6, -4]: 9 m along it is x = 3. + DoorNode.parse({ + id: 'door_rear', + parentId: 'wall_rear', + wallId: 'wall_rear', + position: [9, 1.05, 0], + }), + ] + : []), + ...extra, + ]) +} + +/** + * One tool through the executor every surface shares, on a scene of drawn nodes: the outcome is + * applied and the operation answers. Nothing is derived afterwards: the hand-built house of + * `slopedLot` is what it is drawn as. + */ +export function runTool( + nodes: SceneNodes, + tool: string, + input: Record = {}, +): { nodes: Record; result: Record } { + return run(nodes, tool, input, (scene) => scene) +} + +/** + * One tool as both surfaces run it on a scene the editor made: the outcome is applied, the scene + * settles through the pure reconciler (a floor that rests on the ground takes its height there) + * and the operation answers once it has. For `agentHouse`. + */ +export function runSettled( + nodes: SceneNodes, + tool: string, + input: Record = {}, +): { nodes: Record; result: Record } { + return run(nodes, tool, input, settle) +} + +/** + * One tool as the editor's own store takes it: the write passes the store's rules for derived + * nodes first (a patch to a floor plate is read as an intent and expanded), then settles. + */ +export function runInStore( + nodes: SceneNodes, + tool: string, + input: Record = {}, +): { nodes: Record; result: Record } { + return run(nodes, tool, input, settle, true) +} + +function run( + nodes: SceneNodes, + tool: string, + input: Record, + settled: (nodes: Record) => Record, + storeRules = false, +) { + const operation = (AGENT_OPERATIONS as Record>)[tool] + if (!operation) throw new Error(`no operation ${tool}`) + let after = nodes as Record + const outcome = operation(nodes, input as never, { activeLevelId: null }) + const result = applyAgentOutcome(outcome, { + getNodes: () => after, + applyChanges: (changes) => { + after = applySceneChanges( + after, + storeRules ? (filterDerivedNodeWrites(after, changes as never) as SceneChanges) : changes, + ) as Record + }, + reconcile: () => { + after = settled(after) + }, + }) + return { nodes: outcome.changes ? settled(after) : after, result } +} + +/** + * The scene as it settles after a write: rooms, floor plates and what derives from them. A new + * record, as a store hands one out: the reconciler reads wall supports while it works, and those + * reads are remembered against the record it returns, from before a floor plate took its height. + */ +export function settle(nodes: SceneNodes): Record { + return { + ...(reconcileSceneStructure({ nodes, mintId: (kind) => generateId(kind) }).nodes as Record< + string, + AnyNode + >), + } +} + +/** + * The same lot with a house made the way an agent makes one: `create_room` on an empty level, so + * its floor is an automatic plate that rests on the ground and follows it, and its walls stand on + * that floor up to the storey's top. One room on the plate, a door in the front wall (toward the + * street) and one in the rear wall; ids are the editor's own. + */ +export function agentHouse(options: Omit = {}) { + const bare = slopedLot({ ...options, house: false }) + const site = bare.site_lot as SiteNode + const building = BuildingNode.parse({ + id: 'building_house', + parentId: site.id, + position: options.at ?? [0, 0, 0], + rotation: [0, options.turn ?? 0, 0], + children: ['level_ground'], + }) + const level = LevelNode.parse({ + id: 'level_ground', + parentId: building.id, + level: 0, + name: 'Ground floor', + height: 2.7, + }) + const empty = settle({ + ...bare, + [site.id]: { ...site, children: [...(site.children ?? []), building.id] } as AnyNode, + [building.id]: building, + [level.id]: level, + }) + return runSettled(empty, 'create_room', { + levelId: 'level_ground', + name: 'Living', + polygon: PLATE, + doors: [ + { wallIndex: 2, t: 0.5 }, + { wallIndex: 0, t: 0.75 }, + ], + }).nodes +} + +/** The ground at a site-frame point: the persisted field, or the datum where nobody shaped any. */ +export function groundAt(nodes: SceneNodes, x: number, z: number): number { + const field = persistedTerrainFieldOf(nodes.site_lot as SiteNode, nodes) + return field ? heightAt(field, x, z) : 0 +} diff --git a/packages/core/src/agent-operations/__fixtures__/terraforming-cases.ts b/packages/core/src/agent-operations/__fixtures__/terraforming-cases.ts new file mode 100644 index 0000000000..0c6698e9df --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/terraforming-cases.ts @@ -0,0 +1,205 @@ +import type { AgentToolCase, SceneGraph } from './cases' +import { agentHouse, GROUNDS, type Ground, slopedLot } from './sloped-lots' + +/** The terraforming set on every surface: one answer and one refusal each, on the sloped lots. */ + +const lot = (ground: Ground | null, house = true) => (): SceneGraph => ({ + nodes: slopedLot({ ground, house }), + rootNodeIds: ['site_lot'], +}) +const codes = (result: Record) => + (result.open as { code: string }[]).map((finding) => finding.code) + +export const TERRAFORMING_CASES: AgentToolCase[] = [ + { + name: 'terrain facts: a house 1 m over a falling lot is in the air, its doors over the ground', + tool: 'read_terrain_facts', + scene: lot(GROUNDS.fallToRear), + input: { section: { from: [0, -20], to: [0, 20] } }, + expect: { + result: { hasTerrain: true }, + check: (result) => { + const open = codes(result) + const section = result.section as { ground: unknown[]; floors: unknown[] } + return [ + ...(open.includes('floor_in_air') ? [] : ['no floor_in_air']), + ...(open.filter((code) => code === 'door_above_ground').length === 2 + ? [] + : ['not two doors above the ground']), + ...(section.ground.length === 2 && section.floors.length === 1 + ? [] + : ['the section is not a plane under one floor']), + ] + }, + }, + }, + { + name: 'terrain facts: a flat site answers against the datum, nothing open', + tool: 'read_terrain_facts', + scene: lot(GROUNDS.flat), + input: {}, + expect: { + result: { hasTerrain: false, open: [] }, + mentions: ['flat datum'], + }, + }, + { + name: 'terrain facts need a site', + tool: 'read_terrain_facts', + scene: () => ({ nodes: {}, rootNodeIds: [] }), + input: {}, + expect: { refusal: 'no_site' }, + }, + { + name: 'seat_house balances cut and fill and leaves nothing open', + tool: 'seat_house', + // A house the editor made: its floor rests on the ground, and the scene settles after the seat. + scene: () => ({ nodes: agentHouse({ ground: GROUNDS.fallToRear }), rootNodeIds: ['site_lot'] }), + input: {}, + expect: { + result: { strategy: 'balance', levelId: 'level_ground', buildingId: 'building_house' }, + check: (result) => { + const after = result.after as { open: unknown[] } + const earth = (result.cutVolumeM3 as number) + (result.fillVolumeM3 as number) + return [ + ...(after.open.length ? [`open after seating: ${JSON.stringify(after.open)}`] : []), + ...(earth < 40 ? [] : [`${earth} m3 moved`]), + ...(Math.abs((result.movedBuildingByM as number) + 1) < 0.12 + ? [] + : [`moved ${result.movedBuildingByM}`]), + ] + }, + }, + }, + { + name: 'seat_house takes a strategy or a ground height, not both', + tool: 'seat_house', + scene: lot(GROUNDS.fallToRear), + input: { strategy: 'fill', groundM: 1 }, + expect: { refusal: 'invalid_input' }, + }, + { + name: 'set_terrain_plane tilts a lot through two points', + tool: 'set_terrain_plane', + scene: lot(GROUNDS.flat, false), + input: { + area: [ + [-15, -20], + [15, -20], + [15, 20], + [-15, 20], + ], + through: [ + { at: [0, 20], heightM: 0 }, + { at: [0, -20], heightM: -2 }, + ], + }, + expect: { result: { slopePercent: 5, fallDirection: [0, -1], minM: -2, maxM: 0 } }, + }, + { + name: 'set_terrain_plane refuses three points in a line', + tool: 'set_terrain_plane', + scene: lot(GROUNDS.flat, false), + input: { + area: { center: [0, 0], radiusM: 5 }, + through: [ + { at: [0, 0], heightM: 0 }, + { at: [1, 1], heightM: 1 }, + { at: [2, 2], heightM: 3 }, + ], + }, + expect: { refusal: 'invalid_input' }, + }, + { + name: 'grade_along_line lowers a swale and answers its outline', + tool: 'grade_along_line', + scene: lot(GROUNDS.flat, false), + input: { + line: [ + [-10, 0], + [10, 0], + ], + widthM: 1, + offsetM: -0.3, + }, + expect: { + result: { lengthM: 20, startM: -0.3, endM: -0.3, steepestPercent: 0, deepestCutM: 0.3 }, + check: (result) => + (result.outline as unknown[]).length === 4 ? [] : ['the outline is not four corners'], + }, + }, + { + name: 'grade_along_line refuses a slope limit the ends cannot hold', + tool: 'grade_along_line', + scene: lot(GROUNDS.steep, false), + input: { + line: [ + [10, 20], + [10, 5], + ], + maxSlopePercent: 12, + }, + expect: { refusal: 'slope_limit_unreachable', mentions: ['25.0 m'] }, + }, + { + name: 'add_steps_to_ground solves the flight from the sill and the ground', + tool: 'add_steps_to_ground', + scene: lot(GROUNDS.fallToRear), + input: { doorId: 'door_front' }, + expect: { + result: { doorId: 'door_front', stepCount: 5, sillM: 0.15 }, + check: (result) => + Math.abs((result.riseM as number) - ((result.sillM as number) - (result.groundAtFootM as number))) < 0.01 + ? [] + : ['the rise is not sill minus ground at the foot'], + }, + }, + { + name: 'add_terraces cuts a slope into terraces that touch, each second one a retaining break', + tool: 'add_terraces', + scene: lot(GROUNDS.steep, false), + input: { + line: [ + [0, -12], + [0, 0], + ], + widthM: 8, + count: 3, + }, + expect: { + result: { changedSamples: 380 }, + check: (result) => { + const terraces = result.terraces as { levelM: number; heldAs: string }[] + return [ + ...(terraces.map((terrace) => terrace.heldAs).join() === 'break,lattice,break' + ? [] + : ['the terraces do not alternate break and lattice']), + ...(terraces.map((terrace) => terrace.levelM).join() === '2,1.2,0.4' + ? [] + : [`levels ${terraces.map((terrace) => terrace.levelM).join()}`]), + ] + }, + }, + }, + { + name: 'add_terraces refuses terraces under 1.5 m deep', + tool: 'add_terraces', + scene: lot(GROUNDS.steep, false), + input: { + line: [ + [0, -12], + [0, 0], + ], + widthM: 8, + count: 12, + }, + expect: { refusal: 'invalid_input', mentions: ['1.5 m'] }, + }, + { + name: 'add_steps_to_ground refuses a door the ground stands over', + tool: 'add_steps_to_ground', + scene: lot(GROUNDS.riseToRear), + input: { doorId: 'door_front' }, + expect: { refusal: 'door_below_ground' }, + }, +] diff --git a/packages/core/src/agent-operations/__fixtures__/terrain-cases.ts b/packages/core/src/agent-operations/__fixtures__/terrain-cases.ts new file mode 100644 index 0000000000..07e213fb9b --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/terrain-cases.ts @@ -0,0 +1,238 @@ +import { encodeTerrainField } from '../../lib/terrain-codec' +import { createTerrainField, heightAt } from '../../lib/terrain-field' +import { persistedTerrainFieldOf } from '../../lib/terrain-source-persisted' +import { type AnyNode, BuildingNode, LevelNode, SiteNode, SlabNode } from '../../schema' +import type { AgentToolCase, SceneGraph } from './cases' + +/** y = x - 3 on a 9 × 9 field; the lot stays a spacing inside its border. */ +export function terrainRampScene(scale = 1): SceneGraph { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = (col - 3) * 100 * scale + const site = SiteNode.parse({ + id: 'site_terrain', + polygon: { type: 'polygon', points: [[1, 1], [5, 1], [5, 5], [1, 5]] }, + terrain: encodeTerrainField(field), + }) + return { nodes: { [site.id]: site }, rootNodeIds: [site.id] } +} + +/** A site nobody has shaped: no `terrain`, so its ground is the datum plane. */ +function unshapedSiteScene(): SceneGraph { + const site = SiteNode.parse({ id: 'site_empty' }) + return { nodes: { [site.id]: site }, rootNodeIds: [site.id] } +} + +/** The ramp lot with a raised slab (top 1.6 m) over cols/rows 2..4 of the field. */ +export function terrainHouseScene(): SceneGraph { + const { nodes } = terrainRampScene() + const site = nodes.site_terrain as SiteNode + const building = BuildingNode.parse({ + id: 'building_house', + parentId: site.id, + children: ['level_house'], + }) + const level = LevelNode.parse({ + id: 'level_house', + parentId: building.id, + level: 0, + height: 3, + children: ['slab_house'], + }) + const slab = SlabNode.parse({ + id: 'slab_house', + parentId: level.id, + boundary: 'auto', + polygon: [[2, 2], [4, 2], [4, 4], [2, 4]], + elevation: 1.6, + }) + return { + nodes: { + [site.id]: { ...site, children: [building.id] }, + [building.id]: building, + [level.id]: level, + [slab.id]: slab, + }, + rootNodeIds: [site.id], + } +} + +export const TERRAIN_CASES: AgentToolCase[] = [ + { + name: 'ramp relief and datum areas are sampled facts', + tool: 'read_site_terrain', scene: terrainRampScene, input: { cellM: 1 }, + expect: { result: { + hasTerrain: true, flat: false, datumM: 0, minM: -2, maxM: 2, reliefM: 4, + slopeMeanDeg: 45, slopeMaxDeg: 45, areaAboveGradeM2: 8, areaBelowGradeM2: 8, + sampling: { approximate: true, cellM: 1, spacingM: 1, heightStepM: 0.01 }, + } }, + }, + { + name: 'line profile includes its endpoints', + tool: 'sample_terrain_line', scene: terrainRampScene, + input: { from: [1, 2], to: [5, 2], stepM: 2 }, + expect: { result: { points: [ + { x: 1, z: 2, yM: -2, slopeDeg: 45 }, + { x: 3, z: 2, yM: 0, slopeDeg: 45 }, + { x: 5, z: 2, yM: 2, slopeDeg: 45 }, + ] } }, + }, + { + name: 'contours report the scene datum and resolution', + tool: 'read_terrain_contours', scene: terrainRampScene, input: { intervalM: 1 }, + expect: { result: { datum: 0, sampling: { approximate: true, intervalM: 1, spacingM: 1 } }, + check: (result) => (result.lines as unknown[]).length ? [] : ['the ramp has no contours'] }, + }, + { + name: 'the house slab reports relief, clearance and advisory guard edges', + tool: 'describe_terrain_under_house', scene: terrainHouseScene, input: {}, + expect: { result: { + levelId: 'level_house', slabId: 'slab_house', slabTopM: 1.6, + highestM: 1, lowestM: -1, reliefM: 2, + guardAdvisory: { advisory: true, thresholdM: 0.5 }, + sampling: { approximate: true, spacingM: 1, heightStepM: 0.01 }, + }, + check: (result) => { + const guarded = result.needsGuardAt as unknown[] + const clearance = result.clearanceUnderSlabM as number + return [ + ...(guarded.length === 4 ? [] : [`${guarded.length} guard edges, not 4`]), + ...(Math.abs(clearance - 0.6) < 1e-9 ? [] : [`clearance ${clearance}, not 0.6`]), + ] + } }, + }, + ...['read_site_terrain', 'sample_terrain_line', 'read_terrain_contours', 'describe_terrain_under_house'].map((tool): AgentToolCase => ({ + name: 'missing site is refused', tool, scene: () => ({ nodes: {}, rootNodeIds: [] }), + input: tool === 'sample_terrain_line' ? { from: [1, 1], to: [2, 1] } : {}, + expect: { refusal: 'no_site' }, + })), + ...['read_site_terrain', 'sample_terrain_line', 'read_terrain_contours'].map((tool): AgentToolCase => ({ + name: 'a site with no shaped ground answers with the flat datum, as facts', tool, + scene: unshapedSiteScene, + input: tool === 'sample_terrain_line' ? { from: [1, 1], to: [2, 1] } : {}, + expect: { result: { + note: 'No relief is shaped on this site: the ground is the flat datum plane at y = 0. Relief is shaped with shape_site_terrain and carve_terrain_pad.', + sampling: { approximate: true, method: 'flat_datum' }, + } }, + })), + { name: 'a site with no shaped ground still needs a slab to describe the ground under', + tool: 'describe_terrain_under_house', scene: unshapedSiteScene, input: {}, + expect: { refusal: 'footprint_empty' } }, + { name: 'empty footprint is refused', tool: 'read_site_terrain', scene: terrainRampScene, + input: { footprint: [] }, expect: { refusal: 'footprint_empty' } }, + { name: 'outside footprint measures continuation rather than clamping', tool: 'read_site_terrain', scene: terrainRampScene, + input: { footprint: [[7, 1], [9, 1], [9, 2], [7, 2]] }, + expect: { result: {}, check: (result) => (result.maxM as number) > 5 ? [] : ['the rising border slope was clamped'] } }, + { name: 'outside line follows continuation rather than clamping', tool: 'sample_terrain_line', scene: terrainRampScene, + input: { from: [1, 2], to: [9, 2] }, + expect: { result: {}, check: (result) => { + const points = result.points as { x: number; yM: number }[] + const last = points.at(-1) + return last?.x === 9 && last.yM > 5 ? [] : ['the continuation endpoint was lost or clamped'] + } } }, + { name: 'tiny cells exceed the sampling budget', tool: 'read_site_terrain', scene: terrainRampScene, + input: { cellM: 0.00001 }, expect: { refusal: 'sampling_limit' } }, + { name: 'tiny line steps exceed the sampling budget', tool: 'sample_terrain_line', scene: terrainRampScene, + input: { from: [1, 2], to: [5, 2], stepM: 0.00001 }, expect: { refusal: 'sampling_limit' } }, + { name: 'too many contours are refused, not reported absent', tool: 'read_terrain_contours', scene: terrainRampScene, + input: { intervalM: 0.001 }, expect: { refusal: 'contour_limit' } }, +] + +const PAD = [[2, 2], [4, 2], [4, 4], [2, 4]] + +function terrainWriteScene(): SceneGraph { + const scene = terrainRampScene() + const field = createTerrainField({ cols: 17, rows: 17, spacing: 0.5 }) + for (let row = 0; row < 17; row++) + for (let col = 0; col < 17; col++) field.heights[row * 17 + col] = (col * 0.5 - 3) * 100 + const site = scene.nodes.site_terrain as SiteNode + return { ...scene, nodes: { ...scene.nodes, [site.id]: { ...site, terrain: encodeTerrainField(field) } } } +} + +function padSamplesAre(nodes: Readonly>, quantized: number): string[] { + const site = nodes.site_terrain as SiteNode | undefined + const field = site ? persistedTerrainFieldOf(site, nodes as Record) : null + if (!field) return ['no persisted field after the write'] + const wrong: string[] = [] + for (let z = 2; z <= 4; z += 0.5) + for (let x = 2; x <= 4; x += 0.5) + if (Math.round(heightAt(field, x, z) / field.step) !== quantized) + wrong.push(`sample ${x},${z} is ${heightAt(field, x, z)} m, not ${quantized} units`) + return wrong +} + +export const TERRAIN_SHAPING_CASES: AgentToolCase[] = [ + { + name: 'a pad is levelled at its height with cut and fill reported', + tool: 'carve_terrain_pad', scene: terrainWriteScene, + input: { pad: PAD, padHeightM: 0, blendM: 1 }, + expect: { result: { padHeightM: 0, padAreaM2: 4, sampling: { approximate: true, spacingM: 0.5 } }, + check: (result, nodes) => [ + ...padSamplesAre(nodes, 0), + ...((result.cutVolumeM3 as number) > 0 && (result.fillVolumeM3 as number) > 0 + ? [] + : ['the ramp pad should both cut and fill']), + ...(Math.abs((result.netM3 as number) - ((result.cutVolumeM3 as number) - (result.fillVolumeM3 as number))) < 1e-9 + ? [] + : ['net is not cut − fill']), + ] }, + }, + { + name: 'flatten sets the samples in a polygon to one height', + tool: 'shape_site_terrain', scene: terrainWriteScene, + input: { verb: 'flatten', area: PAD, heightM: 0.5 }, + expect: { result: { changedSamples: 20, beforeMinMaxM: { minM: -1, maxM: 1 }, afterMinMaxM: { minM: 0.5, maxM: 0.5 } }, + check: (_result, nodes) => padSamplesAre(nodes, 50) }, + }, + { + name: 'raise over a circle moves only its samples', + tool: 'shape_site_terrain', scene: terrainWriteScene, + input: { verb: 'raise', area: { x: 3, z: 3, radiusM: 1 }, heightM: 0.5 }, + expect: { result: { changedSamples: 13 } }, + }, + { + name: 'grading around a house pads it and cuts a batter to the ground behind it', + tool: 'grade_around_house', scene: terrainWriteScene, + input: { footprint: PAD, padHeightM: 0, marginM: 0.5, run: 2, reachM: 3 }, + expect: { result: { padHeightM: 0, marginM: 0.5, run: 2, sampling: { approximate: true, spacingM: 0.5 } }, + check: (result, nodes) => [ + ...padSamplesAre(nodes, 0), + ...((result.cutVolumeM3 as number) > 0 ? [] : ['the rising ground behind the pad was not cut']), + ...(Math.abs((result.netM3 as number) - ((result.cutVolumeM3 as number) - (result.fillVolumeM3 as number))) < 1e-9 + ? [] + : ['net is not cut − fill']), + ] }, + }, + { + name: 'an exact wall around a graded pad is one retaining terrain break written with the ground', + tool: 'grade_around_house', scene: terrainWriteScene, + input: { footprint: PAD, padHeightM: 0, marginM: 0.5, run: 2, reachM: 3, wallM: 0.5, exactWall: true }, + expect: { result: { wall: { heightM: 0.5, exact: true, kind: 'retaining' } }, + check: (_result, nodes) => { + const walls = Object.values(nodes).filter((node) => (node as AnyNode).type === 'terrain-break') as unknown as { kind: string; left: unknown; right: unknown }[] + return walls.length === 1 && walls[0]?.kind === 'retaining' && walls[0]?.left === 0 && walls[0]?.right === 'ground' + ? [] + : [`expected one retaining break with the pad as its numeric side, found ${JSON.stringify(walls)}`] + } }, + }, + { name: 'a pad needs a level or a footprint', tool: 'grade_around_house', scene: terrainWriteScene, + input: { pads: [{ padHeightM: 0 }] }, expect: { refusal: 'invalid_input' } }, + { name: 'a house outline needs its pad height', tool: 'grade_around_house', scene: terrainWriteScene, + input: { footprint: PAD }, expect: { refusal: 'invalid_input' } }, + { name: 'a house outline outside the property is refused', tool: 'grade_around_house', scene: terrainWriteScene, + input: { footprint: [[4, 2], [6, 2], [6, 4], [4, 4]], padHeightM: 0 }, expect: { refusal: 'outside_property' } }, + { name: 'a pad outside the property is refused', tool: 'carve_terrain_pad', scene: terrainWriteScene, + input: { pad: [[4, 2], [6, 2], [6, 4], [4, 4]], padHeightM: 0 }, expect: { refusal: 'outside_property' } }, + { name: 'a shaping area outside the property is refused', tool: 'shape_site_terrain', scene: terrainWriteScene, + input: { verb: 'raise', area: { x: 4.5, z: 3, radiusM: 1 }, heightM: 1 }, expect: { refusal: 'outside_property' } }, + { name: 'a pad holding no sample is too small', tool: 'carve_terrain_pad', scene: terrainWriteScene, + input: { pad: [[2.2, 2.2], [2.4, 2.2], [2.4, 2.4], [2.2, 2.4]], padHeightM: 0 }, expect: { refusal: 'pad_too_small' } }, + { name: 'a write that moves nothing is refused', tool: 'shape_site_terrain', scene: terrainWriteScene, + input: { verb: 'raise', area: PAD, heightM: 0 }, expect: { refusal: 'no_change' } }, + { name: 'flatten without a height is refused', tool: 'shape_site_terrain', scene: terrainWriteScene, + input: { verb: 'flatten', area: PAD }, expect: { refusal: 'invalid_input' } }, + { name: 'shaping a scene with no site is refused', tool: 'shape_site_terrain', + scene: () => ({ nodes: {}, rootNodeIds: [] }), + input: { verb: 'raise', area: PAD, heightM: 1 }, expect: { refusal: 'no_site' } }, +] diff --git a/packages/core/src/agent-operations/circulation-geometry.ts b/packages/core/src/agent-operations/circulation-geometry.ts index cd606c9261..64dd849a1e 100644 --- a/packages/core/src/agent-operations/circulation-geometry.ts +++ b/packages/core/src/agent-operations/circulation-geometry.ts @@ -93,9 +93,11 @@ function geometryGroups(scene: SceneNodes, graph: CirculationGraph) { add( node?.type === 'stair' ? 'incomplete_stairs' - : node?.type === 'door' - ? 'unhosted_doors' - : 'disconnected_surfaces', + : node?.type === 'ramp' + ? 'incomplete_ramps' + : node?.type === 'door' + ? 'unhosted_doors' + : 'disconnected_surfaces', id, ) } @@ -118,6 +120,8 @@ const REASONS: Record string> = { `${n} stair or deck connection${n === 1 ? '' : 's'} cannot be measured between their walking surfaces`, incomplete_stairs: (n) => `${n} stair${n === 1 ? ' has' : 's have'} an incomplete walking path or a missing destination floor`, + incomplete_ramps: (n) => + `${n} ramp${n === 1 ? ' has' : 's have'} invalid or unmeasurable centreline geometry`, unhosted_doors: (n) => `${n} door${n === 1 ? ' has' : 's have'} no wall host`, disconnected_surfaces: (n) => `${n} floor surface${n === 1 ? ' is' : 's are'} split into disconnected walking regions`, diff --git a/packages/core/src/agent-operations/circulation-spaces.ts b/packages/core/src/agent-operations/circulation-spaces.ts index e7de2e4a14..e2854cb3c1 100644 --- a/packages/core/src/agent-operations/circulation-spaces.ts +++ b/packages/core/src/agent-operations/circulation-spaces.ts @@ -12,6 +12,7 @@ import { union, } from '../lib/polygon-boolean' import { polygonInteriorPoint } from '../lib/polygon-label' +import { slabTerrainHeightAt } from '../lib/slab-terrain' import { extractRooms } from '../lib/space-detection' import type { AnyNode, AnyNodeId, ElevatorNode, LevelNode, WallNode } from '../schema' import { getLevelElevations } from '../services/storey' @@ -51,6 +52,7 @@ export type Floor = { holes: Pt[][] elevation: number outdoor: boolean + heightAt?: (point: Pt) => number }[] interior: MultiPolygon voids: Pt[][] @@ -295,7 +297,14 @@ function floorOf(nodes: SceneNodes, level: LevelNode, context: FloorContext): Fl polygon: slab.polygon, holes: slab.holes ?? [], elevation: groundElevation + slab.elevation, - outdoor: outdoor(slab.polygon, slab.holes ?? [], slab.support === 'open'), + outdoor: outdoor( + slab.polygon, + slab.holes ?? [], + slab.support === 'open' || slab.terrainMode === 'draped', + ), + ...(slab.terrainMode === 'draped' + ? { heightAt: (point: Pt) => groundElevation + slabTerrainHeightAt(slab, nodes, ...point) } + : {}), })) const zones = zonesOf(on, context.apartmentOfZone).map((zone) => ground @@ -438,7 +447,9 @@ function outdoorElevation(slabs: Floor['slabs'], point: Pt, groundElevation: num pointInPolygon(point, slab.polygon) && !slab.holes.some((hole) => pointInPolygon(point, hole, false)), ) - return covering.length ? Math.max(...covering.map((slab) => slab.elevation)) : groundElevation + return covering.length + ? Math.max(...covering.map((slab) => slab.heightAt?.(point) ?? slab.elevation)) + : groundElevation } export function spaceElevation(floor: Floor, space: Space, point?: Pt) { diff --git a/packages/core/src/agent-operations/delete-node.ts b/packages/core/src/agent-operations/delete-node.ts index 177af12070..77146714e3 100644 --- a/packages/core/src/agent-operations/delete-node.ts +++ b/packages/core/src/agent-operations/delete-node.ts @@ -1,10 +1,25 @@ import { refuse } from '../agent-tools/refusal' +import { planRampGroundRelease, requireRampChangeBudget } from '../lib/ramp-terrain' +import { applySceneChanges, mergeSceneChanges } from './apply-changes' import { descendantsOf } from './scene-queries' -import type { AgentOperation } from './types' +import type { AgentOperation, SceneChanges } from './types' /** `delete_node`: the editor's Delete, which takes a node with everything under it. */ export const deleteNode: AgentOperation<{ id: string }> = (nodes, { id }) => { if (!nodes[id]) refuse('node_not_found', `Node not found: ${id}.`, { id }) const deletedIds = [id, ...descendantsOf(nodes, id).map((node) => node.id)] - return { result: { deletedIds }, changes: { delete: [id] } } + let working = nodes + const releases: SceneChanges[] = [] + for (const removedId of deletedIds) { + const node = nodes[removedId] + if (node?.type !== 'ramp' || deletedIds.includes(node.terrainEffect?.siteId ?? '')) continue + const release = planRampGroundRelease(node, working) + releases.push(release) + working = applySceneChanges(working, release) + } + const changes = releases.length + ? mergeSceneChanges([...releases, { delete: [id] }]) + : { delete: [id] } + if (releases.length) requireRampChangeBudget(changes, nodes) + return { result: { deletedIds }, changes } } diff --git a/packages/core/src/agent-operations/get-node.ts b/packages/core/src/agent-operations/get-node.ts index 57763f48ca..3d47fcdce9 100644 --- a/packages/core/src/agent-operations/get-node.ts +++ b/packages/core/src/agent-operations/get-node.ts @@ -9,6 +9,7 @@ import { resolveCeilingHeight } from '../services/level-height' import { getWallThickness } from '../systems/wall/wall-footprint' import { wallResolvedHeight } from './level-reads' import { referencedSceneMaterialIds } from './scene-materials' +import { terrainFactsForNode } from './terrain-break-facts' import type { AgentOperation, SceneNodes } from './types' /** @@ -92,6 +93,15 @@ export const getNode: AgentOperation<{ id: string }> = (nodes, { id }, { materia : [] return { result: { + // A terrain break says its facts (line, length, side heights, drops, face area); a site its + // breaks'. A break whose ground does not read leaves them out, never the read. + ...(() => { + try { + return terrainFactsForNode(node, nodes) + } catch { + return {} + } + })(), node: { ...node, ...derivedFields(nodes, node) }, ancestorIds: ancestorIdsOf(nodes, id), ...(missingChildIds.length ? { missingChildIds } : {}), diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index 98ce123966..75ec52f039 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -27,13 +27,33 @@ import { moveRoofsToRoofLevel } from './move-roofs' import { paint } from './paint' import { placeInRoom } from './place-in-room' import { placeItems } from './place-items' +import { addRamp } from './ramp' import { ROOM_OPERATIONS } from './room-structure' import { searchAssets } from './search-assets' import { searchMaterials } from './search-materials' import { setCheckpoint } from './set-checkpoint' import { setGroundLevel } from './set-ground-level' +import { setSiteLot } from './set-site-lot' import { getSite, placeBuilding } from './site' import { fitStair, measureStairOperation } from './stairs' +import { addTerraces } from './terraces' +import { + addStepsToGround, + gradeAlongLine, + readTerrainFacts, + seatHouse, + setTerrainPlane, +} from './terraforming' +import { + carveTerrainPad, + describeTerrainUnderHouse, + gradeAroundHouse, + readSiteTerrain, + readTerrainContours, + sampleTerrainLine, + shapeSiteTerrain, +} from './terrain' +import { addTerrainBreak } from './terrain-break' import type { AgentOperation, AgentOperationSteps, AgentOperations } from './types' import { createUnit, listUnits, setUnitMembers } from './units' import { verifyScene, verifySceneSteps } from './verify-scene' @@ -90,6 +110,7 @@ export * from './place-items' export * from './plan-geometry' export * from './point-context' export * from './project-files' +export * from './ramp' export * from './roof-writes' export { ROOM_CHECK_CODES } from './room-checks' export * from './room-floor-script' @@ -101,10 +122,18 @@ export * from './scene-queries' export * from './scene-view' export * from './search-assets' export * from './search-materials' +export * from './set-site-lot' export * from './site' export * from './slab-surface-script' export * from './stairs' +export * from './terraces' +export * from './terraforming' +export * from './terrain' +export * from './terrain-break' +export * from './terrain-break-facts' +export * from './terrain-facts' export * from './types' +export * from './unguarded-drop-observations' export * from './units' export * from './verify-scene' export * from './wall-face-script' @@ -152,6 +181,22 @@ const SINGLE_OPERATIONS = { search_materials: searchMaterials, get_site: getSite, place_building: placeBuilding, + set_site_lot: setSiteLot, + add_ramp: addRamp, + add_terrain_break: addTerrainBreak, + read_site_terrain: readSiteTerrain, + sample_terrain_line: sampleTerrainLine, + read_terrain_contours: readTerrainContours, + shape_site_terrain: shapeSiteTerrain, + carve_terrain_pad: carveTerrainPad, + grade_around_house: gradeAroundHouse, + describe_terrain_under_house: describeTerrainUnderHouse, + read_terrain_facts: readTerrainFacts, + seat_house: seatHouse, + set_terrain_plane: setTerrainPlane, + grade_along_line: gradeAlongLine, + add_steps_to_ground: addStepsToGround, + add_terraces: addTerraces, ...ROOM_OPERATIONS, create_unit: createUnit, set_unit_members: setUnitMembers, diff --git a/packages/core/src/agent-operations/layout-clearance.ts b/packages/core/src/agent-operations/layout-clearance.ts index 4374bd84b3..17f62237a7 100644 --- a/packages/core/src/agent-operations/layout-clearance.ts +++ b/packages/core/src/agent-operations/layout-clearance.ts @@ -11,6 +11,7 @@ import { floorConstructionLift, liftedManualSlab } from '../lib/floor-construction-lift' import { selectSlabSupportForItem } from '../lib/item-slab-support' import { getRenderableSlabPolygon } from '../lib/slab-polygon' +import { slabTerrainHeightAt } from '../lib/slab-terrain' import { levelBaseElevationAt } from '../lib/terrain-support-query' import { type Bounds, @@ -232,9 +233,14 @@ function itemFloorLift(node: ItemNode, nodes: Record): number { walls, siblingSlabs: slabs.filter((other) => other.id !== slab.id), }), - { preferredSlabId: node.supportSlabId }, + { + preferredSlabId: node.supportSlabId, + elevationOf: (slab) => slabTerrainHeightAt(slab, nodes, node.position[0], node.position[2]), + }, ) - return support ? support.elevation : ground() + return support + ? slabTerrainHeightAt(support, nodes, node.position[0], node.position[2]) + : ground() } /** diff --git a/packages/core/src/agent-operations/ramp.ts b/packages/core/src/agent-operations/ramp.ts new file mode 100644 index 0000000000..6919323811 --- /dev/null +++ b/packages/core/src/agent-operations/ramp.ts @@ -0,0 +1,56 @@ +import { z } from 'zod' +import { addRampTool } from '../agent-tools/ramp' +import { refuse } from '../agent-tools/refusal' +import { rampDefaultTransitionLength } from '../lib/ramp' +import { rampFacts } from '../lib/ramp-facts' +import { planRampCreation } from '../lib/ramp-terrain' +import { queryNodes } from '../runtime/node-queries' +import { RampNode } from '../schema/nodes/ramp' +import { applySceneChanges } from './apply-changes' +import type { AgentOperation, SceneChanges } from './types' + +const inputSchema = z.strictObject(addRampTool.input) + +/** One atomic scene plan: only the new ramp and localized Site terrain change. */ +export const addRamp: AgentOperation> = (nodes, rawInput) => { + const parsed = inputSchema.safeParse(rawInput) + if (!parsed.success) refuse('invalid_input', parsed.error.message) + const input = parsed.data + const sites = queryNodes(nodes, { type: 'site' }).filter((node) => node.type === 'site') + if (!input.siteId && sites.length > 1) + refuse('ambiguous_site', 'Choose the Site that owns this ramp with siteId.') + const site = input.siteId ? nodes[input.siteId] : sites[0] + if (site?.type !== 'site') refuse('no_site', 'The scene has no matching Site for this ramp.') + const node = RampNode.safeParse({ + ...input, + parentId: site.id, + name: input.name ?? 'Ramp', + endHeight: input.endHeight ?? input.startHeight ?? 0, + }) + if (!node.success) refuse('invalid_input', node.error.message) + let ramp = node.data + const defaultTransition = rampDefaultTransitionLength(ramp) + ramp = { + ...ramp, + startTransition: input.startTransition ?? defaultTransition, + endTransition: input.endTransition ?? defaultTransition, + } + if (input.endHeight === undefined) { + if (!input.endTargetId) + refuse('ramp_end_required', 'Give an endHeight or a modeled door or level endTargetId.') + const endHeight = rampFacts(ramp, nodes).targets.end?.heightM + if (endHeight === undefined || endHeight === null) + refuse( + 'ramp_end_required', + 'The end target has no measurable height in this Site; give an explicit endHeight.', + { targetId: input.endTargetId }, + ) + ramp = { ...ramp, endHeight } + } + const changes: SceneChanges = planRampCreation(ramp, nodes) + const plannedNodes = applySceneChanges(nodes, changes) + return { + result: { rampId: ramp.id, siteId: site.id, facts: rampFacts(ramp, plannedNodes) }, + changes, + } +} diff --git a/packages/core/src/agent-operations/set-site-lot.test.ts b/packages/core/src/agent-operations/set-site-lot.test.ts new file mode 100644 index 0000000000..e189725e11 --- /dev/null +++ b/packages/core/src/agent-operations/set-site-lot.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, +} from '@pascal-app/core' +import { applySceneChanges, setSiteLot } from '@pascal-app/core/agent-operations' +import { isAgentRefusal } from '@pascal-app/core/agent-tools' +import { type AnyNode, SiteNode } from '@pascal-app/core/schema' + +const context = { activeLevelId: null } +type Nodes = Record + +function slopedScene(): Nodes { + // Deliberately not aligned with the tile lattice: resizing must not resample. + const field = createTerrainField({ cols: 33, rows: 33, spacing: 1, origin: [-16.2, -16.2] }) + for (let row = 0; row < 33; row++) + for (let col = 0; col < 33; col++) field.heights[row * 33 + col] = 1200 - col * 25 + const site = SiteNode.parse({ + id: 'site_lot', + terrain: encodeTerrainField(field), + frontEdge: 1, + polygon: { + type: 'polygon', + points: [ + [-15, -15], + [15, -15], + [15, 15], + [-15, 15], + ], + }, + }) + return { [site.id]: site } +} + +function assertEnlargement(nodes: Nodes) { + const site = Object.values(nodes).find((node): node is SiteNode => node.type === 'site') + if (!site) throw new Error('Fixture has no site') + const before = persistedTerrainFieldOf(site, nodes) + if (!before) throw new Error('Fixture has no legacy terrain') + const frozen = JSON.stringify(site.terrain) + const snapshot = structuredClone(nodes) + const outcome = setSiteLot(nodes, { widthM: 60, depthM: 80 }, context) + const afterNodes = applySceneChanges(nodes, outcome.changes) + const afterSite = afterNodes[site.id] as SiteNode + const after = persistedTerrainFieldOf(afterSite, afterNodes) + if (!after) throw new Error('Enlargement lost terrain') + expect(outcome.result.areaM2).toBe(4800) + expect(outcome.result.polygon).toEqual(afterSite.polygon.points) + expect(JSON.stringify(afterSite.terrain)).toBe(frozen) + expect(afterSite.frontEdge).toBe(site.frontEdge) + for (const [id, node] of Object.entries(nodes)) + if (id !== site.id) expect(afterNodes[id]).toEqual(node) + for (let row = 0; row < before.rows; row++) + for (let col = 0; col < before.cols; col++) { + const x = before.origin[0] + col * before.spacing + const z = before.origin[1] + row * before.spacing + expect(heightAt(after, x, z)).toBe(heightAt(before, x, z)) + if (row + 1 < before.rows && col + 1 < before.cols) + expect(heightAt(after, x + before.spacing / 3, z + before.spacing / 4)).toBe( + heightAt(before, x + before.spacing / 3, z + before.spacing / 4), + ) + } + // Continuation already exists before the polygon changes; enlargement exposes it. + for (const [x, z] of afterSite.polygon.points) + expect(heightAt(after, x, z)).toBe(heightAt(before, x, z)) + expect(nodes).toEqual(snapshot) + return { after, outcome } +} + +describe('set_site_lot', () => { + test('30 × 30 becomes 60 × 80 without resampling the legacy ground or losing its fall', () => { + const { after, outcome } = assertEnlargement(slopedScene()) + expect(outcome.result.polygon).toEqual([ + [-30, -40], + [30, -40], + [30, 40], + [-30, 40], + ]) + expect(heightAt(after, 16.8, 0)).toBeLessThan(heightAt(after, 15.8, 0)) + expect(heightAt(after, 16.8, 0)).toBeGreaterThan(0) + expect(outcome.result.sampling).toMatchObject({ approximate: true }) + }) + + test('a polygon on flat ground returns independently known area and height range', () => { + const site = SiteNode.parse({ id: 'site_flat' }) + const polygon: [number, number][] = [ + [2, 3], + [8, 3], + [8, 7], + [2, 7], + ] + const outcome = setSiteLot({ [site.id]: site }, { polygon }, context) + expect(outcome.result).toMatchObject({ siteId: site.id, polygon, areaM2: 24, minM: 0, maxM: 0 }) + expect( + (applySceneChanges({ [site.id]: site }, outcome.changes)[site.id] as SiteNode).terrain, + ).toBeUndefined() + }) + + test('an explicit rectangle anchor is its centre', () => { + const outcome = setSiteLot(slopedScene(), { widthM: 10, depthM: 20, anchor: [7, -3] }, context) + expect(outcome.result.polygon).toEqual([ + [2, -13], + [12, -13], + [12, 7], + [2, 7], + ]) + expect(outcome.result.areaM2).toBe(200) + }) + + test('invalid lot requests refuse atomically', () => { + const nodes = slopedScene() + const before = structuredClone(nodes) + for (const input of [ + { widthM: 0, depthM: 80 }, + { widthM: 60 }, + { + polygon: [ + [0, 0], + [1, 0], + ], + widthM: 60, + depthM: 80, + }, + ]) { + let code: string | undefined + try { + setSiteLot(nodes, input as never, context) + } catch (error) { + if (!isAgentRefusal(error)) throw error + code = error.code + } + expect(code).toBe('invalid_input') + expect(nodes).toEqual(before) + } + }) +}) + +test('enlarging a cut lot with zero padding exposes falling ground without rewriting the padding', () => { + const legacy = createTerrainField({ cols: 65, rows: 65, spacing: 0.5, origin: [-16, -16] }) + // Reduced owner-scene geometry: south lot samples at z=14..15 lie at -7.8 m; + // the two frozen padding rows at z=15.5 and z=16 remain at zero. + for (let row = 60; row <= 62; row++) + for (let col = 2; col <= 62; col++) legacy.heights[row * 65 + col] = -780 + const site = SiteNode.parse({ + id: 'site_cut_lot', + terrain: encodeTerrainField(legacy), + polygon: { + type: 'polygon', + points: [ + [-15, -15], + [15, -15], + [15, 15], + [-15, 15], + ], + }, + }) + const { after } = assertEnlargement({ [site.id]: site }) + // The frozen padding is at zero despite a -7.8 m cut inside the lot. + // A datum-only continuation would pass preservation but fail to expose the fall. + expect(heightAt(after, 0, 15)).toBeCloseTo(-7.8, 6) + expect(heightAt(after, 0, 15.5)).toBe(0) + expect(heightAt(after, 0, 16)).toBe(0) + expect(heightAt(after, 0, 20)).toBeLessThan(0) + expect(heightAt(after, 0, 30)).toBeLessThan(heightAt(after, 0, 20)) + expect(heightAt(after, 0, 80)).toBeCloseTo(-7.8, 6) +}) diff --git a/packages/core/src/agent-operations/set-site-lot.ts b/packages/core/src/agent-operations/set-site-lot.ts new file mode 100644 index 0000000000..d1c1c772a8 --- /dev/null +++ b/packages/core/src/agent-operations/set-site-lot.ts @@ -0,0 +1,98 @@ +import { z } from 'zod' +import { refuse } from '../agent-tools/refusal' +import { setSiteLotTool } from '../agent-tools/terrain' +import { heightAt, type TerrainField } from '../lib/terrain-field' +import { distance2D, pointInPolygon, polygonArea, polygonBounds, type Vec2 } from './plan-geometry' +import { footprintOf, groundOf } from './terrain' +import type { AgentOperation } from './types' + +const inputSchema = z.strictObject(setSiteLotTool.input) +type LotInput = z.output + +function lotPolygon(input: LotInput, current: Vec2[]): Vec2[] { + if (input.polygon) { + if (input.widthM !== undefined || input.depthM !== undefined || input.anchor !== undefined) + refuse('invalid_input', 'Give a polygon or rectangle dimensions, not both.') + return footprintOf(input.polygon) + } + if (input.widthM === undefined || input.depthM === undefined) + refuse('invalid_input', 'Give a polygon, or both widthM and depthM.') + const bounds = polygonBounds(current) + const [x, z] = input.anchor ?? [bounds.minX + bounds.width / 2, bounds.minZ + bounds.depth / 2] + if (x === undefined || z === undefined) + refuse('invalid_input', 'The rectangle anchor needs two coordinates [x,z].') + const halfWidth = input.widthM / 2 + const halfDepth = input.depthM / 2 + return footprintOf([ + [x - halfWidth, z - halfDepth], + [x + halfWidth, z - halfDepth], + [x + halfWidth, z + halfDepth], + [x - halfWidth, z + halfDepth], + ]) +} + +function lotHeightRange(field: TerrainField | null, polygon: Vec2[]) { + const bounds = polygonBounds(polygon) + const perimeter = polygon.reduce((sum, from, index) => { + const to = polygon[(index + 1) % polygon.length] + return sum + (to ? distance2D(from, to) : 0) + }, 0) + // Bound facts independently of lot size; tiles impose no fixed dimension ceiling. + const cellM = Math.max(0.5, bounds.width / 100, bounds.depth / 100, perimeter / 4000) + let minM = Infinity + let maxM = -Infinity + let sampleCount = 0 + const sample = (x: number, z: number) => { + const height = field ? heightAt(field, x, z) : 0 + if (!Number.isFinite(height)) + refuse('no_terrain', 'The ground cannot produce finite lot heights.') + minM = Math.min(minM, height) + maxM = Math.max(maxM, height) + sampleCount++ + } + for (const [index, from] of polygon.entries()) { + const to = polygon[(index + 1) % polygon.length] + if (!to) continue + const steps = Math.max(1, Math.ceil(distance2D(from, to) / cellM)) + for (let step = 0; step < steps; step++) { + const fraction = step / steps + sample(from[0] + (to[0] - from[0]) * fraction, from[1] + (to[1] - from[1]) * fraction) + } + } + const cols = Math.ceil(bounds.width / cellM) + const rows = Math.ceil(bounds.depth / cellM) + for (let row = 0; row <= rows; row++) { + const z = bounds.minZ + (row / rows) * bounds.depth + for (let col = 0; col <= cols; col++) { + const x = bounds.minX + (col / cols) * bounds.width + if (pointInPolygon([x, z], polygon)) sample(x, z) + } + } + return { minM, maxM, cellM, sampleCount } +} + +export const setSiteLot: AgentOperation = (nodes, input) => { + const parsed = inputSchema.safeParse(input) + if (!parsed.success) refuse('invalid_input', parsed.error.message) + const { site, field } = groundOf(nodes) + const polygon = lotPolygon(parsed.data, footprintOf(site.polygon.points)) + const { minM, maxM, cellM, sampleCount } = lotHeightRange(field, polygon) + return { + result: { + siteId: site.id, + polygon, + areaM2: polygonArea(polygon), + minM, + maxM, + sampling: { + approximate: true, + method: 'lot_grid_and_edges', + spacingM: field?.spacing ?? 0.5, + heightStepM: field?.step ?? 0.01, + cellM, + sampleCount, + }, + }, + changes: { update: [{ id: site.id, data: { polygon: { type: 'polygon', points: polygon } } }] }, + } +} diff --git a/packages/core/src/agent-operations/terraces.test.ts b/packages/core/src/agent-operations/terraces.test.ts new file mode 100644 index 0000000000..52d948e7ad --- /dev/null +++ b/packages/core/src/agent-operations/terraces.test.ts @@ -0,0 +1,276 @@ +import { describe, expect, test } from 'bun:test' +import { isAgentRefusal } from '../agent-tools/refusal' +import { closedHollows } from '../lib/terrain-hollows' +import type { AnyNode, StairNode } from '../schema' +import { type Ground, groundAt, runTool, slopedLot } from './__fixtures__/sloped-lots' +import { type TerrainFacts, terrainFacts } from './terrain-facts' + +/* + * Terraces that touch. Two closed terrain breaks may not touch, so two retaining pads side by + * side left a strip of the natural slope between them: a trench 0.5 m deep and more between two + * terraces (the trial team's D14). add_terraces alternates a break and level lattice ground, so + * each face between two neighbours is one edge of one break. The lot falls toward +x at 20 %. + */ + +type Nodes = Record +const slope: Ground = (x) => -0.2 * x +const lot = (house = false) => slopedLot({ ground: slope, house }) +const refusal = (run: () => unknown) => { + try { + run() + } catch (error) { + if (isAgentRefusal(error)) return error.code + throw error + } + return undefined +} +/** The ground along the middle of the terraces, every 0.1 m. */ +const profile = (nodes: Nodes, from: number, to: number, z = 0) => + Array.from({ length: Math.round((to - from) / 0.1) + 1 }, (_, i) => + groundAt(nodes, from + 0.1 * i, z), + ) + +describe('add_terraces', () => { + const cases = [ + { + name: 'three terraces, each at the mean of its ground', + input: { count: 3 }, + levels: [-0.6, -1.4, -2.2], + }, + { + name: 'four terraces between two stated heights', + input: { count: 4, topM: -0.3, bottomM: -2.1 }, + levels: [-0.3, -0.9, -1.5, -2.1], + }, + { name: 'two terraces from a stated top', input: { count: 2, topM: 0 }, levels: [0, -1.2] }, + ] as const + for (const { name, input, levels } of cases) + test(`${name}: level treads that touch, one vertical face between each two, no trench, no hollow`, () => { + const { nodes, result } = runTool(lot(), 'add_terraces', { + line: [ + [1, 0], + [13, 0], + ], + widthM: 8, + ...input, + }) + const terraces = result.terraces as { levelM: number; heldAs: string; breakId?: string }[] + expect(terraces.map((terrace) => terrace.levelM)).toEqual(levels as unknown as number[]) + expect(terraces.map((terrace) => terrace.heldAs)).toEqual( + levels.map((_, index) => (index % 2 === 0 ? 'break' : 'lattice')), + ) + const tread = 12 / levels.length + const ground = profile(nodes, 1, 13) + // Every point of the section stands at its terrace's level: nothing lies between two terraces. + ground.forEach((height, i) => { + const x = 0.1 * i + const index = Math.min(levels.length - 1, Math.floor((x + 1e-6) / tread)) + const onFace = Math.abs(x / tread - Math.round(x / tread)) < 1e-6 + if (!onFace) expect(height).toBeCloseTo(levels[index] as number, 2) + }) + // And across each face the ground steps by the whole riser within 0.1 m. + for (let index = 1; index < levels.length; index++) { + const x = 1 + index * tread + expect(groundAt(nodes, x - 0.05, 0) - groundAt(nodes, x + 0.05, 0)).toBeCloseTo( + (levels[index - 1] as number) - (levels[index] as number), + 2, + ) + } + const read = terrainFacts(nodes) as TerrainFacts + expect(read.retaining.length).toBe(Math.ceil(levels.length / 2)) + expect(read.open.filter((finding) => finding.code === 'steep_bank')).toEqual([]) + const edges = result.edges as { at: string; heldBy: string }[] + expect(edges.at(-1)?.heldBy).toBe(levels.length % 2 === 1 ? 'wall' : 'bank') + expect( + closedHollows((x, z) => groundAt(nodes, x, z), { + bounds: { minX: -2, minZ: -7, maxX: 15, maxZ: 7 }, + minDepthM: 0.05, + }), + ).toEqual([]) + }) + + test('cut and fill of a terrace at the mean of its ground are alike', () => { + const { result } = runTool(lot(), 'add_terraces', { + line: [ + [1, 0], + [13, 0], + ], + widthM: 8, + count: 3, + }) + const cut = result.cutVolumeM3 as number + const fill = result.fillVolumeM3 as number + expect(cut).toBeGreaterThan(5) + expect(Math.abs(cut - fill)).toBeLessThan(0.25 * (cut + fill)) + }) + + test('stepsAt: a flight from each terrace to the one above, its foot on the lower, its top at the upper', () => { + const { nodes, result } = runTool(lot(true), 'add_terraces', { + line: [ + [7, 12], + [14, 12], + ], + widthM: 6, + count: 3, + stepsAt: 0.5, + }) + const steps = result.steps as { stairId: string; riseM: number; stepCount: number }[] + expect(steps.length).toBe(2) + for (const flight of steps) { + expect(flight.riseM / flight.stepCount).toBeLessThanOrEqual(0.19) + expect((nodes[flight.stairId] as StairNode).totalRise).toBeCloseTo(flight.riseM, 3) + } + const read = terrainFacts(nodes) as TerrainFacts + for (const flight of read.steps) + expect(Math.abs(flight.footOverGroundM)).toBeLessThanOrEqual(0.05) + const levels = (result.terraces as { levelM: number }[]).map((terrace) => terrace.levelM) + expect(read.steps.map((flight) => flight.topM).sort()).toEqual( + [levels[0], levels[1]].map((level) => Math.round((level as number) * 100) / 100).sort(), + ) + }) + + test('with no building to hold a flight, none is made and the answer says so', () => { + const { result } = runTool(lot(), 'add_terraces', { + line: [ + [1, 0], + [13, 0], + ], + widthM: 8, + count: 3, + stepsAt: 0.5, + }) + expect(result.steps).toBeUndefined() + expect(result.stepsNote as string).toContain('No flight was made') + }) + + const refusals: [string, Record, string][] = [ + [ + 'terraces under 1.5 m deep', + { + line: [ + [1, 0], + [13, 0], + ], + widthM: 8, + count: 12, + }, + 'invalid_input', + ], + [ + 'a line under 3 m', + { + line: [ + [1, 0], + [2, 0], + ], + widthM: 8, + count: 2, + }, + 'invalid_input', + ], + [ + 'a line over 200 m', + { + scope: 'context', + line: [ + [-150, 0], + [150, 0], + ], + widthM: 8, + count: 2, + }, + 'invalid_input', + ], + [ + 'a point 10 km away', + { + scope: 'context', + line: [ + [1, 0], + [10_000, 0], + ], + widthM: 8, + count: 2, + }, + 'invalid_input', + ], + [ + 'a point that is not finite', + { + line: [ + [1, 0], + [Number.NaN, 0], + ], + widthM: 8, + count: 2, + }, + 'invalid_input', + ], + [ + 'terraces that leave the lot', + { + line: [ + [1, 0], + [13, 0], + ], + widthM: 60, + count: 3, + }, + 'outside_property', + ], + [ + 'a count of 13', + { + line: [ + [1, 0], + [13, 0], + ], + widthM: 8, + count: 13, + }, + 'invalid_input', + ], + [ + 'a width of 1 km', + { + scope: 'context', + line: [ + [1, 0], + [13, 0], + ], + widthM: 1000, + count: 3, + }, + 'invalid_input', + ], + ] + for (const [name, input, code] of refusals) + test(`refused, at once: ${name} (${code})`, () => { + const started = performance.now() + expect(refusal(() => runTool(lot(), 'add_terraces', input))).toBe(code) + expect(performance.now() - started).toBeLessThan(1000) + }) + + test('terraces laid over a break that is there are refused, nothing written', () => { + const first = runTool(lot(), 'add_terraces', { + line: [ + [1, 0], + [13, 0], + ], + widthM: 8, + count: 3, + }).nodes + expect( + refusal(() => + runTool(first, 'add_terraces', { + line: [ + [3, 2], + [12, 2], + ], + widthM: 8, + count: 3, + }), + ), + ).toBe('crossing_breaks') + }) +}) diff --git a/packages/core/src/agent-operations/terraces.ts b/packages/core/src/agent-operations/terraces.ts new file mode 100644 index 0000000000..d9310298f0 --- /dev/null +++ b/packages/core/src/agent-operations/terraces.ts @@ -0,0 +1,354 @@ +import { z } from 'zod' +import { refuse } from '../agent-tools/refusal' +import { addTerracesTool } from '../agent-tools/terraforming' +import { GROUND_SUPPORT_ID } from '../hooks/spatial-grid/support-host-id' +import { groundLevelOf } from '../lib/ground-level' +import { heightAt, quantize } from '../lib/terrain-field' +import { isLevelAtSiteDatum } from '../lib/terrain-support-query' +import { queryNodes } from '../runtime/node-queries' +import type { AnyNode, AnyNodeId, BuildingNode } from '../schema' +import { StairNode } from '../schema' +import { TerrainBreakNode } from '../schema/nodes/terrain-break' +import { levelPlaneWorldY } from '../services/storey' +import { createDefaultStairSegment } from '../systems/stair/stair-flight' +import { pointInPolygon, type Vec2 } from './plan-geometry' +import { requireNearLot, requireSampleBudget, STEP } from './terraforming' +import { + editingField, + groundOf, + parseInput, + pointOf, + propertyOf, + samplingOf, + terrainWriteOutcome, +} from './terrain' +import { validateTerrainBreakPlacement } from './terrain-break' +import type { AgentOperation, SceneChanges, SceneNodes } from './types' + +const terracesInput = z.strictObject(addTerracesTool.input) + +const MIN_TREAD_M = 1.5 +const MIN_LINE_M = 3 +const MAX_LINE_M = 200 +/** How far beyond a terrace its bank is looked for. */ +const BANK_REACH_M = 12 + +const round = (value: number, digits = 2) => { + const k = 10 ** digits + return Math.round(value * k) / k +} + +/** + * `add_terraces`: a slope cut into level terraces that touch. Two closed breaks may not touch, so + * the terraces alternate: every second one is a closed retaining break at its exact height, the + * ones between are level ground on the lattice. Each face between two neighbours is then one + * edge of one break, vertical and exact, with no strip of ground left between them. + */ +export const addTerraces: AgentOperation> = (nodes, raw) => { + const input = parseInput(terracesInput, raw) + const { site, field: persisted } = groundOf(nodes) + const property = propertyOf(site) + const [top, bottom] = input.line.map(pointOf) as [Vec2, Vec2] + // Bounds first: nothing below is sized from a coordinate or a count before these. + requireNearLot([top, bottom], property, 'The line') + const lengthM = Math.hypot(bottom[0] - top[0], bottom[1] - top[1]) + if (!(lengthM >= MIN_LINE_M && lengthM <= MAX_LINE_M)) + refuse( + 'invalid_input', + `The line is ${lengthM.toFixed(1)} m long; terraces run along ${MIN_LINE_M} to ${MAX_LINE_M} m.`, + ) + const count = input.count + const treadM = lengthM / count + if (treadM < MIN_TREAD_M) + refuse( + 'invalid_input', + `${count} terraces along ${lengthM.toFixed(1)} m are ${treadM.toFixed(2)} m deep each; a terrace is ${MIN_TREAD_M} m deep or more: at most ${Math.floor(lengthM / MIN_TREAD_M)} here.`, + ) + const run = input.run ?? 2 + const half = input.widthM / 2 + const along: Vec2 = [(bottom[0] - top[0]) / lengthM, (bottom[1] - top[1]) / lengthM] + const across: Vec2 = [-along[1], along[0]] + const at = (s: number, t: number): Vec2 => [ + top[0] + along[0] * s + across[0] * t, + top[1] + along[1] * s + across[1] * t, + ] + /** A terrace's rectangle, counter-clockwise in the site frame. */ + const outlineOf = (index: number): Vec2[] => { + const ring = [ + at(index * treadM, -half), + at((index + 1) * treadM, -half), + at((index + 1) * treadM, half), + at(index * treadM, half), + ] + const area = ring.reduce((sum, a, i) => { + const b = ring[(i + 1) % 4] as Vec2 + return sum + a[0] * b[1] - b[0] * a[1] + }, 0) + return area < 0 ? ring.reverse() : ring + } + const whole = [at(0, -half), at(lengthM, -half), at(lengthM, half), at(0, half)] + if (input.scope !== 'context' && !whole.every((corner) => pointInPolygon(corner, property))) + refuse('outside_property', 'The terraces reach outside the site polygon; nothing was written.') + const bounds = { + minX: Math.min(...whole.map((p) => p[0])), + minZ: Math.min(...whole.map((p) => p[1])), + maxX: Math.max(...whole.map((p) => p[0])), + maxZ: Math.max(...whole.map((p) => p[1])), + } + requireSampleBudget(bounds, BANK_REACH_M + 0.5) + const field = editingField( + site, + nodes, + { + kind: 'polygon', + polygon: [ + [bounds.minX, bounds.minZ], + [bounds.maxX, bounds.minZ], + [bounds.maxX, bounds.maxZ], + [bounds.minX, bounds.maxZ], + ], + }, + BANK_REACH_M + 0.5, + ) + const inside = (point: Vec2) => input.scope === 'context' || pointInPolygon(point, property) + + // The ground under each terrace before, read on a grid of its own (half a metre, 40 lines a + // side at most): its mean sets the level where none is stated. + const groundBefore = (point: Vec2) => (persisted ? heightAt(persisted, point[0], point[1]) : 0) + const before = Array.from({ length: count }, (_, index) => { + const rows = Math.min(40, Math.max(2, Math.ceil(treadM / 0.5))) + const cols = Math.min(40, Math.max(2, Math.ceil(input.widthM / 0.5))) + let sum = 0 + let lowest = Number.POSITIVE_INFINITY + let highest = Number.NEGATIVE_INFINITY + for (let row = 0; row < rows; row++) + for (let col = 0; col < cols; col++) { + const height = groundBefore( + at((index + (row + 0.5) / rows) * treadM, ((col + 0.5) / cols - 0.5) * input.widthM), + ) + sum += height + lowest = Math.min(lowest, height) + highest = Math.max(highest, height) + } + return { mean: sum / (rows * cols), lowest, highest } + }) + const place = (point: Vec2) => { + const dx = point[0] - top[0] + const dz = point[1] - top[1] + return { s: dx * along[0] + dz * along[1], t: dx * across[0] + dz * across[1] } + } + const means = before.map((terrace) => terrace.mean) + const first = means[0] as number + const last = means[count - 1] as number + const levels = means.map( + (mean, index) => + quantize( + field, + input.topM !== undefined && input.bottomM !== undefined + ? input.topM + ((input.bottomM - input.topM) * index) / (count - 1) + : input.topM !== undefined + ? input.topM + (mean - first) + : input.bottomM !== undefined + ? input.bottomM + (mean - last) + : mean, + ) * field.step, + ) + /** Every second terrace from the first is a break; the ones between are lattice ground. */ + const isBreak = (index: number) => index % 2 === 0 + + const heights = new Int16Array(field.heights) + const cellM2 = field.spacing * field.spacing + let cutVolumeM3 = 0 + let fillVolumeM3 = 0 + let changedSamples = 0 + let visited = 0 + for (let index = 0; index < field.heights.length; index++) { + const point: Vec2 = [ + field.origin[0] + (index % field.cols) * field.spacing, + field.origin[1] + Math.floor(index / field.cols) * field.spacing, + ] + const { s, t } = place(point) + const beyond = Math.hypot(Math.max(0, -s, s - lengthM), Math.max(0, Math.abs(t) - half)) + if (beyond > BANK_REACH_M) continue + visited++ + const terrace = Math.max(0, Math.min(count - 1, Math.floor(s / treadM))) + const level = levels[terrace] as number + const beforeQ = field.heights[index] ?? 0 + const beforeM = beforeQ * field.step + let target = beforeM + if (beyond === 0) target = level + // A break holds the ground beside it with a face; lattice ground meets it with a bank. + else if (!isBreak(terrace)) + target = + beforeM > level + ? Math.min(beforeM, level + beyond / run) + : Math.max(beforeM, level - beyond / run) + const nextQ = quantize(field, target) + if (nextQ === beforeQ || !inside(point)) continue + heights[index] = nextQ + changedSamples++ + const movedM = (nextQ - beforeQ) * field.step + if (movedM < 0) cutVolumeM3 += -movedM * cellM2 + else fillVolumeM3 += movedM * cellM2 + } + + // The breaks, each placed against the scene and the ones before it. + let withBreaks = nodes + const breaks = new Map() + for (let index = 0; index < count; index++) { + if (!isBreak(index)) continue + const ring = outlineOf(index) + const node = TerrainBreakNode.parse({ + parentId: site.id, + line: [...ring, ring[0]], + kind: 'retaining', + left: levels[index], + right: 'ground', + metadata: { source: 'add_terraces' }, + }) + validateTerrainBreakPlacement(withBreaks, site, node, input.scope) + withBreaks = { ...withBreaks, [node.id]: node } as SceneNodes + breaks.set(index, node) + } + + const groundAt = groundBefore + const edges = [ + { + at: 'top', + heightM: round(groundAt(at(-0.6, 0)) - (levels[0] as number)), + heldBy: 'wall' as const, + }, + ...levels.slice(1).map((level, index) => ({ + at: `between ${index} and ${index + 1}`, + heightM: round((levels[index] as number) - level), + heldBy: 'wall' as const, + })), + { + at: 'bottom', + heightM: round((levels[count - 1] as number) - groundAt(at(lengthM + 0.6, 0))), + heldBy: isBreak(count - 1) ? ('wall' as const) : ('bank' as const), + }, + ] + + // Flights: one from each terrace up to the one above, where the two differ by a step or more. + const steps: { + stairId: string + fromTerrace: number + toTerrace: number + riseM: number + stepCount: number + }[] = [] + const creates: NonNullable = [...breaks.values()].map((node) => ({ + node, + parentId: site.id, + })) + let stepsNote: string | undefined + if (input.stepsAt !== undefined) { + const record = nodes as Record + const buildings = queryNodes(nodes, { type: 'building' }).filter( + (building) => Math.abs(building.rotation[0]) < 1e-9 && Math.abs(building.rotation[2]) < 1e-9, + ) + const building = buildings[0] + const level = building ? groundLevelOf(record, building.id)?.level : undefined + const plane = level ? levelPlaneWorldY(record, level.id) : null + if (!building || !level || plane === null) + stepsNote = + 'No flight was made: a flight belongs to a level of a building, and the scene has none to hold it.' + else { + const cos = Math.cos(building.rotation[1]) + const sin = Math.sin(building.rotation[1]) + const toLocal = ([x, z]: Vec2): Vec2 => [ + cos * (x - building.position[0]) - sin * (z - building.position[2]), + sin * (x - building.position[0]) + cos * (z - building.position[2]), + ] + const carried = isLevelAtSiteDatum(record, level.id) + const t = (input.stepsAt - 0.5) * (input.widthM - 1.2) + for (let lower = 1; lower < count; lower++) { + const upperM = levels[lower - 1] as number + const lowerM = levels[lower] as number + // The flight stands on whichever of the two is lower, and climbs to the other. + const rise = Math.abs(upperM - lowerM) + if (rise < 0.05) continue + const stepCount = Math.max(1, Math.ceil(rise / STEP.maxRiser - 1e-9)) + const going = Math.min( + STEP.maxGoing, + Math.max(STEP.minGoing, STEP.comfort - (2 * rise) / stepCount), + ) + const runM = Math.min(stepCount * going, treadM - 0.6) + const down = upperM > lowerM ? 1 : -1 + const face = lower * treadM + const foot = toLocal(at(face + down * runM, t)) + const climb: Vec2 = [-down * along[0], -down * along[1]] + const turned: Vec2 = [cos * climb[0] - sin * climb[1], sin * climb[0] + cos * climb[1]] + const segment = createDefaultStairSegment({ + width: 1.2, + height: rise, + length: runM, + stepCount, + attachmentSide: 'front', + fillToFloor: true, + }) + const stair = StairNode.parse({ + name: `Steps between terraces ${lower - 1} and ${lower}`, + parentId: level.id, + position: [ + foot[0], + // A level the ground carries stands its flights on the ground; any other states it. + carried ? 0 : round(Math.min(upperM, lowerM) - plane, 4), + foot[1], + ], + rotation: Math.atan2(turned[0], turned[1]), + supportSlabId: GROUND_SUPPORT_ID, + stairType: 'straight', + fromLevelId: level.id, + toLevelId: null, + totalRise: rise, + width: 1.2, + stepCount, + railingMode: stepCount > 3 ? 'both' : 'none', + children: [segment.id], + }) + creates.push( + { node: stair, parentId: level.id }, + { node: { ...segment, parentId: stair.id }, parentId: stair.id }, + ) + steps.push({ + stairId: stair.id, + fromTerrace: down === 1 ? lower : lower - 1, + toTerrace: down === 1 ? lower - 1 : lower, + riseM: round(rise, 3), + stepCount, + }) + } + } + } + + return terrainWriteOutcome( + site, + nodes, + field, + heights, + { + terraces: levels.map((level, index) => ({ + index, + levelM: round(level), + outline: outlineOf(index).map(([x, z]) => [round(x, 3), round(z, 3)]), + heldAs: isBreak(index) ? 'break' : 'lattice', + ...(breaks.get(index) ? { breakId: breaks.get(index)?.id } : {}), + groundBeforeM: { + lowest: round((before[index] as (typeof before)[number]).lowest), + highest: round((before[index] as (typeof before)[number]).highest), + }, + })), + edges, + ...(steps.length ? { steps } : {}), + ...(stepsNote ? { stepsNote } : {}), + cutVolumeM3, + fillVolumeM3, + netM3: cutVolumeM3 - fillVolumeM3, + changedSamples, + sampling: samplingOf(field, 'field_samples_in_terraces', visited), + }, + { create: creates }, + ) +} diff --git a/packages/core/src/agent-operations/terraforming.test.ts b/packages/core/src/agent-operations/terraforming.test.ts new file mode 100644 index 0000000000..54b4be0bcf --- /dev/null +++ b/packages/core/src/agent-operations/terraforming.test.ts @@ -0,0 +1,1346 @@ +import { describe, expect, test } from 'bun:test' +import { AGENT_TOOL_CONTRACTS } from '../agent-tools' +import { isAgentRefusal } from '../agent-tools/refusal' +import { closedHollows } from '../lib/terrain-hollows' +import { type AnyNode, type BuildingNode, LevelNode, SlabNode } from '../schema' +import { MIN_SLAB_THICKNESS } from '../schema/nodes/slab' +import { + agentHouse, + GROUNDS, + type Ground, + groundAt, + runInStore, + runSettled, + runTool, + slopedLot, +} from './__fixtures__/sloped-lots' +import { AGENT_OPERATIONS } from './index' +import { type TerrainFacts, terrainFacts } from './terrain-facts' + +/* + * The shared terraforming set: seat_house, set_terrain_plane, grade_along_line, add_steps_to_ground. + * Lots and house are those of sloped-lots (floor +0.15 over the building's origin, front door to + * the street on +z, rear door); the house stands as an agent leaves it, at y = 0, unless seated. + */ + +type Nodes = Record +type Result = Record +const facts = (nodes: Nodes) => terrainFacts(nodes) as TerrainFacts +const refusal = (run: () => unknown) => { + try { + run() + } catch (error) { + if (isAgentRefusal(error)) return error.code + throw error + } + return undefined +} +const moved = (result: Result) => (result.cutVolumeM3 as number) + (result.fillVolumeM3 as number) +const NAMES = [ + 'read_terrain_facts', + 'seat_house', + 'set_terrain_plane', + 'grade_along_line', + 'add_steps_to_ground', +] + +test('each tool is one contract and one operation, by name', () => { + for (const name of NAMES) { + expect(AGENT_TOOL_CONTRACTS.filter((contract) => contract.name === name)).toHaveLength(1) + expect((AGENT_OPERATIONS as Record)[name]).toBeFunction() + } +}) + +describe('seat_house: a drawn floor (a slab at its own height) on each lot', () => { + const lots: [string, Ground | null][] = [ + ['flat', GROUNDS.flat], + ['falling to the rear', GROUNDS.fallToRear], + ['rising to the rear', GROUNDS.riseToRear], + ['cross slope', GROUNDS.cross], + ['hillside', GROUNDS.steep], + ] + for (const [name, ground] of lots) + for (const strategy of ['balance', 'fill', 'cut', 'keep'] as const) + test(`${name}, ${strategy}: the ground at every wall is the base of the level, each door a step off it, nothing open`, () => { + const { nodes, result } = runTool(slopedLot({ ground }), 'seat_house', { strategy }) + const after = result.after as { + floorOverGroundM: unknown + doors: { stepM: number }[] + open: unknown[] + } + expect(after.open).toEqual([]) + expect(after.floorOverGroundM).toEqual({ min: 0.15, max: 0.15 }) + for (const door of after.doors) { + expect(door.stepM).toBeGreaterThan(0) + expect(door.stepM).toBeLessThanOrEqual(0.2) + } + const [house] = facts(nodes).houses + expect(house?.levelBaseM).toBeCloseTo(result.groundAtWallsM as number, 2) + expect(facts(nodes).open).toEqual([]) + }) + + const sloped = lots.filter(([, ground]) => ground !== null) + for (const [name, ground] of sloped) { + test(`${name}: fill cuts nothing to speak of and stands the pad's edge on the highest ground; cut is its mirror`, () => { + const fill = runTool(slopedLot({ ground }), 'seat_house', { strategy: 'fill' }).result + const cut = runTool(slopedLot({ ground }), 'seat_house', { strategy: 'cut' }).result + const under = fill.groundUnderHouseM as { lowest: number; highest: number } + // Fill cuts its low line round the high side and nothing else. + expect(fill.cutVolumeM3 as number).toBeLessThan(20) + expect(cut.fillVolumeM3 as number).toBeLessThan(3) + expect(fill.padEdgeM).toBeCloseTo(under.highest, 2) + expect(cut.padEdgeM).toBeCloseTo(under.lowest, 2) + expect(fill.groundAtWallsM).toBeCloseTo(under.highest + 0.05, 2) + }) + + test(`${name}: balance moves the least earth of the four, its cut and its fill alike`, () => { + const by = (strategy: string) => + runTool(slopedLot({ ground }), 'seat_house', { strategy }).result + const balance = by('balance') + const cut = balance.cutVolumeM3 as number + const fill = balance.fillVolumeM3 as number + expect(Math.abs(cut - fill)).toBeLessThanOrEqual(Math.max(3, 0.15 * (cut + fill))) + for (const other of ['fill', 'cut', 'keep']) + expect(moved(balance)).toBeLessThanOrEqual(moved(by(other)) + 1) + }) + } + + test('on a flat lot balance stands the pad on the ground: a rise to the walls, no hollow round the house', () => { + const { nodes, result } = runTool(slopedLot({ ground: GROUNDS.flat }), 'seat_house', {}) + expect(result).toMatchObject({ + strategy: 'balance', + padEdgeM: 0, + groundAtWallsM: 0.05, + cutVolumeM3: 0, + }) + expect(groundAt(nodes, 0, 5)).toBeCloseTo(0, 2) + expect(groundAt(nodes, 0, 4)).toBeCloseTo(0.05, 2) + expect(groundAt(nodes, 0, 8)).toBe(0) + }) + + test('a house built 1 m over a falling lot: keeping it there fills 188 m3, balancing moves 20', () => { + const lot = () => slopedLot({ ground: GROUNDS.fallToRear }) + const keep = runTool(lot(), 'seat_house', { strategy: 'keep' }).result + const balance = runTool(lot(), 'seat_house', {}).result + expect(keep.movedBuildingByM).toBe(0) + expect(moved(keep)).toBeGreaterThan(150) + expect(balance.strategy).toBe('balance') + expect(Math.abs((balance.movedBuildingByM as number) + 1)).toBeLessThan(0.12) + expect(moved(balance)).toBeLessThan(40) + }) + + test('the building moves in height only, is named as standing on its ground level, in one change set with the ground', () => { + const before = slopedLot({ ground: GROUNDS.riseToRear, at: [3, 0, -2], turn: Math.PI / 6 }) + const { nodes, result } = runTool(before, 'seat_house', { strategy: 'fill' }) + const building = nodes.building_house as BuildingNode + expect(building.position[0]).toBe(3) + expect(building.position[2]).toBe(-2) + expect(building.position[1]).toBeCloseTo(result.movedBuildingByM as number, 4) + expect(building.rotation[1]).toBeCloseTo(Math.PI / 6, 9) + expect(building.groundLevelId).toBe('level_ground') + expect(Object.values(nodes).some((node) => node.type === 'terrain-tile')).toBe(true) + expect(facts(nodes).open).toEqual([]) + }) + + test('the pad falls away from every wall by the fall asked; 0 is a level pad', () => { + const falls = (padFallPercent?: number) => + facts( + runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', { + ...(padFallPercent === undefined ? {} : { padFallPercent }), + }).nodes, + ).houses[0]?.walls.map((wall) => wall.fallAtWallPercent.min) + for (const fall of falls() ?? []) expect(fall).toBeCloseTo(5, 0) + for (const fall of falls(0) ?? []) expect(fall).toBeCloseTo(0, 0) + }) + + test('a stated ground height is the base of the level', () => { + const { nodes, result } = runTool(slopedLot({ ground: GROUNDS.fallToRear }), 'seat_house', { + groundM: -0.65, + }) + expect(result).toMatchObject({ strategy: 'ground', groundAtWallsM: -0.65, floorM: -0.5 }) + expect(facts(nodes).houses[0]).toMatchObject({ + levelBaseM: -0.65, + floorM: { min: -0.5, max: -0.5 }, + }) + }) + + test('an exact wall is a retaining face in the facts', () => { + const { nodes, result } = runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', { + strategy: 'cut', + wallM: 1, + exactWall: true, + }) + expect(result.wall).toMatchObject({ exact: true, heightM: 1 }) + expect(result.padEdgeM).toBe(result.groundAtWallsM) + expect(facts(nodes).retaining).toHaveLength(1) + // Inside an exact wall the pad is level (a break holds one height): on the cut sides the + // tool's own answer says the water of the bank runs to the wall. + const open = (result.after as { open: { code: string; id: string }[] }).open + expect(open.map((finding) => finding.code)).toEqual([ + 'ground_falls_to_wall', + 'ground_falls_to_wall', + 'ground_falls_to_wall', + ]) + expect(open.map((finding) => finding.id).sort()).toEqual([ + 'wall_left', + 'wall_rear', + 'wall_right', + ]) + }) + + test('a batter the property line stops is said, with the step it leaves', () => { + // A house 2 m from the rear property line, the ground 1.7 m over it there: the cut cannot run out. + const { result } = runTool( + slopedLot({ ground: GROUNDS.steep, at: [0, 0, -14] }), + 'seat_house', + { + strategy: 'cut', + }, + ) + const unmet = result.unmet as string[] + expect(unmet).toHaveLength(1) + expect(unmet[0]).toContain('beyond the property') + expect((result.daylight as { outsideLotM2: number }).outsideLotM2).toBeGreaterThan(0) + }) + + const upper: AnyNode[] = [ + LevelNode.parse({ id: 'level_upper', parentId: 'building_house', level: 1, height: 2.7 }), + SlabNode.parse({ + id: 'slab_upper', + parentId: 'level_upper', + polygon: [ + [-6, -4], + [6, -4], + [6, 4], + [-6, 4], + ], + elevation: 0.05, + }), + ] + const refusals: [string, () => unknown, string][] = [ + [ + 'a strategy and a ground height together', + () => + runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', { + strategy: 'cut', + groundM: 1, + }), + 'invalid_input', + ], + [ + 'an upper storey', + () => + runTool(slopedLot({ ground: GROUNDS.steep, extra: upper }), 'seat_house', { + levelId: 'level_upper', + }), + 'invalid_input', + ], + [ + 'a walk-out with no level under the ground level', + () => runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', { strategy: 'walk_out' }), + 'invalid_input', + ], + [ + 'a house already seated so', + () => { + const seated = runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', {}).nodes + return runTool(seated, 'seat_house', { strategy: 'keep' }) + }, + 'no_change', + ], + ['a scene with no site', () => runTool({}, 'seat_house', {}), 'no_site'], + ] + for (const [name, run, code] of refusals) + test(`refused: ${name} (${code})`, () => { + expect(refusal(run)).toBe(code) + }) +}) + +describe('seat_house: a house an agent made (a floor that rests on the ground and follows it)', () => { + /* + * create_room's floor is an automatic plate: it stands 0.05 m over the highest ground at its + * walls. The storey's top stays on the level's base, so ground over the base takes the storey: + * on a lot rising 2 m the house is left with 1.45 m of its 2.7 m. + */ + const lifted: [string, Ground, number][] = [ + ['rising to the rear', GROUNDS.riseToRear, 1.45], + ['cross slope', GROUNDS.cross, 2.25], + ['hillside', GROUNDS.steep, 1.85], + ] + for (const [name, ground, clear] of lifted) { + test(`${name}: as built the ground lifts the floor and the storey keeps ${clear} m of 2.7; the facts say so`, () => { + const read = facts(agentHouse({ ground })) + expect(read.houses[0]).toMatchObject({ + floorFollowsGround: true, + clearHeightM: clear, + storeyHeightM: 2.7, + }) + expect(read.open.map((finding) => finding.code)).toContain('floor_lifted_by_ground') + }) + + for (const strategy of ['balance', 'fill', 'cut', 'keep'] as const) + test(`${name}, ${strategy}: seated, the floor is 0.05 m over the base and the ground, the storey whole, nothing open`, () => { + const { nodes, result } = runSettled(agentHouse({ ground }), 'seat_house', { strategy }) + const [house] = facts(nodes).houses + expect(house?.clearHeightM).toBe(2.65) + expect(house?.floorOverGroundM).toEqual({ min: 0.05, max: 0.05 }) + expect(house?.levelBaseM).toBeCloseTo(result.groundAtWallsM as number, 2) + expect(result.floorM).toBeCloseTo((result.groundAtWallsM as number) + 0.05, 2) + expect(facts(nodes).open).toEqual([]) + expect((result.after as { open: unknown[]; clearHeightM: number }).open).toEqual([]) + expect((result.after as { clearHeightM: number }).clearHeightM).toBe(2.65) + }) + } + + test('a pad at the mean ground alone does not give the storey back; seating does', () => { + // The ground under the house runs 0.8 to 1.2 m over the level's base (mean 1.0). + const house = agentHouse({ ground: GROUNDS.riseToRear }) + const padded = runSettled(house, 'grade_around_house', { padHeightM: 1 }).nodes + expect(facts(padded).houses[0]?.clearHeightM).toBeCloseTo(1.65, 2) + const seated = runSettled(house, 'seat_house', {}).nodes + expect(facts(seated).houses[0]?.clearHeightM).toBe(2.65) + }) +}) + +/* + * The high side of a seated house. A pad that falls 5 cm to its edge and then meets a bank is a + * crease one lattice cell cannot hold: read half a metre on, the ground rises to the wall. Seated, + * the house has a low line between its walls and the ground that rises beyond them: a level + * bottom, wide enough to survive the lattice, that falls along its length and comes out on lower + * ground. Stated in ground numbers, read every 0.1 m on transects out of every wall. + */ +describe('seat_house: the high side is drained by a low line', () => { + type Transect = { foot: number; low: number; wide: number; rises: boolean } + /** Transects out of the four walls of the fixture house, every half metre, in order round it. */ + function transects(nodes: Nodes): Transect[] { + const building = nodes.building_house as BuildingNode + const cos = Math.cos(building.rotation[1]) + const sin = Math.sin(building.rotation[1]) + const at = (x: number, z: number) => + groundAt( + nodes, + cos * x + sin * z + building.position[0], + -sin * x + cos * z + building.position[2], + ) + const read: Transect[] = [] + // The slab reaches 0.05 m past the room's outline: the foot of the wall is 0.1 m past that. + for (const [x0, z0, dx, dz, length] of [ + [-6.05, -4.05, 1, 0, 12.1], + [6.05, -4.05, 0, 1, 8.1], + [6.05, 4.05, -1, 0, 12.1], + [-6.05, 4.05, 0, -1, 8.1], + ] as const) + for (let s = 0.3; s < length; s += 0.5) { + const heights = Array.from({ length: 35 }, (_, i) => + at(x0 + dx * s + dz * (0.1 + 0.1 * i), z0 + dz * s - dx * (0.1 + 0.1 * i)), + ) + const foot = heights[0] as number + const near = heights.slice(0, 25) + read.push({ + foot, + low: Math.min(...near), + wide: near.filter((height) => height <= foot - 0.04).length * 0.1, + rises: Math.max(...heights) > foot + 0.05, + }) + } + return read + } + /** Each stretch of transects where the ground rises beyond the wall, as its low line's heights. */ + function stretches(read: Transect[]): number[][] { + const first = read.findIndex((each, i) => each.rises && !read.at(i - 1)?.rises) + if (first < 0) return read.every((each) => each.rises) ? [read.map((each) => each.low)] : [] + const turned = [...read.slice(first), ...read.slice(0, first)] + const found: number[][] = [] + let open: number[] | undefined + for (const each of turned) { + if (!each.rises) { + open = undefined + continue + } + if (!open) { + open = [] + found.push(open) + } + open.push(each.low) + } + return found + } + const lots = [ + ['a 20 % hillside', { ground: GROUNDS.steep }], + ['a lot rising 2 m to the rear', { ground: GROUNDS.riseToRear }], + ['a cross slope', { ground: GROUNDS.cross }], + ['a 20 % hillside, the house off the lattice', { ground: GROUNDS.steep, at: [0.13, 0, 0.21] }], + [ + 'a 12 % hillside with a cross fall, the house turned 20 degrees', + { ground: ((x, z) => -z * 0.12 + x * 0.03) as Ground, at: [0.4, 0, -0.3], turn: 0.35 }, + ], + ] as const + for (const [name, lot] of lots) + for (const strategy of ['balance', 'fill', 'cut', 'keep'] as const) { + // Kept where it was drawn on a lot that rises 2 m, the house stands in a pit: next table. + if (strategy === 'keep' && lot.ground === GROUNDS.riseToRear) continue + test(`${name}, ${strategy}: under every wall the ground rises beyond, a low line 0.5 m wide stands 4 cm under its foot, falls to its ends and comes out`, () => { + const built = agentHouse(lot as never) + const { nodes, result } = runSettled(built, 'seat_house', { strategy }) + const read = transects(nodes) + const high = read.filter((each) => each.rises) + expect(high.length).toBeGreaterThan(8) + for (const each of high) { + expect(each.foot - each.low).toBeGreaterThanOrEqual(0.04) + expect(each.wide).toBeGreaterThanOrEqual(0.5) + } + // Along each stretch the line falls from one summit to both ends, 1 cm a metre. + for (const line of stretches(read)) { + const summit = line.indexOf(Math.max(...line)) + for (let i = 1; i < line.length; i++) { + const [nearer, farther] = + i <= summit ? [line[i] as number, line[i - 1] as number] : [line[i - 1], line[i]] + expect(farther as number).toBeLessThanOrEqual((nearer as number) + 0.011) + } + const span = Math.max(summit, line.length - 1 - summit) * 0.5 + expect(Math.max(...line) - Math.min(...line)).toBeGreaterThanOrEqual(0.008 * (span - 1)) + } + expect((result.lowLine as { outlets: number }).outlets).toBeGreaterThanOrEqual(1) + expect(result.unmet).toEqual([]) + // Nowhere within 4 m of the house does water stand: no closed hollow 3 cm deep. + const building = nodes.building_house as BuildingNode + const [cx, , cz] = building.position + const hollows = closedHollows((x, z) => groundAt(nodes, x, z), { + bounds: { minX: -15, minZ: -20, maxX: 15, maxZ: 20 }, + blocked: (x, z) => { + const dx = x - cx + const dz = z - cz + const lx = Math.cos(building.rotation[1]) * dx - Math.sin(building.rotation[1]) * dz + const lz = Math.sin(building.rotation[1]) * dx + Math.cos(building.rotation[1]) * dz + return Math.abs(lx) <= 6.05 && Math.abs(lz) <= 4.05 + }, + within: (x, z) => Math.hypot(x - cx, z - cz) < 11, + }) + expect(hollows).toEqual([]) + }) + } + + for (const [name, lot, strategy] of [ + [ + 'a bowl, the house at its bottom', + { ground: ((x, z) => 0.004 * (x * x + z * z)) as Ground }, + 'cut', + ], + [ + 'a lot rising 2 m, the house kept at the street height', + { ground: GROUNDS.riseToRear }, + 'keep', + ], + ] as const) + test(`${name}: the ground stands over the base on every side, the line has nowhere to run to, and the answer says so`, () => { + const { result } = runSettled(agentHouse(lot as never), 'seat_house', { strategy }) + expect((result.unmet as string[]).join(' ')).toContain('nowhere to run to') + }) +}) + +/* + * A house backed into a slope. Cut back at a batter, a 35 % hill behind a 12 m house costs 970 m3 + * and does not meet the ground within 15 m; held against the house it costs the excavation. + */ +describe('seat_house hillside: the ground over the base is held against the house', () => { + const hill = + (slope: number): Ground => + (_x, z) => + -z * slope + const breaks = (nodes: Nodes) => + Object.values(nodes).filter((node) => node.type === 'terrain-break') as (AnyNode & { + left: number | 'ground' + kind: string + })[] + const cases = [ + { name: 'a 20 % hill', slope: 0.2, input: {}, held: 1.4 }, + { name: 'a 35 % hill', slope: 0.35, input: {}, held: 2.4 }, + { name: 'a 50 % hill, batter 1:1 over the face', slope: 0.5, input: { run: 1 }, held: 2.4 }, + { + name: 'a 35 % hill, holding 1.5 m, batter 1:1.5 over the face', + slope: 0.35, + input: { retainM: 1.5, run: 1.5 }, + held: 1.2, + }, + ] as const + for (const { name, slope, input, held } of cases) + test(`${name}: the base on the low ground, a retaining face on the outline at the base, ${held} m and more of ground against the rear wall, the storey whole, the front door a step off the ground`, () => { + const built = agentHouse({ ground: hill(slope) }) + const { nodes, result } = runSettled(built, 'seat_house', { strategy: 'hillside', ...input }) + const base = result.groundAtWallsM as number + expect(base).toBeCloseTo(-4.05 * slope + 0.05, 1) + const [face] = breaks(nodes) + expect(breaks(nodes).length).toBe(1) + expect(face).toMatchObject({ kind: 'retaining', left: base, right: 'ground' }) + expect((result.hillside as { faceBreakId: string }).faceBreakId).toBe(face?.id as string) + // Just inside the rear wall the ground is the base; just outside it the hill stands held. + expect(groundAt(nodes, 0, -3.9)).toBeCloseTo(base, 2) + expect(groundAt(nodes, 0, -4.3) - base).toBeGreaterThanOrEqual(held) + const retainM = (input as { retainM?: number }).retainM ?? 2.7 + expect(groundAt(nodes, 0, -4.3) - base).toBeLessThanOrEqual(retainM + 0.02) + const read = facts(nodes) + expect(read.houses[0]).toMatchObject({ clearHeightM: 2.65, standing: 'at-grade' }) + expect(read.houses[0]?.doors[0]?.stepM).toBeLessThanOrEqual(0.2) + expect(read.retaining[0]?.heightM.max).toBeGreaterThanOrEqual(held) + expect(result.unmet).toEqual([]) + // Held, the hill costs a fraction of what cutting it back does. + const cut = runSettled(built, 'seat_house', { + strategy: 'cut', + run: (input as { run?: number }).run, + }).result + expect(moved(result)).toBeLessThan(0.6 * moved(cut)) + }) + + test('areawayM: a level areaway at the base between the walls and the face', () => { + const built = agentHouse({ ground: hill(0.35) }) + const { nodes, result } = runSettled(built, 'seat_house', { + strategy: 'hillside', + areawayM: 1.2, + }) + const base = result.groundAtWallsM as number + for (const z of [-4.3, -4.8, -5.2]) expect(groundAt(nodes, 0, z)).toBeCloseTo(base, 2) + expect(groundAt(nodes, 0, -5.4) - base).toBeGreaterThan(2.3) + }) + + test('groundM states the base: a house half in the hill, its low side on fill', () => { + const built = agentHouse({ ground: hill(0.35) }) + const { nodes, result } = runSettled(built, 'seat_house', { strategy: 'hillside', groundM: 0 }) + expect(result.groundAtWallsM).toBe(0) + expect(groundAt(nodes, 0, -4.3)).toBeGreaterThan(1) + expect(groundAt(nodes, 0, 4.5)).toBeCloseTo(-0.02, 1) + expect(result.fillVolumeM3 as number).toBeGreaterThan(40) + }) + + test('seated so again: nothing is written; seated another way: the face is taken away', () => { + const built = agentHouse({ ground: hill(0.35) }) + const seated = runSettled(built, 'seat_house', { strategy: 'hillside' }).nodes + expect(refusal(() => runSettled(seated, 'seat_house', { strategy: 'hillside' }))).toBe( + 'no_change', + ) + const again = runSettled(seated, 'seat_house', { strategy: 'cut', run: 1 }).nodes + expect(breaks(again)).toEqual([]) + expect(facts(again).retaining).toEqual([]) + }) + + test('seated another way first: the base is kept, and the answer says the slope of before is not known', () => { + const built = agentHouse({ ground: hill(0.35) }) + const balanced = runSettled(built, 'seat_house', {}) + const { result } = runSettled(balanced.nodes, 'seat_house', { strategy: 'hillside' }) + expect(result.groundAtWallsM).toBe(balanced.result.groundAtWallsM) + expect(result.movedBuildingByM).toBe(0) + expect((result.unmet as string[]).join(' ')).toContain('an earlier seating') + }) + + for (const [name, input] of [ + ['hillside with a declared wall', { strategy: 'hillside', wallM: 2 }], + ['retainM without hillside', { strategy: 'cut', retainM: 2 }], + ['areawayM without hillside', { areawayM: 1 }], + ['groundM with another strategy', { strategy: 'cut', groundM: 0 }], + ] as const) + test(`refused: ${name} (invalid_input)`, () => { + expect( + refusal(() => runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', input)), + ).toBe('invalid_input') + }) +}) + +describe('seat_house: a house with a level under its ground level', () => { + /** A hillside rising to the rear at 16 %: 1.3 m of fall across the house, a 2.7 m level under it. */ + const hill: Ground = (_x, z) => -0.16 * z + function withLower(ground: Ground = hill) { + let house = agentHouse({ ground }) + house = runSettled(house, 'add_level', { position: 'below', name: 'Lower', height: 2.7 }).nodes + const lower = Object.values(house).find( + (node): node is LevelNode => node.type === 'level' && node.name === 'Lower', + ) as LevelNode + house = runSettled(house, 'create_room', { + levelId: lower.id, + name: 'Rumpus', + polygon: [ + [-6, -4], + [6, -4], + [6, 4], + [-6, 4], + ], + doors: [{ wallIndex: 2, t: 0.5 }], + }).nodes + return { house, lower } + } + + test('walk_out on a fall of more than a storey: the high side is cut back to the base, nothing is unmet', () => { + // 40 %: 3.2 m of fall across the house, over the 2.7 m between the two levels. + const { house, lower } = withLower((_x, z) => -0.4 * z) + // A hill of 40 % is held by a batter steeper than itself: 1 to 1.5. + const { nodes, result } = runSettled(house, 'seat_house', { strategy: 'walk_out', run: 1.5 }) + const walkOut = result.walkOut as { lowerBaseM: number; fallAcrossHouseM: number } + const base = result.groundAtWallsM as number + expect(walkOut.fallAcrossHouseM).toBeGreaterThan(2.7) + expect(base).toBeCloseTo(walkOut.lowerBaseM + 2.7, 2) + expect(result.unmet).toEqual([]) + // Behind the house the hill stood 0.7 m over the base: cut back to it, then a batter up the hill. + expect(groundAt(house, 0, -4.5)).toBeGreaterThan(base + 0.6) + expect(groundAt(nodes, 0, -4.5)).toBeCloseTo(base, 1) + expect(result.cutVolumeM3 as number).toBeGreaterThan(20) + // Beside the low half of the house, and up the hill past the batter's daylight, the ground is its own. + for (const [x, z] of [ + [9.5, 2], + [-9.5, 3], + [0, -18.5], + ] as const) + expect(groundAt(nodes, x, z)).toBeCloseTo(groundAt(house, x, z), 2) + const read = facts(nodes) + const lowerDoor = read.houses[0]?.doors.find((door) => door.levelId === lower.id) + expect(lowerDoor?.stepM).toBeGreaterThanOrEqual(0) + expect(lowerDoor?.stepM).toBeLessThanOrEqual(0.2) + expect(read.houses[0]?.clearHeightM).toBe(2.65) + expect(read.open.map((finding) => finding.code)).not.toContain('ground_over_floor') + }) + + /* + * The trial team's stored scene (13 Nov): the main floor plate over a basement, thickness + * -1.419 m. The store reads a new top on a plate that stands over a level as a thicker or a + * thinner floor, its underside held: put back 1.47 m lower, the plate came out 1.42 m thinner + * than nothing. + */ + for (const [name, slope, input] of [ + ['the default, 16 %', 0.16, {}], + ['walk_out, 16 %', 0.16, { strategy: 'walk_out' }], + ['walk_out, 40 %', 0.4, { strategy: 'walk_out' }], + ] as const) + test(`${name}, through the store's rules: no floor is stored thinner than a slab can be`, () => { + const { house } = withLower((_x, z) => -slope * z) + const { nodes, result } = runInStore(house, 'seat_house', input) + expect((result.floorsPutBack as string[]).length).toBe(1) + for (const slab of Object.values(nodes).filter( + (node): node is SlabNode => node.type === 'slab', + )) + expect(slab.thickness).toBeGreaterThanOrEqual(MIN_SLAB_THICKNESS) + expect(facts(nodes).houses[0]?.clearHeightM).toBe(2.65) + }) + + test('a scene stored with such a floor: the facts say so, and seating the house gives the floor a slab thickness', () => { + const { house } = withLower() + const seated = runInStore(house, 'seat_house', { strategy: 'walk_out' }).nodes + const main = Object.values(seated).find( + (node): node is SlabNode => node.type === 'slab' && node.parentId === 'level_ground', + ) as SlabNode + const stored = { ...seated, [main.id]: { ...main, thickness: -1.4188 } as AnyNode } + expect(facts(stored).open).toContainEqual( + expect.objectContaining({ code: 'floor_without_thickness', id: main.id, value: -1.42 }), + ) + const { nodes, result } = runInStore(stored, 'seat_house', { strategy: 'keep' }) + expect(result.floorsPutBack).toEqual([main.id]) + expect((nodes[main.id] as SlabNode).thickness).toBe(0.05) + expect(facts(nodes).open.map((finding) => finding.code)).not.toContain( + 'floor_without_thickness', + ) + }) + + test('grade_around_house with no level named takes the lowest and digs the house a pit', () => { + const { house, lower } = withLower() + const { result } = runSettled(house, 'grade_around_house', {}) + expect(result.levelId).toBe(lower.id) + expect(result.padHeightM as number).toBeCloseTo(-2.8, 2) + expect(result.cutVolumeM3 as number).toBeGreaterThan(1000) + }) + + test('seat_house with no level named seats the ground level, and puts back the floor the ground had lifted', () => { + const { house } = withLower() + expect(facts(house).houses[0]?.clearHeightM).toBeCloseTo(2.01, 2) + const { nodes, result } = runSettled(house, 'seat_house', {}) + expect(result.levelId).toBe('level_ground') + expect(moved(result)).toBeLessThan(130) + expect((result.floorsPutBack as string[]).length).toBe(1) + expect(facts(nodes).houses[0]).toMatchObject({ + clearHeightM: 2.65, + floorOverGroundM: { min: 0.05, max: 0.05 }, + }) + }) + + test('walk_out: the lower level opens on the ground at the low side, the slope beside the house is its own', () => { + const { house, lower } = withLower() + const { nodes, result } = runSettled(house, 'seat_house', { strategy: 'walk_out' }) + const walkOut = result.walkOut as { + lowerLevelId: string + lowerBaseM: number + openSide: number[] + fallAcrossHouseM: number + storeyBelowM: number + } + // Downhill is +z (the street side); the lowest ground along that wall is about -0.7 m. + expect(walkOut).toMatchObject({ lowerLevelId: lower.id, openSide: [0, 1], storeyBelowM: 2.7 }) + expect(walkOut.lowerBaseM).toBeCloseTo(-0.73, 1) + expect(result.groundAtWallsM as number).toBeCloseTo(walkOut.lowerBaseM + 2.7, 2) + // The lower level's door opens a step over the apron; the apron is level at the lower base. + const read = facts(nodes) + const lowerDoor = read.houses[0]?.doors.find((door) => door.levelId === lower.id) + expect(lowerDoor?.stepM).toBeGreaterThanOrEqual(0) + expect(lowerDoor?.stepM).toBeLessThanOrEqual(0.2) + expect(groundAt(nodes, 0, 5.5)).toBeCloseTo(walkOut.lowerBaseM, 1) + // Beside and behind the house the hill keeps its slope: nothing moved 3 m off the side wall or behind. + for (const [x, z] of [ + [9.5, 0], + [-9.5, -2], + [0, -6], + ] as const) + expect(groundAt(nodes, x, z)).toBeCloseTo(groundAt(house, x, z), 2) + expect(moved(result)).toBeLessThan(40) + // The fall across the house is less than a storey: said, with the height left on the high side. + expect((result.unmet as string[])[0]).toContain('less than the 2.70 m between the two levels') + expect(read.houses[0]?.clearHeightM).toBe(2.65) + }) +}) + +describe('set_terrain_plane', () => { + const LOT_AREA = [ + [-15, -20], + [15, -20], + [15, 20], + [-15, 20], + ] + test('two points make a lot that falls from one to the other, level across', () => { + const { nodes, result } = runTool(slopedLot({ house: false }), 'set_terrain_plane', { + area: LOT_AREA, + through: [ + { at: [0, 20], heightM: 0 }, + { at: [0, -20], heightM: -2 }, + ], + }) + expect(result).toMatchObject({ slopePercent: 5, fallDirection: [0, -1], minM: -2, maxM: 0 }) + for (const [x, z, height] of [ + [0, 0, -1], + [-10, 0, -1], + [10, 10, -0.5], + [0, -19, -1.95], + ] as const) + expect(groundAt(nodes, x, z)).toBeCloseTo(height, 2) + }) + + test('three points fix a plane with a cross fall; one point is a level bench', () => { + const tilted = runTool(slopedLot({ house: false }), 'set_terrain_plane', { + area: LOT_AREA, + through: [ + { at: [-15, -20], heightM: 0 }, + { at: [15, -20], heightM: 3 }, + { at: [-15, 20], heightM: 2 }, + ], + }) + expect(groundAt(tilted.nodes, 0, 0)).toBeCloseTo(2.5, 2) + expect(tilted.result.slopePercent as number).toBeCloseTo(Math.hypot(10, 5), 1) + const bench = runTool(slopedLot({ ground: GROUNDS.steep, house: false }), 'set_terrain_plane', { + area: { center: [0, 0], radiusM: 4 }, + through: [{ at: [0, 0], heightM: 0.5 }], + }) + expect(bench.result).toMatchObject({ + slopePercent: 0, + fallDirection: [0, 0], + minM: 0.5, + maxM: 0.5, + }) + expect(groundAt(bench.nodes, 2, 2)).toBeCloseTo(0.5, 2) + expect(groundAt(bench.nodes, 0, 8)).toBeCloseTo(-1.6, 2) + }) + + test('outside the area the ground blends back over blendM', () => { + const { nodes } = runTool(slopedLot({ house: false }), 'set_terrain_plane', { + area: [ + [-5, -5], + [5, -5], + [5, 5], + [-5, 5], + ], + through: [{ at: [0, 0], heightM: 1 }], + blendM: 4, + }) + expect(groundAt(nodes, 0, 0)).toBeCloseTo(1, 2) + expect(groundAt(nodes, 7, 0)).toBeCloseTo(0.5, 2) + expect(groundAt(nodes, 9, 0)).toBeCloseTo(0, 2) + }) + + const refusals: [string, Record, string][] = [ + [ + 'two points that coincide', + { + area: LOT_AREA, + through: [ + { at: [0, 0], heightM: 0 }, + { at: [0, 0], heightM: 1 }, + ], + }, + 'invalid_input', + ], + [ + 'three points in a line', + { + area: LOT_AREA, + through: [ + { at: [0, 0], heightM: 0 }, + { at: [1, 1], heightM: 1 }, + { at: [2, 2], heightM: 3 }, + ], + }, + 'invalid_input', + ], + [ + 'an area past the property', + { + area: [ + [-20, -20], + [15, -20], + [15, 20], + [-20, 20], + ], + through: [{ at: [0, 0], heightM: 0 }], + }, + 'outside_property', + ], + [ + 'a plane the ground already lies on', + { area: LOT_AREA, through: [{ at: [0, 0], heightM: 0 }] }, + 'no_change', + ], + ] + for (const [name, input, code] of refusals) + test(`refused: ${name} (${code})`, () => { + expect(refusal(() => runTool(slopedLot({ house: false }), 'set_terrain_plane', input))).toBe( + code, + ) + }) +}) + +describe('grade_along_line', () => { + /** A lot that undulates along z: humps of 0.6 m every 19 m. */ + const humps: Ground = (_x, z) => 0.6 * Math.sin(z / 3) + const lot = (ground: Ground | null) => slopedLot({ ground, house: false }) + + test('with a slope limit the strip is no steeper, keeps the ground at both ends, cuts the humps and fills the dips', () => { + const before = lot(humps) + const { nodes, result } = runTool(before, 'grade_along_line', { + line: [ + [0, -18], + [0, 18], + ], + widthM: 3, + maxSlopePercent: 8, + }) + expect(result.groundSteepestPercent as number).toBeGreaterThan(18) + expect(result.steepestPercent as number).toBeLessThanOrEqual(8) + expect(result.startM).toBeCloseTo(groundAt(before, 0, -18), 2) + expect(result.endM).toBeCloseTo(groundAt(before, 0, 18), 2) + expect(result.deepestCutM as number).toBeGreaterThan(0.2) + expect(result.highestFillM as number).toBeGreaterThan(0.2) + // Level across the strip, and no steeper along it than the limit, as the ground now lies. + for (const z of [-12, -6, 0, 6, 12]) { + expect(groundAt(nodes, 1, z)).toBeCloseTo(groundAt(nodes, -1, z), 2) + expect(Math.abs(groundAt(nodes, 0, z + 1) - groundAt(nodes, 0, z))).toBeLessThanOrEqual( + 0.08 + 0.011, + ) + } + }) + + test('ends that the limit cannot join over the line are refused, with the length that would', () => { + let message = '' + try { + runTool(lot(GROUNDS.steep), 'grade_along_line', { + line: [ + [10, 20], + [10, 5], + ], + maxSlopePercent: 12, + }) + } catch (error) { + if (!isAgentRefusal(error)) throw error + expect(error.code).toBe('slope_limit_unreachable') + message = error.message + } + // 3 m of rise over 15 m: 12 % needs 25 m. + expect(message).toContain('25.0 m') + }) + + const strips: [string, number, (height: number) => void][] = [ + ['a swale', -0.3, (height) => expect(height).toBeCloseTo(-0.3, 2)], + ['a berm', 0.5, (height) => expect(height).toBeCloseTo(0.5, 2)], + ] + for (const [name, offsetM, onStrip] of strips) + test(`${name}: the strip stands ${offsetM} m off the ground, battered at 1:2 beside it, and stops at its ends`, () => { + const { nodes, result } = runTool(lot(GROUNDS.flat), 'grade_along_line', { + line: [ + [-10, 0], + [10, 0], + ], + widthM: 1, + offsetM, + }) + onStrip(groundAt(nodes, 0, 0)) + onStrip(groundAt(nodes, 5, 0.5)) + // Half a metre beyond the strip's edge the batter has made up 0.25 m of the offset. + expect(groundAt(nodes, 0, 1)).toBeCloseTo(offsetM - Math.sign(offsetM) * 0.25, 2) + expect(groundAt(nodes, 0, 3)).toBe(0) + expect(groundAt(nodes, 11, 0)).toBe(0) + expect(result.outline).toEqual([ + [-10, 0.5], + [10, 0.5], + [10, -0.5], + [-10, -0.5], + ]) + }) + + const refusals: [string, Record, string][] = [ + [ + 'a line past the property', + { + line: [ + [0, 0], + [0, 30], + ], + }, + 'outside_property', + ], + [ + 'an end height with no slope limit', + { + line: [ + [0, 0], + [0, 10], + ], + startHeightM: 1, + }, + 'invalid_input', + ], + [ + 'a strip on the ground of a flat lot', + { + line: [ + [0, 0], + [0, 10], + ], + }, + 'no_change', + ], + ] + for (const [name, input, code] of refusals) + test(`refused: ${name} (${code})`, () => { + expect(refusal(() => runTool(lot(GROUNDS.flat), 'grade_along_line', input))).toBe(code) + }) +}) + +describe('grade_along_line: a swale says where it leads', () => { + const cases: [string, Ground | null, Record, string, boolean][] = [ + [ + 'down a slope, stopped 0.4 m under the ground at its lower end: water stands there', + GROUNDS.steep, + { + line: [ + [10, -10], + [10, 10], + ], + }, + 'end', + true, + ], + [ + 'down a slope, falling a little less than the ground so that its lower end meets it: it comes out', + GROUNDS.steep, + { + line: [ + [10, -10], + [10, 10], + ], + maxSlopePercent: 18, + startHeightM: 1.6, + endHeightM: -2, + }, + 'end', + false, + ], + [ + 'along the contour of a slope: a trough that holds what runs into it', + GROUNDS.steep, + { + line: [ + [-10, 0], + [10, 0], + ], + }, + 'start', + true, + ], + [ + 'on level ground: a trough with no way out', + GROUNDS.flat, + { + line: [ + [-10, 0], + [10, 0], + ], + }, + 'start', + true, + ], + ] + for (const [name, ground, input, lowestAt, stands] of cases) + test(name, () => { + const lot = slopedLot({ ground: ground ?? (() => 0), house: false }) + const { result } = runTool(lot, 'grade_along_line', { widthM: 1, offsetM: -0.4, ...input }) + const drains = result.drains as { lowestAt: string; standingWaterM: number } + expect(drains.lowestAt).toBe(lowestAt) + expect(drains.standingWaterM > 0.1).toBe(stands) + }) + + test('a strip that is not lowered answers no drains', () => { + const lot = slopedLot({ ground: GROUNDS.steep, house: false }) + const { result } = runTool(lot, 'grade_along_line', { + line: [ + [10, -10], + [10, 10], + ], + offsetM: 0.3, + }) + expect(result.drains).toBeUndefined() + }) +}) + +describe('add_steps_to_ground', () => { + const cases: { name: string; scene: () => Nodes; door: string; steps: number }[] = [ + { + name: 'a floor 1 m over a falling lot, the front door', + scene: () => slopedLot({ ground: GROUNDS.fallToRear }), + door: 'door_front', + steps: 5, + }, + { + name: 'the same house, its rear door over lower ground', + scene: () => slopedLot({ ground: GROUNDS.fallToRear }), + door: 'door_rear', + steps: 8, + }, + { + name: 'a hillside, the front door', + scene: () => slopedLot({ ground: GROUNDS.steep }), + door: 'door_front', + steps: 7, + }, + { + name: 'a turned, moved house on a falling lot', + scene: () => slopedLot({ ground: GROUNDS.fallToRear, at: [2, 0, 1], turn: Math.PI / 3 }), + door: 'door_front', + steps: 6, + }, + { + name: 'a seated house: one step', + scene: () => runTool(slopedLot({ ground: GROUNDS.steep }), 'seat_house', {}).nodes, + door: 'door_front', + steps: 1, + }, + ] + for (const { name, scene, door, steps } of cases) + test(`${name}: the foot is on the ground, the top at the sill, the door served`, () => { + const { nodes, result } = runTool(scene(), 'add_steps_to_ground', { doorId: door }) + expect(result.stepCount).toBe(steps) + const read = facts(nodes) + const flight = read.steps.find((each) => each.stairId === result.stairId) + expect(flight?.footOverGroundM).toBeCloseTo(0, 2) + expect(flight?.doorId).toBe(door) + expect(Math.abs(flight?.topOverSillM ?? 1)).toBeLessThanOrEqual(0.02) + const served = read.houses[0]?.doors.find((each) => each.doorId === door) + expect(served?.servedBy).toBe(result.stairId as string) + const codes = read.open.filter( + (finding) => finding.id === door || finding.id === result.stairId, + ) + expect(codes).toEqual([]) + }) + + const refusals: [string, () => unknown, string][] = [ + [ + 'the ground over the sill', + () => + runTool(slopedLot({ ground: GROUNDS.riseToRear }), 'add_steps_to_ground', { + doorId: 'door_front', + }), + 'door_below_ground', + ], + [ + 'a node that is not a door', + () => runTool(slopedLot(), 'add_steps_to_ground', { doorId: 'wall_front' }), + 'not_a_door', + ], + [ + 'a door that is not there', + () => runTool(slopedLot(), 'add_steps_to_ground', { doorId: 'door_missing' }), + 'node_not_found', + ], + [ + 'a rise of 2 m or more', + () => + runTool( + slopedLot({ ground: GROUNDS.fallToRear, slabElevation: 1.4 }), + 'add_steps_to_ground', + { doorId: 'door_rear' }, + ), + 'steps_too_tall', + ], + ] + for (const [name, run, code] of refusals) + test(`refused: ${name} (${code})`, () => { + expect(refusal(run)).toBe(code) + }) +}) + +/* + * Steps and the seat. Steps made before a house was seated climbed to where its sill was; a house + * lifted by hand on a site with no relief is not carried by the ground, and its steps stood at the + * house's height (the trial team's n2e and n2d, 13 Nov). + */ +describe('steps to the ground and the seat of the house', () => { + const stepFindings = (nodes: Nodes) => + facts(nodes) + .open.map((finding) => finding.code) + .filter((code) => code.startsWith('steps_')) + + test('steps made before the house is seated are solved again from the new sill and ground', () => { + const built = agentHouse({ ground: GROUNDS.fallToRear }) + const door = facts(built).houses[0]?.doors.find((each) => each.stepM > 0.3) + const stepped = runSettled(built, 'add_steps_to_ground', { doorId: door?.doorId }).nodes + expect(stepFindings(stepped)).toEqual([]) + const before = facts(stepped).steps[0] + const { nodes, result } = runSettled(stepped, 'seat_house', {}) + const [resolved] = result.stepsResolved as { stairId: string; doorId: string; riseM?: number }[] + expect(resolved).toMatchObject({ stairId: before?.stairId, doorId: door?.doorId }) + expect(stepFindings(nodes)).toEqual([]) + const after = facts(nodes).steps[0] + if (resolved?.riseM === undefined) expect(after).toBeUndefined() + else { + expect(after?.topOverSillM).toBeCloseTo(0, 1) + expect(after?.footOverGroundM).toBeCloseTo(0, 1) + expect(resolved.riseM).toBeLessThan((before?.topM as number) - (before?.footM as number)) + } + }) + + test('a house lifted 0.9 m by hand on a site with no relief: its steps stand on the ground, their top at the sill', () => { + const lifted = slopedLot({ ground: GROUNDS.flat, at: [0, 0.9, 0] }) + const { nodes, result } = runTool(lifted, 'add_steps_to_ground', { doorId: 'door_front' }) + expect(result).toMatchObject({ groundAtFootM: 0, sillM: 1.05 }) + expect(stepFindings(nodes)).toEqual([]) + expect(facts(nodes).steps[0]).toMatchObject({ footM: 0, footOverGroundM: 0 }) + }) +}) + +describe('limits are checked before anything is sampled', () => { + /* + * These operations are reached from model-written input and from the MCP. Each bound is stated + * in the tool's text and refused before a station, a sample or a field is made: every case + * below answers in well under a second. + */ + const far = 1e9 + const many = Array.from({ length: 65 }, (_, i) => [i * 0.1, 0]) + const cases: [string, string, Record, string][] = [ + [ + 'grade_along_line: a line of a million kilometres', + 'grade_along_line', + { + scope: 'context', + line: [ + [0, 0], + [far, 0], + ], + }, + 'invalid_input', + ], + [ + 'grade_along_line: a line of 2.4 km inside its 500 m of the lot', + 'grade_along_line', + { + scope: 'context', + line: [ + [-500, -500], + [500, -500], + [500, 500], + [-500, 500], + ], + }, + 'sampling_limit', + ], + ['grade_along_line: 65 points', 'grade_along_line', { line: many }, 'invalid_input'], + [ + 'grade_along_line: a point that is not finite', + 'grade_along_line', + { + line: [ + [0, 0], + [Number.POSITIVE_INFINITY, 0], + ], + }, + 'invalid_input', + ], + [ + 'grade_along_line: a point that is not a number', + 'grade_along_line', + { + line: [ + [0, 0], + [Number.NaN, 5], + ], + }, + 'invalid_input', + ], + [ + 'grade_along_line: an end height of a million metres', + 'grade_along_line', + { + line: [ + [0, 0], + [0, 10], + ], + maxSlopePercent: 10, + endHeightM: 1e6, + }, + 'invalid_input', + ], + [ + 'grade_along_line: end heights whose batters would run 40 m out', + 'grade_along_line', + { + line: [ + [0, -15], + [0, 15], + ], + maxSlopePercent: 100, + startHeightM: 25, + endHeightM: 25, + run: 20, + }, + 'invalid_input', + ], + [ + 'grade_along_line: a 20 m strip along a 1.9 km line', + 'grade_along_line', + { + scope: 'context', + line: [ + [-480, -480], + [480, -480], + [480, 480], + ], + widthM: 20, + }, + 'sampling_limit', + ], + [ + 'set_terrain_plane: a circle of a million metres', + 'set_terrain_plane', + { + scope: 'context', + area: { center: [0, 0], radiusM: 1e6 }, + through: [{ at: [0, 0], heightM: 1 }], + }, + 'invalid_input', + ], + [ + 'set_terrain_plane: a circle of 900 m', + 'set_terrain_plane', + { + scope: 'context', + area: { center: [0, 0], radiusM: 900 }, + through: [{ at: [0, 0], heightM: 1 }], + }, + 'sampling_limit', + ], + [ + 'set_terrain_plane: a corner a million kilometres away', + 'set_terrain_plane', + { + scope: 'context', + area: [ + [0, 0], + [far, 0], + [0, far], + ], + through: [{ at: [0, 0], heightM: 1 }], + }, + 'invalid_input', + ], + [ + 'set_terrain_plane: a plane a million metres high', + 'set_terrain_plane', + { area: { center: [0, 0], radiusM: 3 }, through: [{ at: [0, 0], heightM: 1e6 }] }, + 'invalid_input', + ], + [ + 'set_terrain_plane: a plane through a point a million kilometres away', + 'set_terrain_plane', + { + area: { center: [0, 0], radiusM: 3 }, + through: [ + { at: [0, 0], heightM: 0 }, + { at: [far, 0], heightM: 1 }, + ], + }, + 'invalid_input', + ], + ['seat_house: ground a million metres up', 'seat_house', { groundM: 1e6 }, 'invalid_input'], + ['seat_house: a pad margin of a kilometre', 'seat_house', { marginM: 1000 }, 'invalid_input'], + ['seat_house: a reach of a kilometre', 'seat_house', { reachM: 1000 }, 'invalid_input'], + [ + 'seat_house hillside: holding a kilometre of ground', + 'seat_house', + { strategy: 'hillside', retainM: 1000 }, + 'invalid_input', + ], + [ + 'seat_house hillside: an areaway of a kilometre', + 'seat_house', + { strategy: 'hillside', areawayM: 1000 }, + 'invalid_input', + ], + [ + 'read_terrain_facts: a section to a point that is not finite', + 'read_terrain_facts', + { section: { from: [0, 0], to: [Number.POSITIVE_INFINITY, 0] } }, + 'invalid_input', + ], + ] + for (const [name, tool, input, code] of cases) + test(`${name}: ${code}, at once`, () => { + const started = performance.now() + expect(refusal(() => runTool(slopedLot({ ground: GROUNDS.steep }), tool, input))).toBe(code) + expect(performance.now() - started).toBeLessThan(1000) + }) + + /* + * The outline of the house is the scene's own slab, and a scene is model-written: every terrain + * sample is measured against every side of it, and the low line walks it station by station. + */ + const ringOf = (corners: number): [number, number][] => + Array.from({ length: corners }, (_, i) => [ + 5 * Math.cos((2 * Math.PI * i) / corners), + 3.5 * Math.sin((2 * Math.PI * i) / corners), + ]) + const houseWithOutline = (corners: number) => { + const house = slopedLot({ ground: GROUNDS.steep }) + return { ...house, slab_floor: { ...house.slab_floor, polygon: ringOf(corners) } as AnyNode } + } + test('seat_house: a floor outline of 20,000 corners is refused before it is graded against, at once', () => { + const started = performance.now() + expect(refusal(() => runTool(houseWithOutline(20_000), 'seat_house', {}))).toBe( + 'sampling_limit', + ) + expect(performance.now() - started).toBeLessThan(1000) + }) + + test('seat_house: a floor outline of 300 corners is seated, with no low line round it, and the answer says so', () => { + const started = performance.now() + const { result } = runTool(houseWithOutline(300), 'seat_house', { strategy: 'cut', reachM: 3 }) + expect(result.lowLine).toBeUndefined() + expect((result.unmet as string[]).join(' ')).toContain('300 corners') + expect(performance.now() - started).toBeLessThan(5000) + }) + + test('read_terrain_facts: a section of a million kilometres is cut at 2,000 stations and answers', () => { + const started = performance.now() + const { result } = runTool(slopedLot({ ground: GROUNDS.steep }), 'read_terrain_facts', { + section: { from: [0, 0], to: [far, 0] }, + }) + expect((result.section as { ground: unknown[] }).ground.length).toBeLessThanOrEqual(2001) + expect(performance.now() - started).toBeLessThan(2000) + }) +}) diff --git a/packages/core/src/agent-operations/terraforming.ts b/packages/core/src/agent-operations/terraforming.ts new file mode 100644 index 0000000000..7c8f475d36 --- /dev/null +++ b/packages/core/src/agent-operations/terraforming.ts @@ -0,0 +1,1374 @@ +import { z } from 'zod' +import { isAgentRefusal, refuse } from '../agent-tools/refusal' +import { + addStepsToGroundTool, + gradeAlongLineTool, + readTerrainFactsTool, + seatHouseTool, + setTerrainPlaneTool, +} from '../agent-tools/terraforming' +import { GROUND_SUPPORT_ID } from '../hooks/spatial-grid/support-host-id' +import { floorPlateAtGroundContact } from '../lib/floor-foundation-datum' +import { floorSlabsOf } from '../lib/grade-standing' +import { groundLevelOf } from '../lib/ground-level' +import { heightAt, quantize, type TerrainField } from '../lib/terrain-field' +import { closedHollows } from '../lib/terrain-hollows' +import { isLevelAtSiteDatum } from '../lib/terrain-support-query' +import { queryNodes } from '../runtime/node-queries' +import type { AnyNode, AnyNodeId, BuildingNode, DoorNode, LevelNode } from '../schema' +import { StairNode } from '../schema' +import { + DEFAULT_SLAB_ELEVATION, + DEFAULT_SLAB_THICKNESS, + MIN_SLAB_THICKNESS, +} from '../schema/nodes/slab' +import { + getLevelElevations, + getLevelFloorToFloorHeight, + levelPlaneWorldY, +} from '../services/storey' +import { pointInPolygon as onFloorPlate } from '../systems/slab/slab-support' +import { createDefaultStairSegment } from '../systems/stair/stair-flight' +import { getWallCurveFrameAt, getWallCurveLength } from '../systems/wall/wall-curve' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import { applySceneChanges } from './apply-changes' +import { pointInPolygon, polygonBounds, type Vec2 } from './plan-geometry' +import { + areaBounds, + depthInsideArea, + editingField, + fieldSamplesIn, + footprintOf, + gradeHouse, + gradeWallsOf, + groundOf, + houseOutline, + insideArea, + parseInput, + pointOf, + propertyOf, + requireInsideProperty, + type ShapingArea, + samplingOf, + terrainWriteOutcome, +} from './terrain' +import { sillOf, terrainFacts } from './terrain-facts' +import { + type GradeLowLine, + type LowLineFacts, + MAX_LOW_LINE_CORNERS, + outlineDistance, +} from './terrain-grade' +import type { AgentOperation, SceneChanges, SceneNodes } from './types' + +const factsInput = z.strictObject(readTerrainFactsTool.input) +const seatInput = z.strictObject(seatHouseTool.input) +const planeInput = z.strictObject(setTerrainPlaneTool.input) +const lineInput = z.strictObject(gradeAlongLineTool.input) +const stepsInput = z.strictObject(addStepsToGroundTool.input) + +/** How far from the property a point of a ground tool may lie, whatever its scope. */ +const NEAR_LOT_M = 500 +/** The most terrain samples one of these edits may visit: bounded before any is read or allocated. */ +const MAX_SAMPLES = 400_000 +/** The most point-against-edge tests one edit may make: samples times the corners of its area. */ +const MAX_EDGE_TESTS = 20_000_000 +/** The same for a house's own outline, which a seat grades against up to fifteen times. */ +const MAX_OUTLINE_TESTS = 2_000_000 + +/** Points are finite and near the property: nothing is sized from a coordinate before this. */ +export function requireNearLot(points: Vec2[], property: Vec2[], what: string): void { + const bounds = polygonBounds(property) + for (const [x, z] of points) + if ( + !(Number.isFinite(x) && Number.isFinite(z)) || + x < bounds.minX - NEAR_LOT_M || + x > bounds.maxX + NEAR_LOT_M || + z < bounds.minZ - NEAR_LOT_M || + z > bounds.maxZ + NEAR_LOT_M + ) + refuse( + 'invalid_input', + `${what} has a point that is not finite or lies more than ${NEAR_LOT_M} m from the property.`, + ) +} + +/** The samples a rectangle holds at the write lattice: refused over the limit, before the field is built. */ +export function requireSampleBudget( + bounds: { minX: number; minZ: number; maxX: number; maxZ: number }, + haloM: number, +): void { + const count = + (Math.ceil((bounds.maxX - bounds.minX + 2 * haloM) / 0.5) + 2) * + (Math.ceil((bounds.maxZ - bounds.minZ + 2 * haloM) / 0.5) + 2) + if (!Number.isFinite(count) || count > MAX_SAMPLES) + refuse( + 'sampling_limit', + `The edit would visit more than ${MAX_SAMPLES.toLocaleString('en-US')} terrain samples; use a smaller area or a shorter line.`, + ) +} + +const round = (value: number, digits = 2) => { + const k = 10 ** digits + return Math.round(value * k) / k +} + +/** `read_terrain_facts`: how what is built meets the ground (terrain-facts.ts), refused where there is no one ground. */ +export const readTerrainFacts: AgentOperation> = (nodes, raw) => { + const input = parseInput(factsInput, raw) + groundOf(nodes) + const section = input.section + ? { from: pointOf(input.section.from), to: pointOf(input.section.to) } + : undefined + const facts = terrainFacts(nodes, section ? { section } : {}) + if (!facts) refuse('no_site', 'The scene has no site to read the ground from.') + return { result: facts } +} + +const SEAT_DEFAULTS = { marginM: 1, padFallPercent: 5, apronM: 3 } as const + +/** + * The low line a seated house gets round its high side: a level bottom a lattice cell and a half + * wide, 15 cm under the pad's edge at its summit, falling 1 % along its length to where it comes + * out; before held ground it stands a metre + * off the face, 0.25 m under the ground, and the ground falls 8 % from the face to it. + */ +const LOW_LINE: GradeLowLine = { + widthM: 0.75, + fallPerM: 0.01, + underPadM: 0.15, + offM: 1, + depthM: 0.25, + faceFallPerM: 0.08, + daylightM: 8, +} + +/** Ground samples under an outline: its corners and a grid across it, half a metre or 200 lines a side. */ +function groundUnder(outline: Vec2[], ground: (x: number, z: number) => number) { + const bounds = polygonBounds(outline) + const stepX = Math.max(0.5, (bounds.maxX - bounds.minX) / 200) + const stepZ = Math.max(0.5, (bounds.maxZ - bounds.minZ) / 200) + let lowest = Number.POSITIVE_INFINITY + let highest = Number.NEGATIVE_INFINITY + let sum = 0 + let count = 0 + const take = (height: number) => { + lowest = Math.min(lowest, height) + highest = Math.max(highest, height) + sum += height + count++ + } + for (const [x, z] of outline) take(ground(x, z)) + for (let x = bounds.minX + stepX / 2; x < bounds.maxX; x += stepX) + for (let z = bounds.minZ + stepZ / 2; z < bounds.maxZ; z += stepZ) + if (pointInPolygon([x, z], outline)) take(ground(x, z)) + return { lowest, highest, mean: sum / count } +} + +/** The level a house is seated by: the one asked for, else the ground level of the scene's one building. */ +function seatLevel(nodes: SceneNodes, levelId: string | undefined) { + if (levelId !== undefined) return houseOutline(nodes, levelId) + const record = nodes as Record + const buildings = queryNodes(nodes, { type: 'building' }) + const ground = buildings.length === 1 ? groundLevelOf(record, buildings[0]?.id as string) : null + return houseOutline(nodes, ground?.level.id) +} + +/** The edge of an outline that looks most to `direction`, with its outward unit normal. */ +function edgeFacing(outline: Vec2[], direction: Vec2) { + const centre: Vec2 = [ + outline.reduce((sum, point) => sum + point[0], 0) / outline.length, + outline.reduce((sum, point) => sum + point[1], 0) / outline.length, + ] + let best: { from: Vec2; to: Vec2; normal: Vec2; score: number } | undefined + outline.forEach((from, index) => { + const to = outline[(index + 1) % outline.length] as Vec2 + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + if (length < 1e-6) return + let normal: Vec2 = [(to[1] - from[1]) / length, -(to[0] - from[0]) / length] + const mid: Vec2 = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2] + if ((mid[0] - centre[0]) * normal[0] + (mid[1] - centre[1]) * normal[1] < 0) + normal = [-normal[0], -normal[1]] + // The longest edge among those that face the direction squarely. + const facing = normal[0] * direction[0] + normal[1] * direction[1] + const score = facing > 0.7 ? facing + length / 1000 : facing - 1 + if (!best || score > best.score) best = { from, to, normal, score } + }) + return best as { from: Vec2; to: Vec2; normal: Vec2; score: number } +} + +/** + * `seat_house`: the height a house's ground level stands at against the ground under it, the + * building moved to it, the ground graded to meet it. The ground at the walls is brought to the + * level's base, as it lies on a flat site: a floor that rests on the ground then stands where it + * was drawn and the storey keeps its height. The grading is grade_around_house's (`gradeHouse`) + * with a pad that falls away from the walls; where the base goes is what this adds. + */ +export const seatHouse: AgentOperation> = (nodes, raw) => { + const input = parseInput(seatInput, raw) + const hillside = input.strategy === 'hillside' + if (input.strategy !== undefined && input.groundM !== undefined && !hillside) + refuse( + 'invalid_input', + 'Give a strategy or groundM, not both (hillside alone takes groundM, as the height of its base).', + ) + if (input.exactWall && !input.wallM) refuse('invalid_input', 'An exact wall needs wallM above 0.') + if (hillside && (input.wallM !== undefined || input.exactWall)) + refuse( + 'invalid_input', + 'hillside holds the ground with its own face (retainM, areawayM); wallM and exactWall are not for it.', + ) + if (!hillside && (input.retainM !== undefined || input.areawayM !== undefined)) + refuse('invalid_input', 'retainM and areawayM are for the hillside strategy.') + const record = nodes as Record + const { site, field } = groundOf(nodes) + const house = seatLevel(nodes, input.levelId) + const building = nodes[house.buildingId] as BuildingNode + const level = nodes[house.levelId] as LevelNode + const named = building.groundLevelId + if (named ? named !== level.id : level.level !== 0) + refuse( + 'invalid_input', + `${level.name ?? level.id} (${level.id}) is not the ground level of its building${named ? ` (${named} is)` : ''}: a house is seated by the level that stands on the ground.`, + ) + const marginM = input.marginM ?? SEAT_DEFAULTS.marginM + const strategy = hillside + ? 'hillside' + : input.groundM !== undefined + ? 'ground' + : (input.strategy ?? 'balance') + if (strategy === 'walk_out' && input.exactWall) + refuse( + 'invalid_input', + 'A walk-out keeps the natural slope beside the house; exactWall is not for it.', + ) + // A terrain break holds one height on its numeric side: inside an exact wall the pad is level. + const padFallPerM = input.exactWall + ? 0 + : (input.padFallPercent ?? SEAT_DEFAULTS.padFallPercent) / 100 + const ground = (x: number, z: number) => (field ? heightAt(field, x, z) : 0) + // The grading's extent, counted before it or its balance runs: the outline, the pad, the reach. + requireSampleBudget( + polygonBounds(house.footprint), + marginM + (input.reachM ?? 15) + (input.apronM ?? SEAT_DEFAULTS.apronM) + 0.5, + ) + // Every sample is measured against every side of the outline, and the balance grades up to + // fifteen times: the product is bounded before any of it runs. + { + const bounds = polygonBounds(house.footprint) + const reach = marginM + (input.reachM ?? 15) + (input.apronM ?? SEAT_DEFAULTS.apronM) + 0.5 + const samples = + (Math.ceil((bounds.maxX - bounds.minX + 2 * reach) / 0.5) + 2) * + (Math.ceil((bounds.maxZ - bounds.minZ + 2 * reach) / 0.5) + 2) + if (house.footprint.length * samples > MAX_OUTLINE_TESTS) + refuse( + 'sampling_limit', + `The outline of the house has ${house.footprint.length} corners: with the ${samples.toLocaleString('en-US')} terrain samples of this edit that is more than ${MAX_OUTLINE_TESTS.toLocaleString('en-US')} point-against-side tests. Seat a house with a simpler floor outline, or give a shorter reachM.`, + ) + } + const under = groundUnder(house.footprint, ground) + const baseM = levelPlaneWorldY(record, level.id) ?? 0 + const edgeDropM = padFallPerM * marginM + + // A walk-out: the level under the ground level opens on the ground at the low side. + const elevations = getLevelElevations(record) + const lower = + strategy === 'walk_out' + ? queryNodes(nodes, { type: 'level' }) + .filter( + (each) => + elevations.get(each.id)?.buildingId === building.id && each.level < level.level, + ) + .sort((a, b) => b.level - a.level)[0] + : undefined + if (strategy === 'walk_out' && !lower) + refuse( + 'invalid_input', + `A walk-out needs a level under ${level.name ?? level.id}: the one that opens on the ground at the low side.`, + ) + const storeyBelowM = lower ? baseM - (levelPlaneWorldY(record, lower.id) ?? baseM) : 0 + const open = lower + ? edgeFacing( + house.footprint, + input.openToward + ? pointOf(input.openToward) + : (() => { + // Downhill: against the ground's rise across the footprint. + const bounds = polygonBounds(house.footprint) + const dx = + ground(bounds.maxX, (bounds.minZ + bounds.maxZ) / 2) - + ground(bounds.minX, (bounds.minZ + bounds.maxZ) / 2) + const dz = + ground((bounds.minX + bounds.maxX) / 2, bounds.maxZ) - + ground((bounds.minX + bounds.maxX) / 2, bounds.minZ) + const length = Math.hypot(dx, dz) || 1 + return [-dx / length, -dz / length] as Vec2 + })(), + ) + : undefined + const apronM = input.apronM ?? SEAT_DEFAULTS.apronM + const apronOutline = open + ? ([ + open.from, + open.to, + [open.to[0] + open.normal[0] * apronM, open.to[1] + open.normal[1] * apronM], + [open.from[0] + open.normal[0] * apronM, open.from[1] + open.normal[1] * apronM], + ] as Vec2[]) + : undefined + // A house backed into the slope: its own face holds the ground, as high as the storey unless less is asked. + const retain = hillside + ? { + atM: input.areawayM ?? 0, + heightM: input.retainM ?? getLevelFloorToFloorHeight(level.id, record), + } + : undefined + const scopeInside = (points: Vec2[]) => + input.scope === 'context' || points.every((point) => pointInPolygon(point, propertyOf(site))) + if (apronOutline && !scopeInside(apronOutline)) + refuse( + 'outside_property', + 'The apron before the open side reaches outside the site polygon; give a shorter apronM or another openToward.', + ) + + const grading = (padHeightM: number, exactWall: boolean) => + gradeHouse( + nodes, + { + scope: input.scope, + footprint: house.footprint, + padHeightM, + marginM, + run: input.run, + reachM: input.reachM, + terraceRiserM: input.terraceRiserM, + wallM: input.wallM, + ...(exactWall ? { exactWall: true } : {}), + }, + { + padFallPerM, + replaceWalls: true, + // A declared wall at the pad's edge is the caller's own answer to the high side. + ...(input.wallM ? {} : { lowLine: LOW_LINE }), + ...(retain ? { retain } : {}), + ...(apronOutline + ? { + // The hill is cut back where it stands over the ground level's base and keeps its + // slope where it does not; the apron stands at the lower level's base. + cutOnly: true, + morePads: [{ outline: apronOutline, heightM: padHeightM - storeyBelowM, marginM: 0 }], + } + : {}), + }, + ) + /** Cut minus fill of the grading with the pad at `padHeightM`: falls as the pad rises. */ + const net = (padHeightM: number): number => { + try { + const result = grading(padHeightM, false).result as { + cutVolumeM3: number + fillVolumeM3: number + } + return result.cutVolumeM3 - result.fillVolumeM3 + } catch (error) { + if (isAgentRefusal(error) && error.code === 'no_change') return 0 + throw error + } + } + const balanced = (): number => { + let low = under.lowest - 0.5 + let high = under.highest + 0.5 + for (let i = 0; i < 14 && high - low > 0.005; i++) { + const mid = (low + high) / 2 + if (net(mid) > 0) low = mid + else high = mid + } + return (low + high) / 2 + } + // The lowest ground along the open side: the lower level's base stands on it. + const openGroundM = open + ? Math.min( + ...Array.from({ length: 21 }, (_, i) => + ground( + open.from[0] + ((open.to[0] - open.from[0]) * i) / 20 + open.normal[0] * 0.5, + open.from[1] + ((open.to[1] - open.from[1]) * i) / 20 + open.normal[1] * 0.5, + ), + ), + ) + : 0 + // Ground already level under the house at its base: the house is seated, and seating it + // again by the same rule leaves it where it stands. + // The ground at the pad's edge, a margin out from the middle of each side of the outline (a + // point a re-entrant corner brings nearer another wall is on the pad, not at its edge). + const padEdges = house.footprint.flatMap((from, index) => { + const to = house.footprint[(index + 1) % house.footprint.length] as Vec2 + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) || 1 + const mid: Vec2 = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2] + const out: Vec2 = [(to[1] - from[1]) / length, -(to[0] - from[0]) / length] + const sign = pointInPolygon([mid[0] + out[0] * 0.05, mid[1] + out[1] * 0.05], house.footprint) + ? -1 + : 1 + const at: Vec2 = [mid[0] + sign * out[0] * marginM, mid[1] + sign * out[1] * marginM] + return outlineDistance(at, house.footprint) >= marginM - 0.05 ? [ground(at[0], at[1])] : [] + }) + const seated = + under.highest - under.lowest < 0.03 && + Math.abs(under.lowest - baseM) < 0.08 && + (edgeDropM < 0.005 || + (padEdges.length > 0 && Math.max(...padEdges) <= baseM - edgeDropM + 0.02) || + // Backed into the slope already: the face that holds the ground is there. + (hillside && gradeWallsOf(nodes, site, house.footprint).length > 0)) + const wanted = + strategy === 'ground' || (hillside && input.groundM !== undefined) + ? (input.groundM as number) + : (strategy === 'fill' || strategy === 'cut' || strategy === 'balance' || hillside) && seated + ? baseM + : strategy === 'fill' + ? under.highest + edgeDropM + : strategy === 'cut' || hillside + ? under.lowest + edgeDropM + : strategy === 'keep' + ? baseM + : strategy === 'walk_out' + ? openGroundM + storeyBelowM + : // Level ground has nothing to balance: the pad's edge stands on it, as fill does, + // so the fall of the pad is a rise to the walls and not a hollow round the house. + under.highest - under.lowest < 0.03 + ? under.highest + edgeDropM + : balanced() + // A balance within 3 cm of where the house stands is not worth moving it for. + const padHeightM = round( + strategy === 'balance' && Math.abs(wanted - baseM) < 0.03 ? baseM : wanted, + ) + const movedBy = Math.abs(padHeightM - baseM) < 5e-4 ? 0 : round(padHeightM - baseM, 4) + + let graded: ReturnType | undefined + try { + graded = grading(padHeightM, input.exactWall === true) + } catch (error) { + if (!(isAgentRefusal(error) && error.code === 'no_change')) throw error + } + const [x, y, z] = building.position + const seats: { id: string; data: Partial }[] = + movedBy !== 0 || (strategy !== 'keep' && !named) + ? [ + { + id: building.id, + data: { + position: [x, round(y + movedBy, 4), z], + groundLevelId: level.id, + } as Partial, + }, + ] + : [] + // A floor the ground lifted before a level was put under it no longer follows the ground: it + // kept the lift. Seated, it goes back on the base of its level, where a floor is drawn. + // A plate a scene stored thinner than a slab can be takes a slab's thickness, whatever the strategy. + const putBack = floorSlabsOf(record, level).filter( + (slab) => + slab.plateRole === 'base' && + slab.floorHeight === undefined && + slab.referenceFloorElevation === undefined && + !floorPlateAtGroundContact(nodes as Record, slab) && + (slab.thickness < MIN_SLAB_THICKNESS || + (strategy !== 'keep' && Math.abs(slab.elevation - DEFAULT_SLAB_ELEVATION) > 0.01)), + ) + for (const slab of putBack) + seats.push({ + id: slab.id, + data: { + elevation: strategy === 'keep' ? slab.elevation : DEFAULT_SLAB_ELEVATION, + ...(slab.thickness < MIN_SLAB_THICKNESS ? { thickness: DEFAULT_SLAB_THICKNESS } : {}), + } as Partial, + }) + // A regrading that moves a few samples by a centimetre is the lattice, not a change. + const regraded = + graded && + ((graded.result as { cutVolumeM3: number }).cutVolumeM3 + + (graded.result as { fillVolumeM3: number }).fillVolumeM3 >= + 0.25 || + // A face is a change unless the one it replaces is the same face. + (graded.changes?.create ?? []).some(({ node }) => { + if (node.type !== 'terrain-break') return false + const replaced = (graded?.changes?.delete ?? []).map((id) => nodes[id]) + return !replaced.some( + (old) => + old?.type === 'terrain-break' && + old.left === node.left && + JSON.stringify(old.line) === JSON.stringify(node.line), + ) + }) || + (graded.changes?.delete?.length ?? 0) > + (graded.changes?.create ?? []).filter(({ node }) => node.type === 'terrain-break').length) + if (!regraded) graded = undefined + if (!graded && !seats.length) + refuse( + 'no_change', + 'The house already stands at that height and no terrain sample would move; nothing was written.', + ) + const changes: SceneChanges = { + ...(graded?.changes ?? {}), + update: [...(graded?.changes?.update ?? []), ...seats], + } + // Flights that climbed to this house's doors from the ground: the sills and the ground have + // moved, so each is solved again from the two, or taken away where its door now meets the ground. + const stepsResolved: { + stairId: string + doorId: string + stepCount?: number + riseM?: number + removed?: true + }[] = [] + const stepsUnmet: string[] = [] + // Only a flight this set makes: one straight segment standing on the ground, to a door that + // opens on the ground (a door with a stoop, a flight of several segments are left as drawn). + const readBefore = terrainFacts({ ...nodes }) + const flights = (readBefore?.steps ?? []).filter((flight) => { + const stair = nodes[flight.stairId] + const parent = stair?.parentId ? nodes[stair.parentId] : undefined + const door = readBefore?.houses + .flatMap((each) => each.doors) + .find((each) => each.doorId === flight.doorId) + return ( + stair?.type === 'stair' && + parent?.parentId === building.id && + stair.supportSlabId === GROUND_SUPPORT_ID && + stair.stairType === 'straight' && + (stair.children ?? []).length === 1 && + door?.outside === 'ground' + ) + }) + if (flights.length) { + const seatedNodes = applySceneChanges(nodes, changes) as SceneNodes + for (const flight of flights) { + const stair = nodes[flight.stairId] as StairNode + const doorId = flight.doorId as string + let solved: DoorSteps + try { + solved = solveDoorSteps(seatedNodes, doorId) + } catch (error) { + if (!isAgentRefusal(error)) throw error + continue + } + const storey = getLevelFloorToFloorHeight(solved.level.id, seatedNodes as never) + if (solved.rise < 0.05) { + changes.delete = [...(changes.delete ?? []), stair.id] + stepsResolved.push({ stairId: stair.id, doorId, removed: true }) + if (solved.rise < -0.02) + stepsUnmet.push( + `The ground outside ${doorId} now stands ${(-solved.rise).toFixed(2)} m over its sill; its steps were taken away.`, + ) + continue + } + if (solved.rise >= Math.min(storey, 2)) { + stepsUnmet.push( + `The sill of ${doorId} now stands ${solved.rise.toFixed(2)} m over the ground: its steps (${stair.id}) are left as they were, no longer a flight to the ground.`, + ) + continue + } + const segmentId = stair.children?.[0] + changes.update = [ + ...(changes.update ?? []), + { + id: stair.id, + data: { + position: [solved.foot[0], round(solved.footY, 4), solved.foot[1]], + rotation: solved.rotation, + totalRise: solved.rise, + stepCount: solved.stepCount, + railingMode: solved.stepCount > 3 ? 'both' : 'none', + } as Partial, + }, + ...(segmentId + ? [ + { + id: segmentId, + data: { + height: solved.rise, + length: solved.runM, + stepCount: solved.stepCount, + } as Partial, + }, + ] + : []), + ] + stepsResolved.push({ + stairId: stair.id, + doorId, + stepCount: solved.stepCount, + riseM: round(solved.rise, 3), + }) + } + } + const result = (graded?.result ?? {}) as Record + const daylight = result.daylight as + | { reached: boolean; farthestChangeM: number; outsideLotM2: number; outsideLotMaxM?: number } + | undefined + // What the grading could not do, said: the property line and the reach bound it. + const unmet: string[] = [] + if (daylight && daylight.outsideLotM2 > 0) + unmet.push( + `The batter wanted ${daylight.outsideLotM2.toFixed(0)} m2 beyond the property and stopped at its line: the ground steps up to ${(daylight.outsideLotMaxM ?? 0).toFixed(2)} m there.`, + ) + if (open && padHeightM - under.highest > 0.2) + unmet.push( + `The ground falls ${(under.highest - under.lowest).toFixed(2)} m across the house, less than the ${storeyBelowM.toFixed(2)} m between the two levels: the base of the ground level stands ${(padHeightM - under.highest).toFixed(2)} m over the highest ground under the house, and on that side the ground does not reach it.`, + ) + if (daylight && !daylight.reached) + unmet.push( + `The batter did not meet the ground within reachM (${(input.reachM ?? 15).toFixed(0)} m): a face stands where it stopped.`, + ) + const lowLine = result.lowLine as LowLineFacts | undefined + if (!input.wallM && house.footprint.length > MAX_LOW_LINE_CORNERS) + unmet.push( + `The outline of the house has ${house.footprint.length} corners, over the ${MAX_LOW_LINE_CORNERS} a low line is solved round: none was made, and the ground may run to the walls on the high side.`, + ) + if (seated && (strategy === 'cut' || strategy === 'fill' || hillside) && graded) + unmet.push( + `The ground under the house already lay level at the base of its ground level (${baseM.toFixed(2)} m), as an earlier seating leaves it: the base is kept there and the ground is graded from where it lies now. The slope that was there before that seating is not known to this one.`, + ) + if (lowLine?.closed) + unmet.push( + 'The ground stands over the base of the house on every side: the low line round it has nowhere to run to, and water stands in it unless a drain takes it.', + ) + else if (lowLine && lowLine.blindEnds > 0) + unmet.push( + `The low line round the high side did not come out on lower ground within ${LOW_LINE.daylightM} m at ${lowLine.blindEnds} of its ends: water stands there.`, + ) + const facts = { + strategy, + levelId: level.id, + buildingId: building.id, + groundAtWallsM: padHeightM, + movedBuildingByM: movedBy, + padEdgeM: round(padHeightM - padFallPerM * marginM), + groundUnderHouseM: { + lowest: round(under.lowest), + highest: round(under.highest), + mean: round(under.mean), + }, + cutVolumeM3: (result.cutVolumeM3 as number | undefined) ?? 0, + fillVolumeM3: (result.fillVolumeM3 as number | undefined) ?? 0, + netM3: (result.netM3 as number | undefined) ?? 0, + changedSamples: (result.changedSamples as number | undefined) ?? 0, + ...(graded + ? { + batterSlopeDeg: result.batterSlopeDeg, + steepestSampledSlopeDeg: result.steepestSampledSlopeDeg, + daylight: daylight + ? { + reached: daylight.reached, + farthestChangeM: daylight.farthestChangeM, + outsideLotM2: daylight.outsideLotM2, + } + : undefined, + ...(result.wall ? { wall: result.wall } : {}), + ...(result.terraces ? { terraces: result.terraces } : {}), + sampling: result.sampling, + } + : {}), + ...(lowLine + ? { + lowLine: { + lengthM: round(lowLine.lengthM, 1), + summitM: round(lowLine.summitM), + lowestM: round(lowLine.lowestM), + deepestCutM: round(lowLine.deepestCutM), + outlets: lowLine.outlets, + }, + } + : {}), + ...(retain + ? { + hillside: { + retainM: round(retain.heightM), + areawayM: retain.atM, + ...(result.face ? { faceBreakId: (result.face as { breakId: string }).breakId } : {}), + }, + } + : {}), + ...(open && lower + ? { + walkOut: { + lowerLevelId: lower.id, + lowerBaseM: round(padHeightM - storeyBelowM), + openSide: [round(open.normal[0]), round(open.normal[1])], + fallAcrossHouseM: round(under.highest - under.lowest), + storeyBelowM: round(storeyBelowM), + apron: apronOutline?.map(([px, pz]) => [round(px), round(pz)]), + }, + } + : {}), + ...(putBack.length ? { floorsPutBack: putBack.map((slab) => slab.id) } : {}), + ...(stepsResolved.length ? { stepsResolved } : {}), + unmet: [...unmet, ...stepsUnmet], + } + /** The house as it stands once the scene has settled: a floor that follows the ground has moved. */ + const settled = (after: SceneNodes) => { + // A copy of the record: what a host remembers against its own is not this operation's to trust. + const read = terrainFacts({ ...after }) + const seated = read?.houses.find((each) => each.buildingId === building.id) + const about = new Set([ + level.id, + ...(seated?.walls.map((wall) => wall.wallId) ?? []), + ...(seated?.doors.map((door) => door.doorId) ?? []), + ]) + // A level under the one seated, its door under the ground: this strategy did not open it. + const buried = (seated?.doors ?? []).filter( + (door) => door.levelId !== level.id && door.stepM < -0.02 && strategy !== 'walk_out', + ) + return { + ...facts, + unmet: [ + ...facts.unmet, + ...buried.map( + (door) => + `${door.doorId}, on the level under ${level.name ?? level.id}, has the ground ${(-door.stepM).toFixed(2)} m over its sill: this strategy seats the ground level and leaves the level under it in the ground; walk_out stands that level on the low ground.`, + ), + ], + floorM: seated?.floorM.max ?? padHeightM, + after: { + floorOverGroundM: seated?.floorOverGroundM ?? { min: 0, max: 0 }, + clearHeightM: seated?.clearHeightM ?? 0, + doors: (seated?.doors ?? []).map((door) => ({ + doorId: door.doorId, + levelId: door.levelId, + stepM: door.stepM, + outside: door.outside, + })), + open: (read?.open ?? []).filter((finding) => about.has(finding.id)), + }, + } + } + return { + result: settled(applySceneChanges(nodes, changes) as SceneNodes), + changes, + afterReconcile: (after) => ({ result: settled(after) }), + } +} + +type Plane = { at: (x: number, z: number) => number; gradient: Vec2 } + +/** The plane one, two or three points with heights give. */ +function planeThrough(points: { at: Vec2; heightM: number }[]): Plane { + const [a, b, c] = points + if (!a) refuse('invalid_input', 'A plane needs at least one point with a height.') + if (!b) return { at: () => a.heightM, gradient: [0, 0] } + if (!c) { + const dx = b.at[0] - a.at[0] + const dz = b.at[1] - a.at[1] + const lengthSq = dx * dx + dz * dz + if (lengthSq < 1e-9) refuse('invalid_input', 'The two points of the plane coincide.') + const rise = (b.heightM - a.heightM) / lengthSq + return { + at: (x, z) => a.heightM + rise * ((x - a.at[0]) * dx + (z - a.at[1]) * dz), + gradient: [rise * dx, rise * dz], + } + } + const ux = b.at[0] - a.at[0] + const uz = b.at[1] - a.at[1] + const vx = c.at[0] - a.at[0] + const vz = c.at[1] - a.at[1] + const det = ux * vz - vx * uz + if (Math.abs(det) < 1e-9) + refuse('invalid_input', 'The three points of the plane lie in a line; they do not fix a plane.') + const gx = ((b.heightM - a.heightM) * vz - (c.heightM - a.heightM) * uz) / det + const gz = ((c.heightM - a.heightM) * ux - (b.heightM - a.heightM) * vx) / det + return { + at: (x, z) => a.heightM + gx * (x - a.at[0]) + gz * (z - a.at[1]), + gradient: [gx, gz], + } +} + +/** `set_terrain_plane`: the ground over an area as one sloping plane, blended back outside it. */ +export const setTerrainPlane: AgentOperation> = (nodes, raw) => { + const input = parseInput(planeInput, raw) + const { site } = groundOf(nodes) + const property = propertyOf(site) + const area: ShapingArea = Array.isArray(input.area) + ? { kind: 'polygon', polygon: footprintOf(input.area) } + : { kind: 'circle', center: pointOf(input.area.center), radiusM: input.area.radiusM } + requireNearLot(area.kind === 'polygon' ? area.polygon : [area.center], property, 'The area') + requireNearLot( + input.through.map((point) => pointOf(point.at)), + property, + 'The plane', + ) + if (input.scope !== 'context') requireInsideProperty(area, property) + const plane = planeThrough( + input.through.map((point) => ({ at: pointOf(point.at), heightM: point.heightM })), + ) + const blendM = input.blendM ?? 0 + const bounds = areaBounds(area) + requireSampleBudget(bounds, blendM + 0.5) + // Each sample is tested against every edge of a polygon: the product is bounded too. + if (area.kind === 'polygon') { + const visits = + area.polygon.length * + (Math.ceil((bounds.maxX - bounds.minX + 2 * blendM) / 0.5) + 2) * + (Math.ceil((bounds.maxZ - bounds.minZ + 2 * blendM) / 0.5) + 2) + if (visits > MAX_EDGE_TESTS) + refuse( + 'sampling_limit', + `An area of ${area.polygon.length} corners over this extent takes more than ${MAX_EDGE_TESTS.toLocaleString('en-US')} edge tests; use fewer corners or a smaller area.`, + ) + } + const field = editingField(site, nodes, area, blendM + 0.5) + const samples = fieldSamplesIn(field, { + minX: bounds.minX - blendM, + minZ: bounds.minZ - blendM, + maxX: bounds.maxX + blendM, + maxZ: bounds.maxZ + blendM, + }).filter((sample) => input.scope === 'context' || pointInPolygon(sample.point, property)) + const heights = new Int16Array(field.heights) + const cellM2 = field.spacing * field.spacing + let cutVolumeM3 = 0 + let fillVolumeM3 = 0 + let changedSamples = 0 + let minM = Number.POSITIVE_INFINITY + let maxM = Number.NEGATIVE_INFINITY + for (const sample of samples) { + const beforeQ = field.heights[sample.index] ?? 0 + const beforeM = beforeQ * field.step + const onPlane = plane.at(sample.point[0], sample.point[1]) + const inside = insideArea(area, sample.point) + let target = beforeM + if (inside) target = onPlane + else if (blendM > 0) { + const depth = depthInsideArea(area, sample.point) + if (depth > -blendM) target = beforeM + (onPlane - beforeM) * (1 + depth / blendM) + } + const nextQ = quantize(field, target) + if (inside) { + minM = Math.min(minM, nextQ * field.step) + maxM = Math.max(maxM, nextQ * field.step) + } + if (nextQ === beforeQ) continue + heights[sample.index] = nextQ + changedSamples++ + const movedM = (nextQ - beforeQ) * field.step + if (movedM < 0) cutVolumeM3 += -movedM * cellM2 + else fillVolumeM3 += movedM * cellM2 + } + if (!Number.isFinite(minM)) + refuse( + 'no_change', + 'The area holds no terrain sample inside the property; nothing was written.', + ) + const slope = Math.hypot(plane.gradient[0], plane.gradient[1]) + return terrainWriteOutcome(site, nodes, field, heights, { + slopePercent: round(slope * 100, 2), + fallDirection: + slope < 1e-9 + ? [0, 0] + : [round(-plane.gradient[0] / slope, 3), round(-plane.gradient[1] / slope, 3)], + minM, + maxM, + cutVolumeM3, + fillVolumeM3, + netM3: cutVolumeM3 - fillVolumeM3, + changedSamples, + sampling: samplingOf(field, 'field_samples_in_area', samples.length), + }) +} + +const LINE_STATION_M = 0.5 +/** The longest line a strip is graded along: its stations are bounded by this before any is made. */ +const MAX_LINE_M = 2000 +/** The farthest a strip with its batters may reach to a side. */ +const MAX_STRIP_REACH_M = 40 + +type Station = { s: number; point: Vec2; ground: number; height: number } + +/** The breakpoints of a profile: the stations a straight line through their kept neighbours misses by 2 cm. */ +function breakpoints(stations: Station[]): Station[] { + const keep = new Set([0, stations.length - 1]) + const visit = (a: number, b: number) => { + let worst = 0 + let index = -1 + const from = stations[a] as Station + const to = stations[b] as Station + for (let i = a + 1; i < b; i++) { + const each = stations[i] as Station + const t = (each.s - from.s) / (to.s - from.s) + const miss = Math.max( + Math.abs(each.height - (from.height + (to.height - from.height) * t)), + Math.abs(each.ground - (from.ground + (to.ground - from.ground) * t)), + ) + if (miss > worst) { + worst = miss + index = i + } + } + if (index >= 0 && worst > 0.02) { + keep.add(index) + visit(a, index) + visit(index, b) + } + } + visit(0, stations.length - 1) + return [...keep].sort((a, b) => a - b).map((i) => stations[i] as Station) +} + +/** + * `grade_along_line`: a strip of ground along a line, level across, standing `offsetM` over the + * ground that was there and, with a slope limit, eased so no stretch is steeper. The eased profile + * is the mean of the gentlest profiles lying over and under the ground, held between the cones + * the limit allows from each end: it cuts the rises and fills the dips in like measure. + */ +export const gradeAlongLine: AgentOperation> = (nodes, raw) => { + const input = parseInput(lineInput, raw) + const { site, field: persisted } = groundOf(nodes) + const property = propertyOf(site) + const line = input.line.map(pointOf) + const widthM = input.widthM ?? 1.2 + const offsetM = input.offsetM ?? 0 + const run = input.run ?? 2 + if ( + (input.startHeightM !== undefined || input.endHeightM !== undefined) && + input.maxSlopePercent === undefined + ) + refuse( + 'invalid_input', + 'A stated end height needs maxSlopePercent: the strip is eased from that height to the ground within it.', + ) + // Bounds first: nothing below is sized from a coordinate, a length or a height before these. + requireNearLot(line, property, 'The line') + if (input.scope !== 'context' && !line.every((point) => pointInPolygon(point, property))) + refuse('outside_property', 'The line reaches outside the site polygon; nothing was written.') + const segments = line.slice(1).map((to, index) => { + const from = line[index] as Vec2 + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + if (length < 1e-6) refuse('invalid_input', 'Two consecutive points of the line coincide.') + return { from, to, length, count: Math.max(1, Math.ceil(length / LINE_STATION_M)), first: 0 } + }) + const totalLengthM = segments.reduce((sum, segment) => sum + segment.length, 0) + if (totalLengthM > MAX_LINE_M) + refuse( + 'sampling_limit', + `The line is ${totalLengthM.toFixed(0)} m long; a strip is graded along at most ${MAX_LINE_M} m.`, + ) + const ground = (x: number, z: number) => (persisted ? heightAt(persisted, x, z) : 0) + + // Stations along the line, the corners of the line among them: at most MAX_LINE_M / LINE_STATION_M + 64. + const stations: Station[] = [] + let travelled = 0 + segments.forEach((segment, index) => { + const { from, to, length, count } = segment + segment.first = index === 0 ? 0 : stations.length - 1 + for (let i = index === 0 ? 0 : 1; i <= count; i++) { + const point: Vec2 = [ + from[0] + ((to[0] - from[0]) * i) / count, + from[1] + ((to[1] - from[1]) * i) / count, + ] + const height = ground(point[0], point[1]) + stations.push({ + s: travelled + (length * i) / count, + point, + ground: height, + height: height + offsetM, + }) + } + travelled += length + }) + const first = stations[0] as Station + const last = stations[stations.length - 1] as Station + const lengthM = last.s + if (input.startHeightM !== undefined) first.height = input.startHeightM + if (input.endHeightM !== undefined) last.height = input.endHeightM + if (input.maxSlopePercent !== undefined) { + const slope = input.maxSlopePercent / 100 + const rise = Math.abs(last.height - first.height) + if (rise > slope * lengthM + 1e-6) + refuse( + 'slope_limit_unreachable', + `The ends differ by ${rise.toFixed(2)} m over ${lengthM.toFixed(1)} m (${((rise / lengthM) * 100).toFixed(1)} %): ${input.maxSlopePercent} % needs a line of at least ${(rise / slope).toFixed(1)} m between them, or other end heights.`, + { riseM: rise, lengthM, neededLengthM: rise / slope }, + ) + const under = stations.map((station) => station.height) + const over = [...under] + for (let i = 1; i < stations.length; i++) { + const reach = slope * ((stations[i] as Station).s - (stations[i - 1] as Station).s) + under[i] = Math.max(under[i] as number, (under[i - 1] as number) - reach) + over[i] = Math.min(over[i] as number, (over[i - 1] as number) + reach) + } + for (let i = stations.length - 2; i >= 0; i--) { + const reach = slope * ((stations[i + 1] as Station).s - (stations[i] as Station).s) + under[i] = Math.max(under[i] as number, (under[i + 1] as number) - reach) + over[i] = Math.min(over[i] as number, (over[i + 1] as number) + reach) + } + stations.forEach((station, i) => { + const fromStart = slope * station.s + const fromEnd = slope * (lengthM - station.s) + const low = Math.max(first.height - fromStart, last.height - fromEnd) + const high = Math.min(first.height + fromStart, last.height + fromEnd) + const eased = ((under[i] as number) + (over[i] as number)) / 2 + station.height = Math.max(low, Math.min(high, eased)) + }) + } + const deviation = Math.max( + ...stations.map((station) => Math.abs(station.height - station.ground)), + ) + const half = widthM / 2 + const haloM = half + run * deviation + 1 + if (haloM > MAX_STRIP_REACH_M) + refuse( + 'invalid_input', + `The strip stands up to ${deviation.toFixed(2)} m off the ground: with its batters it would reach ${haloM.toFixed(0)} m to a side, over the ${MAX_STRIP_REACH_M} m a strip may. Give end heights nearer the ground, a steeper side batter or a gentler slope limit.`, + ) + + const bounds = polygonBounds(line) + requireSampleBudget(bounds, haloM + 0.5) + const field: TerrainField = editingField( + site, + nodes, + { + kind: 'polygon', + polygon: [ + [bounds.minX, bounds.minZ], + [bounds.maxX, bounds.minZ], + [bounds.maxX, bounds.maxZ], + [bounds.minX, bounds.maxZ], + ], + }, + haloM + 0.5, + ) + const samples = fieldSamplesIn(field, { + minX: bounds.minX - haloM, + minZ: bounds.minZ - haloM, + maxX: bounds.maxX + haloM, + maxZ: bounds.maxZ + haloM, + }).filter((sample) => input.scope === 'context' || pointInPolygon(sample.point, property)) + const heights = new Int16Array(field.heights) + const cellM2 = field.spacing * field.spacing + let cutVolumeM3 = 0 + let fillVolumeM3 = 0 + let changedSamples = 0 + /** The strip's height `t` of the way along a segment of the line, between its two stations there. */ + const heightOn = (segment: (typeof segments)[number], t: number) => { + const along = Math.max(0, Math.min(1, t)) * segment.count + const index = Math.min(segment.count - 1, Math.floor(along)) + const a = stations[segment.first + index] as Station + const b = stations[segment.first + index + 1] as Station + return a.height + (b.height - a.height) * (along - index) + } + for (const sample of samples) { + // The nearest point of the line that is not beyond one of its ends: one test per segment of + // the line (64 points at most), not per station. + let nearest = Number.POSITIVE_INFINITY + let heightM = 0 + for (let i = 0; i < segments.length; i++) { + const segment = segments[i] as (typeof segments)[number] + const dx = segment.to[0] - segment.from[0] + const dz = segment.to[1] - segment.from[1] + const t = + ((sample.point[0] - segment.from[0]) * dx + (sample.point[1] - segment.from[1]) * dz) / + (segment.length * segment.length) + if ((i === 0 && t < 0) || (i + 1 === segments.length && t > 1)) continue + const clamped = Math.max(0, Math.min(1, t)) + const distance = Math.hypot( + sample.point[0] - (segment.from[0] + dx * clamped), + sample.point[1] - (segment.from[1] + dz * clamped), + ) + if (distance < nearest) { + nearest = distance + heightM = heightOn(segment, clamped) + } + } + if (nearest > haloM) continue + const beforeQ = field.heights[sample.index] ?? 0 + const beforeM = beforeQ * field.step + let target = beforeM + if (nearest <= half) target = heightM + else if (beforeM > heightM + 0.005) target = Math.min(beforeM, heightM + (nearest - half) / run) + else if (beforeM < heightM - 0.005) target = Math.max(beforeM, heightM - (nearest - half) / run) + const nextQ = quantize(field, target) + if (nextQ === beforeQ) continue + heights[sample.index] = nextQ + changedSamples++ + const movedM = (nextQ - beforeQ) * field.step + if (movedM < 0) cutVolumeM3 += -movedM * cellM2 + else fillVolumeM3 += movedM * cellM2 + } + + const steepest = (read: (station: Station) => number) => + stations.slice(1).reduce((max, station, i) => { + const previous = stations[i] as Station + return Math.max(max, Math.abs(read(station) - read(previous)) / (station.s - previous.s)) + }, 0) * 100 + // The strip's outline: its left side out, its right side back. + const side = (sign: number) => + stations.map((station, i): Vec2 => { + const a = stations[Math.max(0, i - 1)] as Station + const b = stations[Math.min(stations.length - 1, i + 1)] as Station + const length = Math.hypot(b.point[0] - a.point[0], b.point[1] - a.point[1]) || 1 + return [ + round(station.point[0] - (sign * half * (b.point[1] - a.point[1])) / length, 3), + round(station.point[1] + (sign * half * (b.point[0] - a.point[0])) / length, 3), + ] + }) + const corners = new Set(breakpoints(stations).map((station) => station.s)) + line.forEach((point) => { + const at = stations.find( + (station) => station.point[0] === point[0] && station.point[1] === point[1], + ) + if (at) corners.add(at.s) + }) + const kept = stations + .map((station, i) => ({ station, i })) + .filter(({ station }) => corners.has(station.s)) + const left = side(1) + const right = side(-1) + // A strip lowered into the ground is a swale: where it leads. Its lowest bottom, and the + // deepest closed hollow the strip leaves within a metre of it (none where it comes out). + let drains: + | { lowestAt: 'start' | 'end' | 'between'; lowestM: number; standingWaterM: number } + | undefined + if (offsetM < 0) { + let lowest = first + for (const station of stations) if (station.height < lowest.height - 1e-9) lowest = station + const after: TerrainField = { ...field, heights } + const reach = half + 1 + const [hollow] = closedHollows((x, z) => heightAt(after, x, z), { + bounds: { + minX: bounds.minX - haloM, + minZ: bounds.minZ - haloM, + maxX: bounds.maxX + haloM, + maxZ: bounds.maxZ + haloM, + }, + within: (x, z) => + segments.some((segment) => { + const dx = segment.to[0] - segment.from[0] + const dz = segment.to[1] - segment.from[1] + const t = Math.max( + 0, + Math.min( + 1, + ((x - segment.from[0]) * dx + (z - segment.from[1]) * dz) / + (segment.length * segment.length), + ), + ) + return Math.hypot(x - segment.from[0] - dx * t, z - segment.from[1] - dz * t) <= reach + }), + }) + drains = { + lowestAt: lowest.s < 0.26 ? 'start' : lowest.s > lengthM - 0.26 ? 'end' : 'between', + lowestM: round(lowest.height), + standingWaterM: round(hollow?.depthM ?? 0), + } + } + return terrainWriteOutcome(site, nodes, field, heights, { + lengthM: round(lengthM), + startM: round(first.height), + endM: round(last.height), + steepestPercent: round( + steepest((station) => station.height), + 1, + ), + groundSteepestPercent: round( + steepest((station) => station.ground), + 1, + ), + profile: breakpoints(stations).map((station) => ({ + sM: round(station.s), + heightM: round(station.height), + groundM: round(station.ground), + })), + outline: [ + ...kept.map(({ i }) => left[i] as Vec2), + ...kept.reverse().map(({ i }) => right[i] as Vec2), + ], + cutVolumeM3, + fillVolumeM3, + netM3: cutVolumeM3 - fillVolumeM3, + ...(drains ? { drains } : {}), + deepestCutM: round(Math.max(0, ...stations.map((station) => station.ground - station.height))), + highestFillM: round(Math.max(0, ...stations.map((station) => station.height - station.ground))), + changedSamples, + sampling: samplingOf(field, 'field_samples_along_line', samples.length), + }) +} + +export const STEP = { maxRiser: 0.19, comfort: 0.63, minGoing: 0.25, maxGoing: 0.35 } as const + +type DoorSteps = { + door: DoorNode + level: LevelNode + rise: number + stepCount: number + runM: number + sill: number + /** The foot in the level's frame, the flight's turn, the height of its foot over the level's own ground reference. */ + foot: Vec2 + rotation: number + footY: number + footSite: Vec2 + groundAtFootM: number + doorWidth: number +} + +/** + * The flight an exterior door needs: its top at the sill against the wall, its foot on the ground, + * the rise and the run solved from the two. Refuses a door that is not exterior; the caller reads + * `rise` for a door at, under or far over the ground. + */ +function solveDoorSteps(nodes: SceneNodes, doorId: string): DoorSteps { + const record = nodes as Record + const door = nodes[doorId] + if (!door) refuse('node_not_found', `No node ${doorId} in the scene.`) + if (door.type !== 'door') refuse('not_a_door', `Node ${doorId} is not a door.`) + const wall = door.parentId ? nodes[door.parentId] : undefined + const level = wall?.parentId ? nodes[wall.parentId] : undefined + const building = level?.parentId ? nodes[level.parentId] : undefined + if (wall?.type !== 'wall' || level?.type !== 'level' || building?.type !== 'building') + refuse('not_exterior', `Door ${door.id} is not on a wall of a building's level.`) + if (Math.abs(building.rotation[0]) > 1e-9 || Math.abs(building.rotation[2]) > 1e-9) + refuse('building_rotation_unsupported', 'The building tips out of the site plane.') + const { field } = groundOf(nodes) + const cos = Math.cos(building.rotation[1]) + const sin = Math.sin(building.rotation[1]) + const toSite = ([lx, lz]: Vec2): Vec2 => [ + cos * lx + sin * lz + building.position[0], + -sin * lx + cos * lz + building.position[2], + ] + const ground = (local: Vec2) => { + const [sx, sz] = toSite(local) + return field ? heightAt(field, sx, sz) : 0 + } + const length = getWallCurveLength(wall) + const { position, height, width: doorWidth } = door as DoorNode + const curve = getWallCurveFrameAt(wall, position[0] / length) + const faces = getWallFaceOffsets(wall) + const floors = floorSlabsOf(record, level) + const beside = (offset: number): Vec2 => [ + curve.point.x + curve.normal.x * offset, + curve.point.y + curve.normal.y * offset, + ] + const onFloor = ([lx, lz]: Vec2) => floors.some((slab) => onFloorPlate(lx, lz, slab.polygon)) + const a = onFloor(beside(faces.a + 0.15)) + const b = onFloor(beside(faces.b - 0.15)) + if (a === b) + refuse( + 'not_exterior', + `Door ${door.id} has a floor on ${a ? 'both sides' : 'neither side'}: steps to the ground climb to a door with a floor on one side only.`, + ) + // The floor is on the `b` side: out is along the normal, from the `a` face. + const outward = a ? -1 : 1 + const face = a ? faces.b : faces.a + const out = (distance: number) => beside(face + outward * distance) + const plane = levelPlaneWorldY(record, level.id) ?? 0 + const sill = sillOf( + wall, + { position, height }, + a ? beside(faces.a + 0.15) : beside(faces.b - 0.15), + floors, + plane, + nodes, + ) + let rise = sill - ground(out(0.3)) + let stepCount = 1 + let runM = STEP.maxGoing + for (let i = 0; i < 6; i++) { + // No riser over 0.19 m: a 0.25 m rise is two steps, not one tall one. + stepCount = Math.max(1, Math.ceil(rise / STEP.maxRiser - 1e-9)) + const going = Math.min( + STEP.maxGoing, + Math.max(STEP.minGoing, STEP.comfort - (2 * rise) / stepCount), + ) + runM = stepCount * going + const next = sill - ground(out(runM)) + if (Math.abs(next - rise) < 1e-3) { + rise = next + break + } + rise = next + } + const foot = out(runM) + const groundAtFootM = ground(foot) + return { + door: door as DoorNode, + level, + rise, + stepCount, + runM, + sill, + foot, + // A flight climbs along +z turned by its rotation: toward the wall is against the outward normal. + rotation: Math.atan2(-outward * curve.normal.x, -outward * curve.normal.y), + // A level the ground carries stands its flights on the ground; on any other the foot states + // the ground's height itself. + footY: isLevelAtSiteDatum(record, level.id) ? 0 : groundAtFootM - plane, + footSite: toSite(foot), + groundAtFootM, + doorWidth, + } +} + +/** + * `add_steps_to_ground`: the outside flight an exterior door needs, its top at the sill against + * the wall, its foot on the ground, the rise and the run solved from the two. + */ +export const addStepsToGround: AgentOperation> = (nodes, raw) => { + const input = parseInput(stepsInput, raw) + const solved = solveDoorSteps(nodes, input.doorId) + const { door, level, rise, stepCount, runM, sill, foot } = solved + if (rise < -0.02) + refuse( + 'door_below_ground', + `The ground outside ${door.id} stands ${(-rise).toFixed(2)} m over its sill: grade the ground down to the door before steps.`, + { stepM: rise }, + ) + if (rise < 0.05) + refuse( + 'steps_not_needed', + `The sill of ${door.id} is ${rise.toFixed(2)} m over the ground outside it; there is no rise to climb.`, + { stepM: rise }, + ) + const storey = getLevelFloorToFloorHeight(level.id, nodes as never) + if (rise >= Math.min(storey, 2)) + refuse( + 'steps_too_tall', + `The sill of ${door.id} is ${rise.toFixed(2)} m over the ground outside it: that is a flight between storeys, not steps to the ground, or ground to raise first.`, + { rise }, + ) + const width = input.width ?? solved.doorWidth + 0.4 + const segment = createDefaultStairSegment({ + width, + height: rise, + length: runM, + stepCount, + attachmentSide: 'front', + fillToFloor: true, + }) + const stair = StairNode.parse({ + name: `Steps to ${door.name ?? door.id}`, + parentId: level.id, + position: [foot[0], round(solved.footY, 4), foot[1]], + rotation: solved.rotation, + supportSlabId: GROUND_SUPPORT_ID, + stairType: 'straight', + fromLevelId: level.id, + toLevelId: null, + totalRise: rise, + width, + stepCount, + railingMode: stepCount > 3 ? 'both' : 'none', + children: [segment.id], + }) + return { + result: { + stairId: stair.id, + doorId: door.id, + stepCount, + riseM: round(rise, 3), + runM: round(runM, 3), + sillM: round(sill, 3), + foot: [round(solved.footSite[0], 3), round(solved.footSite[1], 3)], + groundAtFootM: round(solved.groundAtFootM, 3), + }, + changes: { + create: [ + { node: stair, parentId: level.id }, + { node: { ...segment, parentId: stair.id }, parentId: stair.id }, + ], + }, + } +} diff --git a/packages/core/src/agent-operations/terrain-break-facts.ts b/packages/core/src/agent-operations/terrain-break-facts.ts new file mode 100644 index 0000000000..41bc45fca8 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-break-facts.ts @@ -0,0 +1,18 @@ +import { terrainBreakFacts, terrainBreaksOf } from '../lib/terrain-breaks' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import type { AnyNode } from '../schema' +import type { SceneNodes } from './types' + +export function terrainFactsForNode(node: AnyNode, nodes: SceneNodes): Record { + const site = node.type === 'site' ? node : node.parentId ? nodes[node.parentId] : undefined + if (site?.type !== 'site' || (node.type !== 'site' && node.type !== 'terrain-break')) return {} + const field = persistedTerrainFieldOf(site, nodes) + if (!field) return node.type === 'site' ? { breaks: [] } : {} + return node.type === 'terrain-break' + ? { terrainBreak: terrainBreakFacts(node, field) } + : { + breaks: terrainBreaksOf(site, nodes).map((terrainBreak) => + terrainBreakFacts(terrainBreak, field), + ), + } +} diff --git a/packages/core/src/agent-operations/terrain-break-observations.test.ts b/packages/core/src/agent-operations/terrain-break-observations.test.ts new file mode 100644 index 0000000000..080c0282da --- /dev/null +++ b/packages/core/src/agent-operations/terrain-break-observations.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, test } from 'bun:test' +import { createTerrainField, encodeTerrainField } from '@pascal-app/core' +import { AGENT_OPERATIONS } from '@pascal-app/core/agent-operations' +import { + type AnyNode, + BuildingNode, + LevelNode, + SiteNode, + SlabNode, + TerrainBreakNode, + WallNode, +} from '@pascal-app/core/schema' + +type Nodes = Record +type BreakIssue = { + type: string + nodeId: string + breakId: string + sides: string[] + sideHeightRanges: { left: { minM: number; maxM: number }; right: { minM: number; maxM: number } } + dropM: { minM: number; maxM: number } + coordinateFrame: string +} +const context = { activeLevelId: null } + +function fixture() { + const field = createTerrainField({ cols: 41, rows: 41, spacing: 1 }) + const edge = TerrainBreakNode.parse({ + id: 'terrain-break_observed', + parentId: 'site_observed', + kind: 'cliff', + line: [ + [10, 0], + [10, 40], + ], + left: 5, + right: 2, + }) + const site = SiteNode.parse({ + id: 'site_observed', + children: ['building_observed', edge.id], + terrain: encodeTerrainField(field), + }) + // +90° about Y maps level-local (x,z) to Site (10+z,20-x). + const building = BuildingNode.parse({ + id: 'building_observed', + parentId: site.id, + children: ['level_observed'], + position: [10, 0, 20], + rotation: [0, Math.PI / 2, 0], + }) + const level = LevelNode.parse({ + id: 'level_observed', + parentId: building.id, + level: 0, + children: ['slab_observed', 'wall_observed'], + }) + const slab = SlabNode.parse({ + id: 'slab_observed', + parentId: level.id, + polygon: [ + [-2, -2], + [2, -2], + [2, 2], + [-2, 2], + ], + elevation: 5, + thickness: 0.2, + }) + // The centreline lies ON the break. The solid wall footprint straddles it. + const wall = WallNode.parse({ + id: 'wall_observed', + parentId: level.id, + start: [-2, 0], + end: [2, 0], + thickness: 0.5, + }) + const nodes: Nodes = Object.fromEntries( + [site, building, level, slab, wall, edge].map((node) => [node.id, node]), + ) + return { nodes, edge, site, slab, wall } +} + +function issues(nodes: Nodes): BreakIssue[] { + const result = AGENT_OPERATIONS.verify_scene(nodes, {}, context).result + return (result.issues as BreakIssue[]).filter((issue) => issue.type === 'terrain_break_straddled') +} + +// Expectations are Site-space solid intersection facts, not building-local +// centreline tests or a decision to reject/repair the authored scene. +describe('verify_scene terrain break observations', () => { + test('reports transformed slab solid and wall footprint with both side ranges and drop facts', () => { + const { nodes, edge } = fixture() + const frozen = JSON.stringify(nodes) + const observations = issues(nodes) + expect(observations.map((issue) => issue.nodeId).sort()).toEqual([ + 'slab_observed', + 'wall_observed', + ]) + for (const issue of observations) { + expect(issue).toMatchObject({ + type: 'terrain_break_straddled', + breakId: edge.id, + sides: ['left', 'right'], + sideHeightRanges: { left: { minM: 5, maxM: 5 }, right: { minM: 2, maxM: 2 } }, + dropM: { minM: 3, maxM: 3 }, + coordinateFrame: 'site', + }) + } + expect(JSON.stringify(nodes)).toBe(frozen) + }) + + test('touching the break is not straddling it, for either slab boundary or wall face', () => { + const { nodes, slab, wall } = fixture() + nodes[slab.id] = SlabNode.parse({ + ...slab, + polygon: [ + [-2, 0], + [2, 0], + [2, 2], + [-2, 2], + ], + }) + nodes[wall.id] = WallNode.parse({ ...wall, start: [-2, 0.25], end: [2, 0.25] }) + expect(issues(nodes)).toEqual([]) + }) + + test('a closed break entirely within a slab courtyard hole is not an occupied-slab observation', () => { + const { nodes, edge, slab, wall } = fixture() + nodes[edge.id] = TerrainBreakNode.parse({ + ...edge, + kind: 'retaining', + line: [ + [9, 19], + [11, 19], + [11, 21], + [9, 21], + [9, 19], + ], + }) + nodes[slab.id] = SlabNode.parse({ + ...slab, + holes: [ + [ + [-1.5, -1.5], + [-1.5, 1.5], + [1.5, 1.5], + [1.5, -1.5], + ], + ], + }) + delete nodes[wall.id] + nodes.level_observed = LevelNode.parse({ ...nodes.level_observed, children: [slab.id] }) + expect(issues(nodes)).toEqual([]) + }) + + test('old no-break scenes produce no terrain-break observation', () => { + const { nodes, edge, site } = fixture() + delete nodes[edge.id] + nodes[site.id] = SiteNode.parse({ + ...site, + children: site.children.filter((id) => id !== edge.id), + }) + expect(issues(nodes)).toEqual([]) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-break-observations.ts b/packages/core/src/agent-operations/terrain-break-observations.ts new file mode 100644 index 0000000000..f8bb985437 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-break-observations.ts @@ -0,0 +1,182 @@ +import { levelBuildingId } from '../building/level-duplication' +import { containsPoint, type MultiPolygon, type Ring } from '../lib/polygon-boolean' +import { terrainBreakHeightAt, terrainBreaksOf } from '../lib/terrain-breaks' +import type { TerrainField } from '../lib/terrain-field' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import { queryNodes } from '../runtime/node-queries' +import type { AnyNode, BuildingNode, TerrainBreakNode } from '../schema' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { levelIdOf } from './scene-queries' +import type { SceneNodes } from './types' +import { slabSurfaces } from './unguarded-drop-observations' + +type Point = [number, number] +type Footprint = { node: AnyNode; building: BuildingNode; solid: MultiPolygon } + +export type TerrainBreakObservation = { + type: 'terrain_break_straddled' + severity: 'info' + nodeId: string + breakId: string + nodeIds: string[] + coordinateFrame: 'site' + sides: ['left', 'right'] + sideHeightRanges: { left: { minM: number; maxM: number }; right: { minM: number; maxM: number } } + dropM: { minM: number; maxM: number } + sampling: { method: 'break_intervals'; maxStepM: number; sampleCount: number } + message: string +} + +const cross = (a: Point, b: Point) => a[0] * b[1] - a[1] * b[0] +const subtract = (a: Point, b: Point): Point => [a[0] - b[0], a[1] - b[1]] +const mix = (a: Point, b: Point, t: number): Point => [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, +] + +function siteRing(ring: Ring, building: BuildingNode): Ring { + const cos = Math.cos(building.rotation[1]) + const sin = Math.sin(building.rotation[1]) + return ring.map(([x, z]) => [ + cos * x + sin * z + building.position[0], + -sin * x + cos * z + building.position[2], + ]) +} + +function siteSolid(footprint: Footprint): MultiPolygon { + return footprint.solid.map(({ outer, holes }) => ({ + outer: siteRing(outer, footprint.building), + holes: holes.map((hole) => siteRing(hole, footprint.building)), + })) +} + +function footprints(nodes: SceneNodes): Footprint[] { + const result: Footprint[] = [] + for (const surface of slabSurfaces(nodes as Record)) { + const building = surface.buildingId ? nodes[surface.buildingId] : undefined + if (building?.type === 'building' && !building.rotation[0] && !building.rotation[2]) + result.push({ node: surface.slab, building, solid: surface.solid }) + } + for (const node of queryNodes(nodes, { type: 'wall' })) { + if (node.type !== 'wall') continue + const levelId = levelIdOf(nodes, node.id) + const level = levelId ? nodes[levelId] : undefined + const buildingId = level?.type === 'level' ? levelBuildingId(nodes, level) : null + const building = buildingId ? nodes[buildingId] : undefined + if (!levelId || building?.type !== 'building' || building.rotation[0] || building.rotation[2]) + continue + const walls = queryNodes(nodes, { type: 'wall' }).filter( + (candidate): candidate is AnyNode & { type: 'wall' } => + candidate.type === 'wall' && levelIdOf(nodes, candidate.id) === levelId, + ) + const outer = getWallPlanFootprint(node, calculateLevelMiters(walls)).map( + ({ x, y }): Point => [x, y], + ) + if (outer.length >= 3) result.push({ node, building, solid: [{ outer, holes: [] }] }) + } + return result +} + +function segmentParameters(from: Point, to: Point, solid: MultiPolygon): number[] { + const direction = subtract(to, from) + const values = [0, 1] + for (const polygon of solid) + for (const ring of [polygon.outer, ...polygon.holes]) + for (let index = 0; index < ring.length; index++) { + const start = ring[index] + const end = ring[(index + 1) % ring.length] + if (!start || !end) continue + const edge = subtract(end, start) + const denominator = cross(direction, edge) + if (Math.abs(denominator) < 1e-12) continue + const offset = subtract(start, from) + const t = cross(offset, edge) / denominator + const u = cross(offset, direction) / denominator + if (t > 0 && t < 1 && u >= 0 && u <= 1) values.push(t) + } + return [...new Set(values)].sort((a, b) => a - b) +} + +function straddledIntervals(terrainBreak: TerrainBreakNode, solid: MultiPolygon): [Point, Point][] { + const intervals: [Point, Point][] = [] + for (let index = 1; index < terrainBreak.line.length; index++) { + const from = terrainBreak.line[index - 1] + const to = terrainBreak.line[index] + if (!from || !to) continue + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + const normal: Point = [-(to[1] - from[1]) / length, (to[0] - from[0]) / length] + const values = segmentParameters(from, to, solid) + for (let span = 1; span < values.length; span++) { + const begin = values[span - 1] + const end = values[span] + if (begin === undefined || end === undefined || (end - begin) * length < 1e-6) continue + const midpoint = mix(from, to, (begin + end) / 2) + const probe = 1e-5 + const left: Point = [midpoint[0] + normal[0] * probe, midpoint[1] + normal[1] * probe] + const right: Point = [midpoint[0] - normal[0] * probe, midpoint[1] - normal[1] * probe] + if (containsPoint(solid, left) && containsPoint(solid, right)) + intervals.push([mix(from, to, begin), mix(from, to, end)]) + } + } + return intervals +} + +function intervalHeights( + terrainBreak: TerrainBreakNode, + field: TerrainField, + intervals: [Point, Point][], +) { + const left: number[] = [] + const right: number[] = [] + const drops: number[] = [] + for (const [from, to] of intervals) { + const steps = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[1] - from[1]) / 0.25)) + for (let index = 0; index <= steps; index++) { + const [x, z] = mix(from, to, index / steps) + const leftM = terrainBreakHeightAt(field, terrainBreak, 'left', x, z) + const rightM = terrainBreakHeightAt(field, terrainBreak, 'right', x, z) + left.push(leftM) + right.push(rightM) + drops.push(Math.abs(leftM - rightM)) + } + } + const range = (values: number[]) => ({ minM: Math.min(...values), maxM: Math.max(...values) }) + return { + sideHeightRanges: { left: range(left), right: range(right) }, + dropM: range(drops), + sampling: { method: 'break_intervals' as const, maxStepM: 0.25, sampleCount: drops.length }, + } +} + +export function terrainBreakObservations(nodes: SceneNodes): TerrainBreakObservation[] { + const result: TerrainBreakObservation[] = [] + const sites = queryNodes(nodes, { type: 'site' }).filter( + (site) => site.type === 'site' && terrainBreaksOf(site, nodes).length > 0, + ) + if (!sites.length) return result + const surfaces = footprints(nodes) + for (const site of sites) { + if (site.type !== 'site') continue + const field = persistedTerrainFieldOf(site, nodes) + if (!field) continue + for (const terrainBreak of terrainBreaksOf(site, nodes)) + for (const footprint of surfaces) { + if (footprint.building.parentId !== site.id) continue + const intervals = straddledIntervals(terrainBreak, siteSolid(footprint)) + if (!intervals.length) continue + const facts = intervalHeights(terrainBreak, field, intervals) + result.push({ + type: 'terrain_break_straddled', + severity: 'info', + nodeId: footprint.node.id, + breakId: terrainBreak.id, + nodeIds: [footprint.node.id, terrainBreak.id], + coordinateFrame: 'site', + sides: ['left', 'right'], + ...facts, + message: `${footprint.node.type} ${footprint.node.name ?? footprint.node.id} straddles terrain break ${terrainBreak.name ?? terrainBreak.id}: ground on left ${facts.sideHeightRanges.left.minM.toFixed(3)}–${facts.sideHeightRanges.left.maxM.toFixed(3)} m, right ${facts.sideHeightRanges.right.minM.toFixed(3)}–${facts.sideHeightRanges.right.maxM.toFixed(3)} m; drop ${facts.dropM.minM.toFixed(3)}–${facts.dropM.maxM.toFixed(3)} m.`, + }) + } + } + return result +} diff --git a/packages/core/src/agent-operations/terrain-break.ts b/packages/core/src/agent-operations/terrain-break.ts new file mode 100644 index 0000000000..c4b9323770 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-break.ts @@ -0,0 +1,89 @@ +import { z } from 'zod' +import { refuse } from '../agent-tools/refusal' +import { addTerrainBreakTool } from '../agent-tools/terrain' +import { pointInPolygon } from '../lib/polygon-relations' +import { + terrainBreakFacts, + terrainBreaksOf, + terrainLinePolygonCrossings, + validateTerrainBreak, + validateTerrainBreakLotSpan, +} from '../lib/terrain-breaks' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import { queryNodes } from '../runtime/node-queries' +import type { SiteNode } from '../schema/nodes/site' +import { TerrainBreakNode } from '../schema/nodes/terrain-break' +import type { AgentOperation, SceneNodes } from './types' + +const inputSchema = z.strictObject(addTerrainBreakTool.input) +type Point = [number, number] + +function segmentInside(from: Point, to: Point, polygon: Point[]): boolean { + if (!pointInPolygon(from, polygon) || !pointInPolygon(to, polygon)) return false + const cuts = [ + 0, + ...terrainLinePolygonCrossings(from, to, polygon).filter((t) => t > 0 && t < 1), + 1, + ] + return cuts.slice(1).every((end, i) => { + const start = cuts[i] + if (start === undefined) return false + const t = (start + end) / 2 + return pointInPolygon( + [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t], + polygon, + ) + }) +} + +export function validateTerrainBreakPlacement( + nodes: SceneNodes, + site: SiteNode, + boundary: TerrainBreakNode, + scope: 'lot' | 'context' = 'lot', +): void { + validateTerrainBreak(boundary) + const polygon = site.polygon.points + if (polygon.length < 3 || polygon.some((point) => !point.every(Number.isFinite))) + refuse('invalid_polygon', 'The site needs a finite property polygon.') + for (let i = 1; i < boundary.line.length; i++) { + const from = boundary.line[i - 1] + const to = boundary.line[i] + if (!from || !to) refuse('invalid_input', 'The terrain-break line has a missing point.') + if (scope === 'lot' && !segmentInside(from, to, polygon)) + refuse( + 'outside_property', + 'The terrain-break line leaves the property; use scope context explicitly.', + ) + } + validateTerrainBreakLotSpan(boundary, polygon) + terrainBreaksOf(site, { ...nodes, [boundary.id]: boundary }) +} + +export const addTerrainBreak: AgentOperation> = (nodes, raw) => { + const parsed = inputSchema.safeParse(raw) + if (!parsed.success) refuse('invalid_input', parsed.error.message) + const line = parsed.data.line.map((point): Point => { + const [x, z] = point + if (x === undefined || z === undefined || !Number.isFinite(x) || !Number.isFinite(z)) + refuse('invalid_input', 'A terrain-break point must have two finite coordinates [x,z].') + return [x, z] + }) + const input = { ...parsed.data, line } + validateTerrainBreak(input) + const sites = queryNodes(nodes, { type: 'site' }).filter( + (node): node is SiteNode => node.type === 'site', + ) + if (!sites.length) refuse('no_site', 'The scene has no site for a terrain break.') + if (sites.length !== 1) refuse('ambiguous_site', 'The scene has more than one site.') + const site = sites[0] + if (!site) refuse('no_site', 'The scene has no site for a terrain break.') + const boundary = TerrainBreakNode.parse({ ...input, parentId: site.id }) + validateTerrainBreakPlacement(nodes, site, boundary, input.scope) + const current = persistedTerrainFieldOf(site, nodes) + if (site.terrain && !current) refuse('no_terrain', 'The persisted terrain field cannot be read.') + const field = persistedTerrainFieldOf(site, { ...nodes, [boundary.id]: boundary }) + if (!field) refuse('no_terrain', 'The terrain-break field cannot be read.') + const result = terrainBreakFacts(boundary, field) + return { result, changes: { create: [{ node: boundary, parentId: site.id }] } } +} diff --git a/packages/core/src/agent-operations/terrain-breaks.test.ts b/packages/core/src/agent-operations/terrain-breaks.test.ts new file mode 100644 index 0000000000..fe6e596bff --- /dev/null +++ b/packages/core/src/agent-operations/terrain-breaks.test.ts @@ -0,0 +1,317 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + terrainBreaksOf, +} from '@pascal-app/core' +import { + AGENT_OPERATIONS, + addTerrainBreak, + applySceneChanges, + carveTerrainPad, +} from '@pascal-app/core/agent-operations' +import { + AGENT_TOOL_CONTRACTS, + addTerrainBreakTool, + isAgentRefusal, +} from '@pascal-app/core/agent-tools' +import { type AnyNode, SiteNode, TerrainTileNode } from '@pascal-app/core/schema' + +type Nodes = Record +const context = { activeLevelId: null } +const line: [number, number][] = [ + [4, 0], + [4, 8], +] +const pad: [number, number][] = [ + [2.13, 2.27], + [5.13, 2.27], + [5.13, 4.27], + [2.13, 4.27], +] + +function scene(spacing = 0.95): Nodes { + const field = createTerrainField({ cols: 20, rows: 20, spacing, origin: [-0.13, -0.27] }) + field.heights.fill(125) + const site = SiteNode.parse({ + id: 'site_breaks', + terrain: encodeTerrainField(field), + polygon: { + type: 'polygon', + points: [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ], + }, + }) + return { [site.id]: site } +} + +function fieldOf(nodes: Nodes) { + const field = persistedTerrainFieldOf(nodes.site_breaks as SiteNode, nodes) + if (!field) throw new Error('Expected authoritative terrain') + return field +} + +function applied(nodes: Nodes, outcome: ReturnType): Nodes { + if (!outcome.changes) throw new Error('Expected terrain operation changes') + return applySceneChanges(nodes, outcome.changes) as Nodes +} + +function refusalCode(call: () => unknown) { + try { + call() + } catch (error) { + return isAgentRefusal(error) ? error.code : String(error) + } + return null +} + +// The operation must persist semantic breaks, never approximate a cliff by +// distorting samples or inventing a thick slab. Original scene bytes are a +// read-only oracle, while the target terrace height comes from the request. +describe('add_terrain_break', () => { + test('a tile-covered keep-ground region with no same-side samples is refused, not replaced by datum', () => { + const samples = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + samples.heights.fill(500) + const tile = TerrainTileNode.parse({ + id: 'terrain-tile_isolated', + parentId: 'site_breaks', + ix: 0, + iz: 0, + heights: encodeTerrainField(samples).heights, + }) + const site = SiteNode.parse({ id: 'site_breaks', children: [tile.id] }) + const nodes: Nodes = { [site.id]: site, [tile.id]: tile } + const frozen = JSON.stringify(nodes) + expect(heightAt(fieldOf(nodes), 0.25, 0.25)).toBe(5) + const code = refusalCode(() => + addTerrainBreak( + nodes, + { + line: [ + [0.2, 0.2], + [0.3, 0.2], + [0.3, 0.3], + [0.2, 0.3], + [0.2, 0.2], + ], + kind: 'retaining', + left: 'ground', + right: 2, + }, + context, + ), + ) + expect(code).toBe('unsupported_geometry') + expect(JSON.stringify(nodes)).toBe(frozen) + expect(heightAt(fieldOf(nodes), 0.25, 0.25)).toBe(5) + }) + + test('one public contract creates a site child with exact numeric sides and measured facts', () => { + expect(AGENT_OPERATIONS.add_terrain_break).toBe(addTerrainBreak) + expect(AGENT_TOOL_CONTRACTS.filter((tool) => tool.name === 'add_terrain_break')).toHaveLength(1) + expect(addTerrainBreakTool.name).toBe('add_terrain_break') + const nodes = scene() + const frozen = JSON.stringify(nodes) + const outcome = addTerrainBreak(nodes, { line, kind: 'cliff', left: 5, right: 2 }, context) + expect(outcome.changes).toBeDefined() + const after = applied(nodes, outcome) + const breaks = terrainBreaksOf(after.site_breaks as SiteNode, after) + expect(breaks).toHaveLength(1) + const edge = breaks[0] + if (!edge) throw new Error('Expected the created terrain break') + expect(edge).toMatchObject({ parentId: 'site_breaks', line, kind: 'cliff', left: 5, right: 2 }) + expect((after.site_breaks as SiteNode).children).toContain(edge.id) + expect(outcome.result).toMatchObject({ + breakId: edge.id, + lengthM: 8, + left: { minM: 5, maxM: 5 }, + right: { minM: 2, maxM: 2 }, + dropMinM: 3, + dropMaxM: 3, + faceAreaM2: 24, + }) + expect(heightAt(fieldOf(after), 4 - 1e-7, 3)).toBe(5) + expect(heightAt(fieldOf(after), 4 + 1e-7, 3)).toBe(2) + expect((after.site_breaks as SiteNode).terrain).toEqual((nodes.site_breaks as SiteNode).terrain) + expect( + Object.values(after).filter((node) => node.type === 'terrain-tile' || node.type === 'slab'), + ).toEqual([]) + expect(JSON.stringify(nodes)).toBe(frozen) + }) + + test('refuses unsupported bends and internal endpoints honestly without changing the input', () => { + for (const unsupported of [ + [ + [0, 2], + [4, 3], + [8, 2], + ], + [ + [3, 3], + [5, 5], + ], + [ + [1, 1], + [7, 7], + [1, 7], + [7, 1], + [1, 1], + ], + ] satisfies [number, number][][]) { + const nodes = scene() + const frozen = JSON.stringify(nodes) + expect( + refusalCode(() => + addTerrainBreak( + nodes, + { + line: unsupported, + kind: 'cliff', + left: 5, + right: 'ground', + }, + context, + ), + ), + ).toBe('unsupported_geometry') + expect(JSON.stringify(nodes)).toBe(frozen) + } + }) + + test('refuses crossing breaks atomically, rather than guessing their precedence', () => { + const nodes = scene() + const first = addTerrainBreak(nodes, { line, kind: 'cliff', left: 5, right: 2 }, context) + const after = applied(nodes, first) + const frozen = JSON.stringify(after) + expect( + refusalCode(() => + addTerrainBreak( + after, + { + line: [ + [0, 4], + [8, 4], + ], + kind: 'retaining', + left: 3, + right: 'ground', + }, + context, + ), + ), + ).toBe('crossing_breaks') + expect(JSON.stringify(after)).toBe(frozen) + expect(terrainBreaksOf(after.site_breaks as SiteNode, after)).toHaveLength(1) + }) +}) + +describe('carve_terrain_pad discontinuous edges', () => { + test('a retaining pool terrace composes over the upper region of an existing cliff', () => { + const nodes = scene() + const cliff = addTerrainBreak(nodes, { line, kind: 'cliff', left: 5, right: 2 }, context) + const withCliff = applied(nodes, cliff) + const outcome = carveTerrainPad( + withCliff, + { + pad: [ + [1, 2], + [3, 2], + [3, 6], + [1, 6], + ], + padHeightM: 7, + edges: 'retaining', + }, + context, + ) + const after = applied(withCliff, outcome) + expect(terrainBreaksOf(after.site_breaks as SiteNode, after)).toHaveLength(2) + expect(heightAt(fieldOf(after), 2, 4)).toBe(7) + expect(heightAt(fieldOf(after), 3 + 1e-7, 4)).toBe(5) + expect(heightAt(fieldOf(after), 4 + 1e-7, 4)).toBe(2) + expect( + Object.values(after).filter((node) => node.type === 'slab' || node.type === 'terrain-tile'), + ).toEqual([]) + expect((after.site_breaks as SiteNode).terrain).toEqual((nodes.site_breaks as SiteNode).terrain) + }) + + for (const edges of ['retaining', 'cliff'] as const) { + for (const spacing of [0.5, 0.95]) { + test(`${edges} on a ${spacing} m legacy field makes an exact pool terrace without terrain deformation`, () => { + const nodes = scene(spacing) + const frozen = JSON.stringify(nodes) + const before = fieldOf(nodes) + const outcome = carveTerrainPad(nodes, { pad, padHeightM: 4, edges }, context) + const after = applied(nodes, outcome) + const breaks = terrainBreaksOf(after.site_breaks as SiteNode, after) + expect(breaks).toHaveLength(1) + const edge = breaks[0] + if (!edge) throw new Error('Expected the retaining or cliff pad boundary') + expect(edge).toMatchObject({ kind: edges, left: 4, right: 'ground' }) + expect(edge.line[0]).toEqual(edge.line.at(-1)) + let twiceArea = 0 + for (let i = 0; i + 1 < edge.line.length; i++) { + const a = edge.line[i] + const b = edge.line[i + 1] + if (!a || !b) throw new Error('Expected consecutive terrain break vertices') + twiceArea += a[0] * b[1] - b[0] * a[1] + } + expect(twiceArea).toBeCloseTo(12, 8) + const field = fieldOf(after) + for (const [x, z] of [ + [3, 3], + [2.13 + 1e-7, 3], + [5.13 - 1e-7, 3], + [4, 2.27 + 1e-7], + [4, 4.27 - 1e-7], + ] as const) + expect(Math.abs(heightAt(field, x, z) - 4)).toBeLessThanOrEqual(0.001) + for (const [x, z] of [ + [2.13 - 1e-7, 3], + [5.13 + 1e-7, 3], + [4, 2.27 - 1e-7], + [4, 4.27 + 1e-7], + [7, 7], + ] as const) + expect(heightAt(field, x, z)).toBe(heightAt(before, x, z)) + expect( + Object.values(after).filter( + (node) => node.type === 'slab' || node.type === 'terrain-tile', + ), + ).toEqual([]) + expect((after.site_breaks as SiteNode).terrain).toEqual( + (nodes.site_breaks as SiteNode).terrain, + ) + expect(JSON.stringify(nodes)).toBe(frozen) + }) + } + } + + test('retaining edges also preserve existing tile payloads byte-for-byte', () => { + const nodes = scene() + const field = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + field.heights.fill(125) + const tile = TerrainTileNode.parse({ + id: 'terrain-tile_existing', + parentId: 'site_breaks', + ix: 0, + iz: 0, + heights: encodeTerrainField(field).heights, + }) + nodes[tile.id] = tile + nodes.site_breaks = SiteNode.parse({ ...nodes.site_breaks, children: [tile.id] }) + const frozenTile = JSON.stringify(tile) + const outcome = carveTerrainPad(nodes, { pad, padHeightM: 4, edges: 'retaining' }, context) + const after = applied(nodes, outcome) + expect(JSON.stringify(after[tile.id])).toBe(frozenTile) + expect(Object.values(after).filter((node) => node.type === 'terrain-tile')).toHaveLength(1) + expect(heightAt(fieldOf(after), 3, 3)).toBe(4) + expect(heightAt(fieldOf(after), 6, 3)).toBe(1.25) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-facts.test.ts b/packages/core/src/agent-operations/terrain-facts.test.ts new file mode 100644 index 0000000000..4bbbe2e3f4 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-facts.test.ts @@ -0,0 +1,498 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, type LevelNode, WindowNode } from '../schema' +import { + agentHouse, + GROUNDS, + type Ground, + runSettled, + runTool, + slopedLot, +} from './__fixtures__/sloped-lots' +import { type TerrainFacts, terrainFacts } from './terrain-facts' + +/* + * What stands on the ground, against the ground, as facts. The lots are those of sloped-lots: a + * 12 x 8 m house whose floor is +0.15 over the building's origin, a front door toward the street + * (+z) and a rear door, the building as an agent leaves it (y = 0) unless a case seats it. + */ + +type Nodes = Record +const facts = (nodes: Nodes, options = {}) => terrainFacts(nodes, options) as TerrainFacts +const codes = (nodes: Nodes) => + facts(nodes) + .open.map((finding) => `${finding.code}:${finding.id}`) + .sort() +const built = (ground: Ground | null, extra = {}) => slopedLot({ ground, ...extra }) +const after = (nodes: Nodes, ...calls: [string, Record][]) => + calls.reduce((scene, [tool, input]) => runTool(scene, tool, input).nodes, nodes) + +describe('terrain facts: the house against the ground', () => { + const cases: { name: string; scene: () => Nodes; open: string[] }[] = [ + { name: 'a flat lot, the house as built', scene: () => built(GROUNDS.flat), open: [] }, + { + name: 'a flat lot, the house turned and off centre', + scene: () => built(GROUNDS.flat, { at: [3, 0, -2], turn: Math.PI / 6 }), + open: [], + }, + { + name: 'the ground 1 m under the house: the floor is in the air and both doors open over it', + scene: () => built(GROUNDS.fallToRear), + open: [ + 'door_above_ground:door_front', + 'door_above_ground:door_rear', + 'floor_in_air:level_ground', + 'ground_falls_to_wall:wall_front', + ], + }, + { + name: 'the ground 1 m over the house: it stands over the floor and over both sills', + scene: () => built(GROUNDS.riseToRear), + open: [ + 'door_below_ground:door_front', + 'door_below_ground:door_rear', + 'ground_falls_to_wall:wall_rear', + 'ground_over_floor:level_ground', + 'room_light_behind_earth:zone_living', + ], + }, + { + name: 'a hillside through the house: buried behind, in the air in front', + scene: () => built(GROUNDS.steep), + open: [ + 'door_above_ground:door_front', + 'door_below_ground:door_rear', + 'floor_in_air:level_ground', + 'ground_falls_to_wall:wall_rear', + 'ground_over_floor:level_ground', + ], + }, + { + name: 'seated on the mean ground by set_ground_level: the uphill edge and its door are under it', + scene: () => + after(built(GROUNDS.fallToRear), ['set_ground_level', { levelId: 'level_ground' }]), + open: [ + 'door_above_ground:door_rear', + 'door_below_ground:door_front', + 'ground_falls_to_wall:wall_front', + 'ground_over_floor:level_ground', + ], + }, + { + name: 'the ground brought to the house by grade_around_house: nothing open', + scene: () => after(built(GROUNDS.fallToRear), ['grade_around_house', {}]), + open: [], + }, + { + name: 'a house cut into rising ground by grade_around_house: the bank runs to every wall', + scene: () => after(built(GROUNDS.riseToRear), ['grade_around_house', {}]), + open: [ + 'ground_falls_to_wall:wall_front', + 'ground_falls_to_wall:wall_left', + 'ground_falls_to_wall:wall_rear', + 'ground_falls_to_wall:wall_right', + ], + }, + ] + for (const { name, scene, open } of cases) + test(name, () => { + expect(codes(scene())).toEqual(open) + }) + + test('the numbers of a house standing 1 m over a falling lot', () => { + const [house] = facts(built(GROUNDS.fallToRear)).houses + expect(house?.floorM).toEqual({ min: 0.15, max: 0.15 }) + expect(house?.groundM).toEqual({ lowest: -1.2, highest: -0.8, mean: -1 }) + expect(house?.floorOverGroundM).toEqual({ min: 0.95, max: 1.35 }) + expect(house?.floorInAirShare).toBe(1) + const front = house?.walls.find((wall) => wall.wallId === 'wall_front') + expect(front).toMatchObject({ side: 'front', outward: [0, 1], lengthM: 12 }) + expect(front?.fallAwayPercent).toEqual({ min: -5, max: -5 }) + expect(house?.walls.find((wall) => wall.wallId === 'wall_rear')).toMatchObject({ + side: 'rear', + fallAwayPercent: { min: 5, max: 5 }, + fallsTowardLengthM: 0, + }) + const door = house?.doors.find((each) => each.doorId === 'door_front') + expect(door).toMatchObject({ at: [0, 4.65], sillM: 0.15, outside: 'ground' }) + expect(door?.outsideM).toBeCloseTo(-0.77, 1) + expect(door?.stepM).toBeCloseTo(0.92, 1) + }) + + test('a turned, moved building is read where it stands', () => { + const [house] = facts(built(GROUNDS.fallToRear, { at: [3, 0, -2], turn: Math.PI / 2 })).houses + // A quarter turn puts the plate's long side along z: the ground under it runs from z -8 to 4. + expect(house?.groundM.lowest).toBeCloseTo(-1.4, 2) + expect(house?.groundM.highest).toBeCloseTo(-0.8, 2) + // The front door (building-local [0, 4.65]) now looks along +x. + expect(house?.doors.find((door) => door.doorId === 'door_front')?.at).toEqual([7.65, -2]) + }) + + test('a flat site says so and measures against the datum', () => { + const read = facts(built(GROUNDS.flat)) + expect(read.hasTerrain).toBe(false) + expect(read.note).toContain('flat datum') + expect(read.houses[0]?.doors.map((door) => door.stepM)).toEqual([0.15, 0.15]) + expect(read.earthwork).toBeUndefined() + }) +}) + +describe('terrain facts: what is laid and built on the ground', () => { + // Skipped in this cut: it needs add_site_surface (site flatwork, a sibling of terrain), which this PR does not carry. + test.skip('a flat drive over a hillside hangs in the air; a draped walk follows it too steeply', () => { + const scene = after( + built(GROUNDS.steep), + [ + 'add_site_surface', + { + kind: 'driveway', + corners: [ + [8.5, 5], + [11.5, 20], + ], + levelId: 'level_ground', + }, + ], + [ + 'add_site_surface', + { + kind: 'path', + terrainMode: 'draped', + corners: [ + [-11, 5], + [-9.8, 20], + ], + levelId: 'level_ground', + }, + ], + ) + const read = facts(scene) + const drive = read.surfaces.find((surface) => surface.kind === 'driveway') + const walk = read.surfaces.find((surface) => surface.kind === 'walk') + expect(drive).toMatchObject({ mode: 'flat', overGroundM: { min: 1.05, max: 4.05 } }) + expect(walk).toMatchObject({ mode: 'draped', overGroundM: { min: 0.03, max: 0.03 } }) + expect(walk?.slopePercent.max).toBeCloseTo(20, 0) + const open = read.open.map((finding) => finding.code) + expect(open).toContain('surface_off_ground') + expect(open).toContain('surface_steep') + }) + + // Skipped in this cut: it needs add_steps (outside steps, a sibling of terrain), which this PR does not carry. + test.skip('steps of the right rise from the right foot serve the door; a wrong rise misses its sill', () => { + const house = built(GROUNDS.fallToRear) + const door = facts(house).houses[0]?.doors.find((each) => each.doorId === 'door_front') + expect(door?.stepM).toBeCloseTo(0.92, 1) + // Five risers on goings of 0.26: a run of 1.31 m, the foot that far before the wall's face. + const fitted = after(house, ['add_steps', { x: 0, z: 5.4, rise: 0.92, rotation: 180 }]) + const served = facts(fitted) + expect(served.steps[0]).toMatchObject({ footOverGroundM: 0, doorId: 'door_front' }) + expect(Math.abs(served.steps[0]?.topOverSillM ?? 1)).toBeLessThanOrEqual(0.05) + expect(served.open.map((finding) => `${finding.code}:${finding.id}`)).not.toContain( + 'door_above_ground:door_front', + ) + const short = facts(after(house, ['add_steps', { x: 0, z: 5.4, rise: 0.5, rotation: 180 }])) + expect(short.open.map((finding) => finding.code)).toContain('steps_miss_door') + }) + + test('a ramp whose start is left at height 0 over ground 4 m lower is off the ground', () => { + const scene = after(built(GROUNDS.steep), [ + 'add_ramp', + { start: [-3, 20], segments: [{ type: 'line', end: [-3, 6] }], width: 3, endHeight: 0.1 }, + ]) + const read = facts(scene) + expect(read.ramps[0]?.ends[0]).toMatchObject({ at: [-3, 20], heightM: 0 }) + expect(read.ramps[0]?.ends[0]?.overGroundM).toBeGreaterThan(3.9) + expect(read.open.map((finding) => finding.code)).toContain('ramp_end_off_ground') + }) + + test('a retained pad states the height it holds; a filled pad left as a lattice step is a bank no face holds', () => { + const pad = { + pad: [ + [-7, -5], + [7, -5], + [7, 5], + [-7, 5], + ], + padHeightM: 0, + } + const held = facts( + after(built(GROUNDS.riseToRear), ['carve_terrain_pad', { ...pad, edges: 'retaining' }]), + ) + expect(held.retaining).toEqual([ + expect.objectContaining({ + kind: 'retaining', + lengthM: 48, + heightM: { min: 0.75, max: 1.25 }, + }), + ]) + expect(held.open.map((finding) => finding.code)).not.toContain('steep_bank') + const loose = facts( + after(built(GROUNDS.fallToRear), ['carve_terrain_pad', { ...pad, blendM: 3 }]), + ) + expect(loose.retaining).toEqual([]) + expect(loose.banks.areaM2).toBeGreaterThan(10) + expect(loose.open.map((finding) => finding.code)).toContain('steep_bank') + }) + + test('the earth a grading moved is stated against the ground before it', () => { + const graded = runTool(built(GROUNDS.fallToRear), 'grade_around_house', {}) + const read = facts(graded.nodes) + expect(read.earthwork?.against).toBe('base_field') + expect(read.earthwork?.cutM3).toBeCloseTo(0, 0) + expect(read.earthwork?.fillM3).toBeCloseTo(graded.result.fillVolumeM3 as number, -1) + }) +}) + +describe('terrain facts: a section through the house and the ground', () => { + test('a plane is two breakpoints, the floor a span with its clearance', () => { + const read = facts(built(GROUNDS.fallToRear), { section: { from: [0, -20], to: [0, 20] } }) + expect(read.section?.ground).toEqual([ + { sM: 0, groundM: -2 }, + { sM: 40, groundM: 0 }, + ]) + expect(read.section?.floors).toEqual([ + { + slabId: 'slab_floor', + fromM: 16, + toM: 24, + topM: 0.15, + overGroundM: { min: 0.95, max: 1.35 }, + }, + ]) + }) + + test('a graded section keeps the pad, the batter and the daylight line as breakpoints', () => { + const graded = after(built(GROUNDS.fallToRear), ['grade_around_house', {}]) + const section = facts(graded, { section: { from: [0, -20], to: [0, 20] } }).section + const at = (sM: number) => section?.ground.find((point) => point.sM === sM)?.groundM + // The pad: 1 m beyond the walls (z -5 to 5 is 15 to 25 m along), level at 0. + expect(at(15)).toBe(0) + expect(at(25)).toBe(0) + expect(section?.ground.length).toBeLessThan(12) + expect(section?.floors[0]?.overGroundM).toEqual({ min: 0.15, max: 0.15 }) + }) +}) + +/* + * Earth against a house: a house backed into a slope holds ground on its walls. The facts say how + * much on each wall, what its windows and rooms keep, and whether water runs to the wall; none of + * it is a finding by itself. + */ +describe('terrain facts: a house that holds earth', () => { + const hill: Ground = (_x, z) => -z * 0.35 + /** The fixture house with a window in its rear wall, sill 0.9 m over the floor, 1.2 m high. */ + const withRearWindow = () => + slopedLot({ + ground: hill, + extra: [ + WindowNode.parse({ + id: 'window_rear', + parentId: 'wall_rear', + wallId: 'wall_rear', + position: [3, 1.5, 0], + height: 1.2, + width: 1.2, + }), + ], + }) + const wallOf = (read: TerrainFacts, id: string) => + read.houses[0]?.walls.find((wall) => wall.wallId === id) + + test('backed into a 35 % hill: 2.3 m of earth on the rear wall, the side walls from that to none, a low line 0.04 m and more under each foot, no water to a wall', () => { + const read = facts(runTool(built(hill), 'seat_house', { strategy: 'hillside' }).nodes) + const rear = wallOf(read, 'wall_rear') + expect(rear?.earthAgainstM.max).toBeGreaterThanOrEqual(2.3) + expect(rear?.earthLengthM).toBeCloseTo(12, 0) + expect(rear?.buriedShare).toBeGreaterThan(0.8) + expect(rear?.lowLineUnderFootM.min).toBeGreaterThanOrEqual(0.04) + expect(rear?.fallsTowardLengthM).toBe(0) + const side = wallOf(read, 'wall_left') + expect(side?.earthAgainstM.max).toBeGreaterThan(2) + expect(side?.earthAgainstM.mean).toBeLessThan(side?.earthAgainstM.max as number) + expect(wallOf(read, 'wall_front')?.earthAgainstM.max).toBe(0) + // The rear door of the fixture house is in the wall that holds the earth. + expect(read.open.map((finding) => `${finding.code}:${finding.id}`)).toEqual([ + 'door_below_ground:door_rear', + ]) + }) + + test('across an areaway the wall holds none: the face stands 1.2 m before it, 2.3 m and more high, and the ground over the face does not run to the wall', () => { + const read = facts( + runTool(built(hill, { doors: false }), 'seat_house', { strategy: 'hillside', areawayM: 1.2 }) + .nodes, + ) + const rear = wallOf(read, 'wall_rear') + expect(rear?.earthAgainstM.max).toBe(0) + expect(rear?.faceBefore?.distanceM).toBeGreaterThanOrEqual(1) + expect(rear?.faceBefore?.distanceM).toBeLessThanOrEqual(1.4) + expect(rear?.faceBefore?.heightM).toBeGreaterThanOrEqual(2.3) + expect(read.open.map((finding) => finding.code)).toEqual([]) + }) + + for (const [name, input, under] of [ + ['held to the storey: the ground stands over the sill of the rear window', {}, true], + ['held 0.8 m: the window is clear', { retainM: 0.8, run: 1 }, false], + ] as const) + test(`a window in the wall that holds the earth, ${name}`, () => { + const read = facts( + runTool(withRearWindow(), 'seat_house', { strategy: 'hillside', ...input }).nodes, + ) + const window = wallOf(read, 'wall_rear')?.windows[0] + expect(window?.windowId).toBe('window_rear') + expect((window?.underGroundM as number) > 0).toBe(under) + expect(read.open.some((finding) => finding.code === 'window_below_ground')).toBe(under) + // The room keeps its front door on the open side: it is not a room behind earth. + expect(read.houses[0]?.roomsAgainstEarth[0]).toMatchObject({ + zoneId: 'zone_living', + declared: false, + }) + expect(read.open.some((finding) => finding.code === 'room_light_behind_earth')).toBe(false) + }) +}) + +describe('terrain facts: one floor, read one way', () => { + test('a seat read before the scene settles and after: the same door steps', () => { + const house = agentHouse({ ground: GROUNDS.fallToRear }) + const steps = (nodes: Nodes) => facts(nodes).houses[0]?.doors.map((door) => door.stepM) + const unsettled = runTool(house, 'seat_house', {}).nodes + const settled = runSettled(house, 'seat_house', {}).nodes + expect(steps(unsettled)).toEqual(steps(settled)) + expect(Math.max(...(steps(settled) as number[]))).toBeLessThanOrEqual(0.2) + }) +}) + +describe('terrain facts: a drive is read the way it is travelled', () => { + // Skipped in this cut: it needs add_site_surface (site flatwork, a sibling of terrain), which this PR does not carry. + test.skip('a bed graded to 18 %, a driveway draped on its outline: no steeper than the bed along it, the batter at its edges apart', () => { + const lot = slopedLot({ ground: GROUNDS.steep }) + const bed = runTool(lot, 'grade_along_line', { + line: [ + [-13, 18], + [-7, 6], + [-13, -6], + ], + widthM: 3, + maxSlopePercent: 18, + }) + expect(bed.result.steepestPercent as number).toBeLessThanOrEqual(18) + const paved = runTool(bed.nodes, 'add_site_surface', { + kind: 'driveway', + terrainMode: 'draped', + polygon: (bed.result.outline as number[][]).map(([x, z]) => [x, z]), + }).nodes + const drive = facts(paved).surfaces.find((surface) => surface.kind === 'driveway') + expect(drive?.slopePercent.max).toBeLessThanOrEqual(18.6) + expect(drive?.crossFallPercent?.mean).toBeLessThan(3) + expect(drive?.steepestGroundPercent).toBeGreaterThanOrEqual(drive?.slopePercent.max as number) + expect(codes(paved).filter((code) => code.startsWith('surface_steep'))).toEqual([]) + }) +}) + +describe('terrain facts and verify_scene on a house that walks out', () => { + const lower = (house: Nodes) => + Object.values(house).find( + (node): node is LevelNode => node.type === 'level' && node.name === 'Lower', + ) as LevelNode + function withLower() { + let house = agentHouse({ ground: (_x, z) => -0.16 * z }) + house = runSettled(house, 'add_level', { position: 'below', name: 'Lower', height: 2.7 }).nodes + return runSettled(house, 'create_room', { + levelId: lower(house).id, + name: 'Rumpus', + polygon: [ + [-6, -4], + [6, -4], + [6, 4], + [-6, 4], + ], + doors: [{ wallIndex: 2, t: 0.5 }], + }).nodes + } + const issues = (nodes: Nodes) => + (runTool(nodes, 'verify_scene', {}).result.issues as { type: string; message: string }[]).map( + (issue) => issue.type, + ) + + test('walked out: the ground level stands over the low ground on purpose; verify_scene does not call it unseated, the facts do not call its floor in the air', () => { + const { nodes } = runSettled(withLower(), 'seat_house', { strategy: 'walk_out' }) + expect(issues(nodes)).not.toContain('ground_level_unseated') + expect(codes(nodes).filter((code) => code.startsWith('floor_in_air'))).toEqual([]) + }) + + test('seated by its ground level alone: the door of the level under it stays in the ground, and the answer says which strategy opens it', () => { + const { result } = runSettled(withLower(), 'seat_house', {}) + expect((result.unmet as string[]).join(' ')).toContain('walk_out stands that level') + }) +}) + +describe('terrain facts: faces and drops', () => { + /** A 6 m cliff across a level lot at z = -6: the plateau behind it, the low ground before it. */ + const cliffed = (at: [number, number, number]) => + runTool(slopedLot({ ground: () => 0, at }), 'add_terrain_break', { + line: [ + [-15, -6], + [15, -6], + ], + kind: 'cliff', + left: 0, + right: 6, + }).nodes + for (const [name, at, stands, finding] of [ + [ + 'a house on the plateau, its front wall 1 m from the edge', + [0, 6, -11], + { standsAt: 'top', distanceM: 1 }, + true, + ], + [ + 'the same house 4 m back from the edge', + [0, 6, -14], + { standsAt: 'top', distanceM: 4 }, + false, + ], + [ + 'a house at the foot, its rear wall 1 m from the face', + [0, 0, -1], + { standsAt: 'foot', distanceM: 1 }, + false, + ], + ] as const) + test(`${name}: the face names the house, where it stands and how far${finding ? ', and it stands at the edge of a drop' : ''}`, () => { + const read = facts(cliffed(at as [number, number, number])) + expect(read.retaining[0]).toMatchObject({ kind: 'cliff', heightM: { min: 6, max: 6 } }) + expect(read.retaining[0]?.houses).toEqual([{ buildingId: 'building_house', ...stands }]) + expect(read.open.some((each) => each.code === 'house_at_drop_edge')).toBe(finding) + }) + + test('the face that holds the ground against a house backed into a slope is not a drop the house stands at', () => { + const read = facts( + runTool( + built((_x, z) => -z * 0.35, { doors: false }), + 'seat_house', + { strategy: 'hillside' }, + ).nodes, + ) + expect(read.retaining[0]?.houses).toEqual([]) + }) + + for (const [name, retainingHeight, unheld] of [ + ['with no retaining sides, the faces beside it stand unheld', undefined, true], + ['with retaining sides of 1.2 m, they are held', 1.2, false], + ] as const) + test(`a ramp cut into a 20 % slope, ${name}`, () => { + const lot = slopedLot({ ground: GROUNDS.steep, house: false }) + const { nodes } = runTool(lot, 'add_ramp', { + start: [10, 19], + segments: [{ type: 'line', end: [10, 4] }], + width: 3, + startHeight: -3.8, + endHeight: -1.8, + use: 'vehicle', + ...(retainingHeight ? { retainingHeight } : {}), + }) + const [ramp] = facts(nodes).ramps + expect(ramp?.sides.cutMaxM).toBeGreaterThan(0.8) + expect(ramp?.sides.cutMaxM).toBeLessThan(1.2) + expect((ramp?.sides.unheldLengthM as number) > 1).toBe(unheld) + expect(codes(nodes).some((code) => code.startsWith('ramp_side_unheld'))).toBe(unheld) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-facts.ts b/packages/core/src/agent-operations/terrain-facts.ts new file mode 100644 index 0000000000..e173e0727d --- /dev/null +++ b/packages/core/src/agent-operations/terrain-facts.ts @@ -0,0 +1,1437 @@ +import { stretchesAlongWall } from '../building/zone-wall-stretches' +import { automaticFloorHeight, floorPlateAtGroundContact } from '../lib/floor-foundation-datum' +import { floorSlabsOf, levelGradeStanding } from '../lib/grade-standing' +import { groundLevelOf } from '../lib/ground-level' +import { getOpeningFloorDatum } from '../lib/opening-floor-datum' +import { rampHeightAt, rampOffsetPoint, rampStations } from '../lib/ramp' +import { rampFacts } from '../lib/ramp-facts' +import { classifyEdges, outwardNormal, resolveFrontEdge } from '../lib/setback-envelope' +import { isSiteFlatwork } from '../lib/site-flatwork' +import { slabTerrainHeightAt } from '../lib/slab-terrain' +import { terrainBreakFacts, terrainBreaksOf } from '../lib/terrain-breaks' +import { heightAt, slopeAt, type TerrainField } from '../lib/terrain-field' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import { queryNodes } from '../runtime/node-queries' +import type { + AnyNode, + AnyNodeId, + BuildingNode, + DoorNode, + LevelNode, + RampNode, + SiteNode, + SlabNode, + StairNode, + WallNode, +} from '../schema' +import { MIN_SLAB_THICKNESS } from '../schema/nodes/slab' +import { + getLevelElevations, + getLevelFloorToFloorHeight, + levelPlaneWorldY, +} from '../services/storey' +import { pointInPolygon as inPolygon } from '../systems/slab/slab-support' +import { stairBaseElevation } from '../systems/stair/stair-base-elevation' +import { resolveStairWalkingSurfaces } from '../systems/stair/stair-clearance' +import { getWallCurveFrameAt, getWallCurveLength } from '../systems/wall/wall-curve' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import { pointInPolygon as onOrInPolygon } from './plan-geometry' +import type { SceneNodes } from './types' + +/** + * What stands on the ground, against the ground: one measure for the model (read_terrain_facts) and + * for a harness that states it. Every height is metres above the scene datum and every point is in + * the site frame; the ground is the persisted terrain, or the flat datum where nobody shaped any. + * + * The facts are measured; `open` lists the ones past a stated limit, each with its number. The + * limits are design context, said in the answer, not a code check. + */ + +type Pt = [number, number] +type Range = { min: number; max: number } + +export const TERRAIN_FACT_LIMITS = { + /** Ground this far over a floor's top, a sill or a paved surface counts as over it. */ + groundOverM: 0.02, + /** A floor edge this far over the ground stands in the air (the unguarded-drop threshold). */ + floorInAirM: 0.5, + /** A floor that follows the ground this far over its level's base has taken that much of the storey. */ + floorLiftM: 0.15, + /** A door's sill this far over what is outside it is more than one riser. */ + doorStepM: 0.2, + /** How far from a wall the ground's fall is measured, and from how close to its face. */ + fallReachM: 3, + fallFromM: 0.3, + /** Ground rising more than this going away from a wall runs to it, unless it first falls this much from the wall's foot. */ + fallTowardPercent: 1, + fallAtWallPercent: 2, + /** The stretch from the wall's foot that fall is read over. */ + fallAtWallM: 0.5, + /** A stretch of wall this long with the ground running to it is stated. */ + fallTowardLengthM: 1, + /** + * Water runs to a wall where the ground climbs from its foot, without first falling, over at + * least this reach and by at least this much; a face the ground steps up at is not a climb. + */ + runsToWallReachM: 1, + runsToWallRiseM: 0.03, + /** Ground this far over a floor, against a wall, is earth the wall holds. */ + earthAgainstM: 0.3, + /** A paved surface this far off the ground is off it. */ + surfaceOffGroundM: 0.15, + drivePercent: 18, + walkPercent: 12.5, + /** The end of a flight or a ramp this far from the ground or the sill misses it. */ + meetM: 0.05, + /** A house this close to the top of a face this high stands at the edge of a drop. */ + dropEdgeM: 2, + dropHeightM: 1, + /** Ground steeper than this with no wall or face holding it is a bank to hold. */ + bankDeg: 45, + bankAreaM2: 1, +} as const + +export type TerrainFinding = { + code: + | 'ground_over_floor' + | 'floor_in_air' + | 'floor_lifted_by_ground' + | 'floor_without_thickness' + | 'door_above_ground' + | 'door_below_ground' + | 'ground_falls_to_wall' + | 'window_below_ground' + | 'room_light_behind_earth' + | 'surface_off_ground' + | 'surface_under_ground' + | 'surface_steep' + | 'steps_off_ground' + | 'steps_miss_door' + | 'ramp_end_off_ground' + | 'ramp_steep' + | 'ramp_side_unheld' + | 'house_at_drop_edge' + | 'steep_bank' + /** The node the fact is about. */ + id: string + /** The number past its limit: metres, percent or degrees, as the message says. */ + value: number + message: string +} + +export type WallGroundFacts = { + wallId: string + /** The side of the lot the wall's outside faces, the street being the front; absent with no street edge. */ + side?: 'front' | 'rear' | 'left' | 'right' + /** Unit vector from the wall to its outside. */ + outward: Pt + lengthM: number + /** The ground along the wall's outside foot. */ + groundM: Range + /** The floor the wall stands on, over that ground: negative where the ground stands over the floor. */ + floorOverGroundM: Range + /** How the ground falls going away from the wall, percent over `fallReachM`: negative rises. */ + fallAwayPercent: Range + /** The same over the first half metre from the wall's foot: a fall here carries water off the wall even under a bank. */ + fallAtWallPercent: Range + /** Length of the wall where the ground climbs from its foot without first falling: water runs to the wall. */ + fallsTowardLengthM: number + /** How far under the wall's foot the lowest ground within 2.5 m of it lies: 0 where the ground only rises. */ + lowLineUnderFootM: Range + /** Earth against the wall: the ground at its outside face over the floor inside (0 where it is lower). */ + earthAgainstM: { max: number; mean: number } + /** Length of the wall with more than `earthAgainstM` of earth against it, and that earth's share of the storey height. */ + earthLengthM: number + buriedShare: number + /** A face the ground steps up at before the wall (a retaining face across an areaway): how far, how high. */ + faceBefore?: { distanceM: number; heightM: number } + /** Windows in the wall: the sill of each against the ground outside it. */ + windows: { windowId: string; sillM: number; outsideM: number; underGroundM: number }[] +} + +export type DoorGroundFacts = { + doorId: string + wallId: string + levelId: string + at: Pt + sillM: number + /** What is outside the door: the ground, or a slab laid there (a porch, a patio). */ + outside: 'ground' | 'slab' + outsideId?: string + outsideM: number + /** Sill minus outside: positive is a step down to it, negative is ground or paving over the sill. */ + stepM: number + /** Steps or a ramp whose upper end stands at this door. */ + servedBy?: string +} + +export type HouseGroundFacts = { + buildingId: string + levelId: string + /** `at-grade`, `partly-below-grade` or `below-grade`, as the level's standing is read everywhere. */ + standing: string + /** The level's base: the plane its storey stands on, and its storey height from there. */ + levelBaseM: number + storeyHeightM: number + /** The top of the ground level's floor (its lowest and highest floor slab). */ + floorM: Range + /** + * What the storey keeps between its highest floor and its top. A floor that rests on the ground + * follows the ground at its walls; the storey's top stays on the level's base. + */ + clearHeightM: number + /** The floor rests on the ground and follows it (an automatic floor plate), or stands where it was drawn. */ + floorFollowsGround: boolean + /** How far the highest floor that follows the ground stands over the level's base; 0 with none. */ + followingFloorOverBaseM: number + /** The ground under the floor. */ + groundM: { lowest: number; highest: number; mean: number } + /** Floor top minus ground under it: negative where the ground stands over the floor. */ + floorOverGroundM: Range + /** Share of the floor with the ground over it, and with more than `floorInAirM` of air under it. */ + groundOverFloorShare: number + floorInAirShare: number + walls: WallGroundFacts[] + doors: DoorGroundFacts[] + /** Rooms of the ground level along a wall that holds earth: what light their openings keep. */ + roomsAgainstEarth: { + zoneId: string + name: string + /** Its length along outside walls, and along those that hold earth. */ + frontageM: number + earthFrontageM: number + /** Its windows and doors to the outside: with the ground under the sill, and with the ground over it. */ + openingsClear: number + openingsUnderGround: number + /** The room states artificial light and ventilation (its daylight declaration). */ + declared: boolean + }[] +} + +export type SurfaceGroundFacts = { + slabId: string + kind: string + mode: 'flat' | 'draped' + areaM2: number + /** Surface top minus the ground under it. */ + overGroundM: Range + /** + * The slope of the surface itself (0 for a flat one). A drive or a walk is read the way it is + * travelled: down its middle (the points farthest from its sides), along the side nearest each + * point, over 3 m; any other surface by the ground's steepest slope under it. + */ + slopePercent: { max: number; mean: number } + /** A drive or a walk: its fall across the way it is travelled. */ + crossFallPercent?: { max: number; mean: number } + /** The steepest the ground stands under any point of it (its edges on a batter included). */ + steepestGroundPercent: number +} + +export type StepsGroundFacts = { + stairId: string + foot: Pt + footM: number + groundAtFootM: number + /** Foot minus ground: positive stands in the air, negative is under the ground. */ + footOverGroundM: number + topM: number + /** The door whose sill the upper end stands at, and upper end minus that sill. */ + doorId?: string + topOverSillM?: number +} + +export type RampGroundFacts = { + rampId: string + lengthM: number + maximumSlopePercent: number + statedLimitPercent: number + /** Each end: its height, the ground just beyond it, and the difference. */ + ends: { at: Pt; heightM: number; groundBeyondM: number; overGroundM: number }[] + /** + * The ground beside the ramp against its surface: the highest it stands over it (a cut) and + * under it (a fill), the height of the ramp's own retaining sides, and the length of side + * where a face higher than those sides, and than 0.3 m, stands with nothing to hold it. + */ + sides: { cutMaxM: number; fillMaxM: number; retainingHeightM: number; unheldLengthM: number } +} + +export type TerrainFacts = { + hasTerrain: boolean + houses: HouseGroundFacts[] + surfaces: SurfaceGroundFacts[] + steps: StepsGroundFacts[] + ramps: RampGroundFacts[] + /** + * Faces that hold ground: terrain breaks, with the height they hold, and each house within 10 m + * of one: on its high side (`top`) or its low side (`foot`), and how far its walls stand from it. + */ + retaining: { + breakId: string + kind: string + lengthM: number + heightM: Range + houses: { buildingId: string; standsAt: 'top' | 'foot'; distanceM: number }[] + }[] + /** Ground steeper than `bankDeg` inside the lot that no face holds. */ + banks: { steepestDeg: number; areaM2: number } + /** + * Earth moved against the ground before any tile was written (the frozen base field, or the + * datum): a lot whose natural relief was itself written as tiles counts that relief here. + */ + earthwork?: { cutM3: number; fillM3: number; against: 'base_field' | 'datum' } + open: TerrainFinding[] + limits: typeof TERRAIN_FACT_LIMITS + section?: TerrainSection + note?: string +} + +export type TerrainSection = { + from: Pt + to: Pt + lengthM: number + /** The ground along the line at its breakpoints, `sM` metres from `from`. */ + ground: { sM: number; groundM: number }[] + /** The floors the line passes over: where, and their top. */ + floors: { slabId: string; fromM: number; toM: number; topM: number; overGroundM: Range }[] +} + +const round = (value: number, digits = 2) => { + const k = 10 ** digits + return Math.round(value * k) / k +} +/** The least and the greatest of a list, by a loop: a long list is not spread onto the stack. */ +const rangeOf = (values: number[]): Range => { + let min = Number.POSITIVE_INFINITY + let max = Number.NEGATIVE_INFINITY + for (const value of values) { + if (value < min) min = value + if (value > max) max = value + } + return { min: round(min), max: round(max) } +} + +type Frame = { + building: BuildingNode + toSite: (x: number, z: number) => Pt + toLocal: (x: number, z: number) => Pt + /** A building-local direction in the site frame. */ + turn: (x: number, z: number) => Pt +} + +function frameOf(building: BuildingNode): Frame | null { + if (Math.abs(building.rotation[0]) > 1e-9 || Math.abs(building.rotation[2]) > 1e-9) return null + const cos = Math.cos(building.rotation[1]) + const sin = Math.sin(building.rotation[1]) + const [px, , pz] = building.position + return { + building, + toSite: (x, z) => [cos * x + sin * z + px, -sin * x + cos * z + pz], + toLocal: (x, z) => [cos * (x - px) - sin * (z - pz), sin * (x - px) + cos * (z - pz)], + turn: (x, z) => [cos * x + sin * z, -sin * x + cos * z], + } +} + +type Ground = (x: number, z: number) => number + +/** A floor that rests on the ground and takes its height from it, not from what was drawn. */ +function followsGround(nodes: SceneNodes, slab: SlabNode): boolean { + return ( + slab.plateRole === 'base' && + slab.floorHeight === undefined && + slab.referenceFloorElevation === undefined && + floorPlateAtGroundContact(nodes as Record, slab) + ) +} + +/** + * The top of a floor slab over its level's base. A floor that follows the ground is read from the + * ground as it lies now: its stored elevation is only rewritten when the scene next settles. + */ +function floorTopOf(nodes: SceneNodes, slab: SlabNode): number { + return followsGround(nodes, slab) + ? automaticFloorHeight(nodes as Record, slab) + : slab.elevation +} + +/** Corners and a grid across a polygon, no finer than half a metre, capped so a big plate stays cheap. */ +function polygonSamples(polygon: Pt[], stepM = 0.5, cap = 40): Pt[] { + const samples: Pt[] = [...polygon] + const xs = polygon.map(([x]) => x) + const zs = polygon.map(([, z]) => z) + const minX = Math.min(...xs) + const maxX = Math.max(...xs) + const minZ = Math.min(...zs) + const maxZ = Math.max(...zs) + const stepX = Math.max(stepM, (maxX - minX) / cap) + const stepZ = Math.max(stepM, (maxZ - minZ) / cap) + for (let x = minX + stepX / 2; x < maxX; x += stepX) + for (let z = minZ + stepZ / 2; z < maxZ; z += stepZ) + if (inPolygon(x, z, polygon)) samples.push([x, z]) + return samples +} + +function shoelace(polygon: Pt[]): number { + let sum = 0 + for (let i = 0; i < polygon.length; i++) { + const [x, z] = polygon[i] as Pt + const [nx, nz] = polygon[(i + 1) % polygon.length] as Pt + sum += x * nz - nx * z + } + return Math.abs(sum / 2) +} + +/** The level a building stands on the ground by: the one it names or the stack gives, else its lowest floor. */ +function groundLevel(nodes: Record, building: BuildingNode): LevelNode | null { + const named = groundLevelOf(nodes, building.id)?.level + if (named && floorSlabsOf(nodes, named).length) return named + const elevations = getLevelElevations(nodes) + const levels = queryNodes(nodes, { type: 'level' }) + .filter( + (node) => + elevations.get(node.id)?.buildingId === building.id && floorSlabsOf(nodes, node).length > 0, + ) + .sort((a, b) => a.level - b.level) + return levels.find((level) => level.level >= 0) ?? levels[0] ?? null +} + +/** The side of the lot a direction faces: the role of the lot edge whose outward normal it follows best. */ +function lotSides(site: SiteNode): ((outward: Pt) => WallGroundFacts['side']) | null { + const points = site.polygon?.points as Pt[] | undefined + if (!points || points.length < 3) return null + if (site.frontEdge === undefined && !site.streetEdges?.length) return null + const roles = classifyEdges( + points, + resolveFrontEdge(points, site.frontEdge, site.northRotation), + site.streetEdges, + ) + const normals = points.map((_, index) => outwardNormal(points, index)) + return ([ox, oz]) => { + let best = 0 + let bestDot = Number.NEGATIVE_INFINITY + normals.forEach(([nx, nz], index) => { + const dot = ox * nx + oz * nz + if (dot > bestDot) { + bestDot = dot + best = index + } + }) + const role = roles[best] + return role === 'front' || role === 'rear' || role === 'left' || role === 'right' + ? role + : undefined + } +} + +/** + * The sill of a door or a window over the datum. Its height is counted from the floor it stands + * on; a floor that follows the ground is read as it lies now, like the floor itself. + */ +export function sillOf( + wall: WallNode, + opening: { position: [number, number, number]; height: number }, + inside: Pt, + floors: SlabNode[], + plane: number, + nodes: SceneNodes, +): number { + const floor = floors.find((slab) => inPolygon(inside[0], inside[1], slab.polygon)) + const datum = + floor && followsGround(nodes, floor) + ? automaticFloorHeight(nodes as Record, floor) + : getOpeningFloorDatum(wall, opening as DoorNode, nodes) + return plane + datum + opening.position[1] - opening.height / 2 +} + +/** Whether a point lies in a polygon or within `reach` of its edges. */ +function inOrNear(x: number, z: number, polygon: Pt[], reach: number): boolean { + if (inPolygon(x, z, polygon)) return true + for (let i = 0; i < polygon.length; i++) { + const [ax, az] = polygon[i] as Pt + const [bx, bz] = polygon[(i + 1) % polygon.length] as Pt + const dx = bx - ax + const dz = bz - az + const lengthSq = dx * dx + dz * dz + const t = lengthSq ? Math.max(0, Math.min(1, ((x - ax) * dx + (z - az) * dz) / lengthSq)) : 0 + if (Math.hypot(x - ax - dx * t, z - az - dz * t) <= reach) return true + } + return false +} + +type Exterior = { wall: WallNode; outward: 1 | -1 } + +/** The walls of a level with a floor on one side only, and which side is out. */ +function exteriorWalls(level: LevelNode, floors: SlabNode[], nodes: SceneNodes): Exterior[] { + const onFloor = ([x, z]: Pt) => floors.some((slab) => inPolygon(x, z, slab.polygon)) + const found: Exterior[] = [] + for (const id of level.children) { + const wall = nodes[id] + if (wall?.type !== 'wall') continue + const length = getWallCurveLength(wall) + if (length < 0.05) continue + const faces = getWallFaceOffsets(wall) + let a = 0 + let b = 0 + for (const t of [0.2, 0.5, 0.8]) { + const frame = getWallCurveFrameAt(wall, t) + const side = (offset: number): Pt => [ + frame.point.x + frame.normal.x * offset, + frame.point.y + frame.normal.y * offset, + ] + if (onFloor(side(faces.a + 0.15))) a++ + if (onFloor(side(faces.b - 0.15))) b++ + } + // Floor on the `b` side alone: the `a` side is out, along the normal. + if (b >= 2 && a === 0) found.push({ wall, outward: 1 }) + else if (a >= 2 && b === 0) found.push({ wall, outward: -1 }) + } + return found +} + +function wallFacts( + { wall, outward }: Exterior, + frame: Frame, + floorM: number, + ground: Ground, + nodes: SceneNodes, + sideOf: ReturnType, + floors: SlabNode[], + plane: number, + storeyHeightM: number, +): WallGroundFacts { + const L = TERRAIN_FACT_LIMITS + const length = getWallCurveLength(wall) + const faces = getWallFaceOffsets(wall) + const face = outward === 1 ? faces.a : faces.b + const floor = floorM + // A wall is read every half metre, a very long one at 400 places. + const count = Math.min(400, Math.max(2, Math.ceil(length / 0.5))) + const grounds: number[] = [] + const gaps: number[] = [] + const falls: number[] = [] + const fallsAtWall: number[] = [] + const lows: number[] = [] + let toward = 0 + let earthMax = 0 + let earthSum = 0 + let earthLength = 0 + let faceBefore: WallGroundFacts['faceBefore'] + let normal: Pt = [0, 0] + for (let i = 0; i <= count; i++) { + const curve = getWallCurveFrameAt(wall, i / count) + const out = (distance: number): Pt => + frame.toSite( + curve.point.x + curve.normal.x * (face + outward * distance), + curve.point.y + curve.normal.y * (face + outward * distance), + ) + const near = ground(...out(L.fallFromM)) + const far = ground(...out(L.fallFromM + L.fallReachM)) + const fall = ((near - far) / L.fallReachM) * 100 + const atWall = ((near - ground(...out(L.fallFromM + L.fallAtWallM))) / L.fallAtWallM) * 100 + grounds.push(near) + gaps.push(floor - near) + falls.push(fall) + fallsAtWall.push(atWall) + // The ground from the wall's foot outward, every 0.2 m to 3.1 m: how far it climbs without + // first falling (a step of more than 100 % is a face, not a climb), and its lowest within 2.5 m. + const foot = ground(...out(0.1)) + let before = foot + let reach = 0 + let climb = 0 + let climbing = true + let lowest = foot + for (let k = 1; k <= 15; k++) { + const distance = 0.1 + 0.2 * k + const here = ground(...out(distance)) + const step = here - before + if (climbing) { + if (step < -0.005) climbing = false + else { + reach = distance + if (step <= 0.2) climb += Math.max(0, step) + else if (!faceBefore || step > faceBefore.heightM) + faceBefore = { distanceM: round(distance - 0.1), heightM: round(step) } + } + } + if (distance <= 2.5) lowest = Math.min(lowest, here) + before = here + } + lows.push(foot - lowest) + if (reach >= L.runsToWallReachM && climb >= L.runsToWallRiseM) toward += length / (count + 1) + const earth = Math.max(0, foot - floor) + earthMax = Math.max(earthMax, earth) + earthSum += earth + if (earth > L.earthAgainstM) earthLength += length / (count + 1) + if (i === Math.floor(count / 2)) + normal = frame.turn(curve.normal.x * outward, curve.normal.y * outward) + } + const windows: WallGroundFacts['windows'] = [] + for (const childId of wall.children ?? []) { + const node = nodes[childId] + if (node?.type !== 'window' || !Array.isArray(node.position)) continue + const curve = getWallCurveFrameAt(wall, node.position[0] / length) + const beside = (offset: number): Pt => [ + curve.point.x + curve.normal.x * offset, + curve.point.y + curve.normal.y * offset, + ] + const inside = outward === 1 ? beside(faces.b - 0.15) : beside(faces.a + 0.15) + const sill = sillOf(wall, node as never, inside, floors, plane, nodes) + const outsideM = ground(...frame.toSite(...beside(face + outward * 0.15))) + windows.push({ + windowId: node.id, + sillM: round(sill), + outsideM: round(outsideM), + underGroundM: round(Math.max(0, outsideM - sill)), + }) + } + const side = sideOf?.(normal) + const earthMean = earthSum / (count + 1) + return { + wallId: wall.id, + ...(side ? { side } : {}), + outward: [round(normal[0]), round(normal[1])], + lengthM: round(length), + groundM: rangeOf(grounds), + floorOverGroundM: rangeOf(gaps), + fallAwayPercent: { min: round(Math.min(...falls), 1), max: round(Math.max(...falls), 1) }, + fallAtWallPercent: { + min: round(Math.min(...fallsAtWall), 1), + max: round(Math.max(...fallsAtWall), 1), + }, + fallsTowardLengthM: round(toward, 1), + lowLineUnderFootM: rangeOf(lows), + earthAgainstM: { max: round(earthMax), mean: round(earthMean) }, + earthLengthM: round(earthLength, 1), + buriedShare: round(Math.min(1, earthMean / storeyHeightM)), + ...(faceBefore ? { faceBefore } : {}), + windows, + } +} + +function doorFacts( + level: LevelNode, + floors: SlabNode[], + frame: Frame, + plane: number, + ground: Ground, + nodes: SceneNodes, +): DoorGroundFacts[] { + const onFloor = ([x, z]: Pt) => floors.some((slab) => inPolygon(x, z, slab.polygon)) + const others = level.children + .map((id) => nodes[id]) + .filter( + (node): node is SlabNode => + node?.type === 'slab' && + !node.recessed && + node.polygon.length >= 3 && + !floors.includes(node), + ) + const facts: DoorGroundFacts[] = [] + for (const id of level.children) { + const wall = nodes[id] + if (wall?.type !== 'wall') continue + const length = getWallCurveLength(wall) + if (length < 0.05) continue + const faces = getWallFaceOffsets(wall) + for (const childId of wall.children ?? []) { + const door = nodes[childId] + if (door?.type !== 'door' || !Array.isArray(door.position)) continue + const { position, height } = door as DoorNode + const curve = getWallCurveFrameAt(wall, position[0] / length) + const side = (offset: number): Pt => [ + curve.point.x + curve.normal.x * offset, + curve.point.y + curve.normal.y * offset, + ] + const a = onFloor(side(faces.a + 0.15)) + const b = onFloor(side(faces.b - 0.15)) + if (a === b) continue + const local = a ? side(faces.b - 0.6) : side(faces.a + 0.6) + const inside = a ? side(faces.a + 0.15) : side(faces.b - 0.15) + const sill = sillOf(wall, { position, height }, inside, floors, plane, nodes) + const at = frame.toSite(...local) + const landing = others + .filter((slab) => inPolygon(local[0], local[1], slab.polygon)) + .sort((p, q) => q.elevation - p.elevation)[0] + const outsideM = landing + ? plane + slabTerrainHeightAt(landing, nodes, local[0], local[1]) + : ground(...at) + facts.push({ + doorId: door.id, + wallId: wall.id, + levelId: level.id, + at: [round(at[0]), round(at[1])], + sillM: round(sill), + outside: landing ? 'slab' : 'ground', + ...(landing ? { outsideId: landing.id } : {}), + outsideM: round(outsideM), + stepM: round(sill - outsideM), + }) + } + } + return facts +} + +function houseFacts( + building: BuildingNode, + site: SiteNode, + ground: Ground, + nodes: SceneNodes, +): HouseGroundFacts | null { + const record = nodes as Record + const frame = frameOf(building) + const level = groundLevel(record, building) + if (!frame || !level) return null + const plane = levelPlaneWorldY(record, level.id) + if (plane === null) return null + const floors = floorSlabsOf(record, level) + const tops = floors.map((slab) => plane + floorTopOf(nodes, slab)) + const storeyHeight = getLevelFloorToFloorHeight(level.id, record) + const following = floors.flatMap((slab, index) => + followsGround(nodes, slab) ? [tops[index] as number] : [], + ) + // A lower level under the floor: the floor over it is not in the air, it is a storey. + const elevationsOf = getLevelElevations(record) + const below = queryNodes(nodes, { type: 'level' }) + .filter( + (each) => elevationsOf.get(each.id)?.buildingId === building.id && each.level < level.level, + ) + .flatMap((each) => floorSlabsOf(record, each)) + const gaps: number[] = [] + const grounds: number[] = [] + let over = 0 + let air = 0 + floors.forEach((slab, index) => { + const top = tops[index] as number + for (const [x, z] of polygonSamples(slab.polygon)) { + const height = ground(...frame.toSite(x, z)) + grounds.push(height) + gaps.push(top - height) + if (height - top > TERRAIN_FACT_LIMITS.groundOverM) over++ + if ( + top - height > TERRAIN_FACT_LIMITS.floorInAirM && + // Over a level under it, to the thickness of a wall, the floor is a storey, not in the air. + !below.some((lower) => inOrNear(x, z, lower.polygon, 0.35)) + ) + air++ + } + }) + const sideOf = lotSides(site) + // Doors of the ground level and of the levels under it: a basement that walks out has a door too. + const elevations = getLevelElevations(record) + const doors = queryNodes(nodes, { type: 'level' }) + .filter( + (node) => elevations.get(node.id)?.buildingId === building.id && node.level <= level.level, + ) + .flatMap((each) => { + const eachPlane = levelPlaneWorldY(record, each.id) + return eachPlane === null + ? [] + : doorFacts(each, floorSlabsOf(record, each), frame, eachPlane, ground, nodes) + }) + const walls = exteriorWalls(level, floors, nodes).map((exterior) => + wallFacts( + exterior, + frame, + Math.max(...tops), + ground, + nodes, + sideOf, + floors, + plane, + storeyHeight, + ), + ) + return { + buildingId: building.id, + levelId: level.id, + standing: levelGradeStanding(record, level.id), + levelBaseM: round(plane), + storeyHeightM: round(storeyHeight), + floorM: rangeOf(tops), + clearHeightM: round(plane + storeyHeight - Math.max(...tops)), + floorFollowsGround: following.length > 0, + followingFloorOverBaseM: round(Math.max(0, ...following.map((top) => top - plane))), + groundM: { + lowest: rangeOf(grounds).min, + highest: rangeOf(grounds).max, + mean: round(grounds.reduce((sum, value) => sum + value, 0) / grounds.length), + }, + floorOverGroundM: rangeOf(gaps), + groundOverFloorShare: round(over / gaps.length), + floorInAirShare: round(air / gaps.length), + walls, + doors, + roomsAgainstEarth: roomsAgainstEarth(level, walls, doors, nodes), + } +} + +/** The rooms of a level that lie along a wall holding earth, with what their openings keep clear. */ +function roomsAgainstEarth( + level: LevelNode, + walls: WallGroundFacts[], + doors: DoorGroundFacts[], + nodes: SceneNodes, +): HouseGroundFacts['roomsAgainstEarth'] { + const L = TERRAIN_FACT_LIMITS + const rooms: HouseGroundFacts['roomsAgainstEarth'] = [] + for (const id of level.children) { + const zone = nodes[id] + if (zone?.type !== 'zone' || zone.spaceRole !== 'room' || zone.polygon.length < 3) continue + let frontage = 0 + let earthFrontage = 0 + let clear = 0 + let under = 0 + for (const facts of walls) { + const wall = nodes[facts.wallId] + if (wall?.type !== 'wall') continue + const stretches = stretchesAlongWall(zone, wall) + const along = stretches.reduce((sum, [from, to]) => sum + to - from, 0) + if (along <= 0.05) continue + frontage += along + if (facts.earthAgainstM.max > L.earthAgainstM) + earthFrontage += Math.min(along, facts.earthLengthM) + const within = (openingId: string) => { + const opening = nodes[openingId] + const at = (opening as { position?: number[] } | undefined)?.position?.[0] + return at !== undefined && stretches.some(([from, to]) => at >= from && at <= to) + } + for (const window of facts.windows) + if (within(window.windowId)) window.underGroundM > L.groundOverM ? under++ : clear++ + for (const door of doors) + if (door.wallId === facts.wallId && within(door.doorId)) + door.stepM < -L.groundOverM ? under++ : clear++ + } + if (earthFrontage > 0.05) + rooms.push({ + zoneId: zone.id, + name: zone.name ?? zone.id, + frontageM: round(frontage, 1), + earthFrontageM: round(earthFrontage, 1), + openingsClear: clear, + openingsUnderGround: under, + declared: (zone.metadata as { daylight?: unknown } | undefined)?.daylight !== undefined, + }) + } + return rooms +} + +function surfaceFacts( + slab: SlabNode, + field: TerrainField | null, + ground: Ground, + nodes: SceneNodes, +): SurfaceGroundFacts | null { + const record = nodes as Record + const level = slab.parentId ? nodes[slab.parentId] : undefined + const building = level?.parentId ? nodes[level.parentId] : undefined + if (level?.type !== 'level' || building?.type !== 'building') return null + const frame = frameOf(building) + const plane = levelPlaneWorldY(record, level.id) + if (!frame || plane === null || slab.polygon.length < 3) return null + const gaps: number[] = [] + const slopes: number[] = [] + const along: number[] = [] + const across: number[] = [] + const draped = slab.terrainMode === 'draped' + const flatwork = (slab.metadata as { flatwork?: unknown } | undefined)?.flatwork + const kind = typeof flatwork === 'string' ? flatwork : 'surface' + const travelled = draped && (kind === 'driveway' || kind === 'walk') + const top = (x: number, z: number) => plane + slabTerrainHeightAt(slab, nodes, x, z) + /** The nearest side of the outline to a point: how far, and which way it runs. */ + const nearestSide = (x: number, z: number): { distance: number; way: Pt } => { + let distance = Number.POSITIVE_INFINITY + let way: Pt = [1, 0] + for (let i = 0; i < slab.polygon.length; i++) { + const [ax, az] = slab.polygon[i] as Pt + const [bx, bz] = slab.polygon[(i + 1) % slab.polygon.length] as Pt + const dx = bx - ax + const dz = bz - az + const lengthSq = dx * dx + dz * dz + if (lengthSq < 1e-9) continue + const t = Math.max(0, Math.min(1, ((x - ax) * dx + (z - az) * dz) / lengthSq)) + const d = Math.hypot(x - ax - dx * t, z - az - dz * t) + if (d < distance) { + distance = d + const length = Math.sqrt(lengthSq) + way = [dx / length, dz / length] + } + } + return { distance, way } + } + const samples = polygonSamples(slab.polygon) + const sides = travelled ? samples.map(([x, z]) => nearestSide(x, z)) : [] + // The middle of the way: the points farthest from its sides, where a wheel or a foot goes and + // the lattice does not mix in the batter beside it. + const middle = Math.max(0.3, 0.75 * Math.max(0, ...sides.map((side) => side.distance))) + const on = (px: number, pz: number) => inPolygon(px, pz, slab.polygon) + samples.forEach(([x, z], index) => { + const at = frame.toSite(x, z) + gaps.push(top(x, z) - ground(...at)) + slopes.push(draped && field ? Math.tan(slopeAt(field, at[0], at[1])) * 100 : 0) + const side = sides[index] + if (!side || side.distance < middle) return + const { way } = side + const reach = 1.5 + const ends: [Pt, Pt] = [ + [x - way[0] * reach, z - way[1] * reach], + [x + way[0] * reach, z + way[1] * reach], + ] + if (on(...ends[0]) && on(...ends[1])) + along.push((Math.abs(top(...ends[1]) - top(...ends[0])) / (2 * reach)) * 100) + const beside: [Pt, Pt] = [ + [x + way[1] * 0.4, z - way[0] * 0.4], + [x - way[1] * 0.4, z + way[0] * 0.4], + ] + if (on(...beside[0]) && on(...beside[1])) + across.push((Math.abs(top(...beside[1]) - top(...beside[0])) / 0.8) * 100) + }) + const stat = (values: number[]) => ({ + max: round(Math.max(...values), 1), + mean: round(values.reduce((sum, value) => sum + value, 0) / values.length, 1), + }) + return { + slabId: slab.id, + kind, + mode: draped ? 'draped' : 'flat', + areaM2: round(shoelace(slab.polygon), 1), + overGroundM: rangeOf(gaps), + slopePercent: stat(along.length ? along : slopes), + ...(along.length && across.length ? { crossFallPercent: stat(across) } : {}), + steepestGroundPercent: round(Math.max(...slopes), 1), + } +} + +/** Outside flights: a stair that climbs to no storey. */ +function stepsFacts( + stair: StairNode, + ground: Ground, + nodes: SceneNodes, + doors: DoorGroundFacts[], +): StepsGroundFacts | null { + const record = nodes as Record + const level = stair.parentId ? nodes[stair.parentId] : undefined + const building = level?.parentId ? nodes[level.parentId] : undefined + if (level?.type !== 'level' || building?.type !== 'building') return null + const frame = frameOf(building) + const plane = levelPlaneWorldY(record, level.id) + if (!frame || plane === null) return null + const base = stairBaseElevation(stair, nodes as Record, level.id) + const foot = frame.toSite(stair.position[0], stair.position[2]) + const footM = plane + base + const rise = stair.totalRise ?? 0 + let upper: Pt | null = null + try { + const surfaces = resolveStairWalkingSurfaces(stair, nodes as Record) + const top = surfaces.reduce<(typeof surfaces)[number] | null>( + (best, surface) => (!best || surface.top > best.top ? surface : best), + null, + ) + if (top) upper = frame.toSite(top.walkingLine[1][0], top.walkingLine[1][2]) + } catch { + upper = null + } + const groundAtFoot = ground(...foot) + const near = upper + ? doors + .map((door) => ({ door, gap: Math.hypot(door.at[0] - upper[0], door.at[1] - upper[1]) })) + .filter(({ gap }) => gap <= 1.2) + .sort((p, q) => p.gap - q.gap)[0]?.door + : undefined + return { + stairId: stair.id, + foot: [round(foot[0]), round(foot[1])], + footM: round(footM), + groundAtFootM: round(groundAtFoot), + footOverGroundM: round(footM - groundAtFoot), + topM: round(footM + rise), + ...(near ? { doorId: near.doorId, topOverSillM: round(footM + rise - near.sillM) } : {}), + } +} + +function rampGroundFacts(ramp: RampNode, ground: Ground, nodes: SceneNodes): RampGroundFacts { + const facts = rampFacts(ramp, nodes) + const stations = rampStations(ramp) + const first = stations[0] + const last = stations[stations.length - 1] + // A cell diagonal beyond the end clears the ground the ramp itself graded. + const beyond = 0.5 * Math.SQRT2 + 0.03 + const ends = ( + [ + [first, -1, facts.endpoints.start.heightM], + [last, 1, facts.endpoints.end.heightM], + ] as const + ).flatMap(([station, sign, heightM]) => { + if (!station) return [] + const at: Pt = [ + station.point[0] + station.tangent[0] * sign * beyond, + station.point[1] + station.tangent[1] * sign * beyond, + ] + const groundBeyondM = ground(...at) + return [ + { + at: [round(station.point[0]), round(station.point[1])] as Pt, + heightM: round(heightM), + groundBeyondM: round(groundBeyondM), + overGroundM: round(heightM - groundBeyondM), + }, + ] + }) + // The ground 0.15 m beyond each side, at every station: a cut-fill ramp keeps the ground that + // was there beside its corridor, so a face stands at its edge wherever the two differ. + let cutMaxM = 0 + let fillMaxM = 0 + let unheldLengthM = 0 + const held = Math.max(ramp.retainingHeight ?? 0, 0.3) + for (let i = 0; i < stations.length; i++) { + const station = stations[i] as (typeof stations)[number] + const next = stations[i + 1] ?? station + const before = stations[i - 1] ?? station + const span = (next.distance - before.distance) / 2 + const surface = rampHeightAt(ramp, station.distance) + for (const side of [1, -1]) { + const beside = rampOffsetPoint(station, side * (ramp.width / 2 + 0.15)) + const over = ground(beside[0], beside[1]) - surface + cutMaxM = Math.max(cutMaxM, over) + fillMaxM = Math.max(fillMaxM, -over) + if (Math.abs(over) > held) unheldLengthM += span + } + } + return { + rampId: ramp.id, + lengthM: round(facts.lengthM), + maximumSlopePercent: round(facts.maximumSlopePercent, 1), + statedLimitPercent: facts.maxSlopePercent, + ends, + sides: { + cutMaxM: round(cutMaxM), + fillMaxM: round(fillMaxM), + retainingHeightM: ramp.retainingHeight ?? 0, + unheldLengthM: round(unheldLengthM, 1), + }, + } +} + +/** Lot samples at half a metre, coarser on a large lot. */ +function lotSamples(site: SiteNode): { points: Pt[]; cellM2: number } { + const polygon = (site.polygon?.points ?? []) as Pt[] + if (polygon.length < 3) return { points: [], cellM2: 0 } + const xs = polygon.map(([x]) => x) + const zs = polygon.map(([, z]) => z) + const [minX, maxX] = [Math.min(...xs), Math.max(...xs)] + const [minZ, maxZ] = [Math.min(...zs), Math.max(...zs)] + const width = maxX - minX + const depth = maxZ - minZ + const step = Math.max(0.5, Math.sqrt((width * depth) / 40_000)) + const points: Pt[] = [] + for (let x = minX + step / 2; x < maxX; x += step) + for (let z = minZ + step / 2; z < maxZ; z += step) + if (inPolygon(x, z, polygon)) points.push([x, z]) + return { points, cellM2: step * step } +} + +function sectionOf( + from: Pt, + to: Pt, + ground: Ground, + nodes: SceneNodes, + houses: { frame: Frame; plane: number; floors: SlabNode[] }[], +): TerrainSection { + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + const count = Math.max(1, Math.min(2000, Math.ceil(length / 0.25))) + const at = (i: number): Pt => [ + from[0] + ((to[0] - from[0]) * i) / count, + from[1] + ((to[1] - from[1]) * i) / count, + ] + const heights = Array.from({ length: count + 1 }, (_, i) => ground(...at(i))) + // Keep the breakpoints: a station whose height the line through its kept neighbours misses by 2 cm. + const keep = new Set([0, count]) + const simplify = (a: number, b: number) => { + let worst = 0 + let index = -1 + for (let i = a + 1; i < b; i++) { + const line = + (heights[a] as number) + + (((heights[b] as number) - (heights[a] as number)) * (i - a)) / (b - a) + const miss = Math.abs((heights[i] as number) - line) + if (miss > worst) { + worst = miss + index = i + } + } + if (index >= 0 && worst > 0.02) { + keep.add(index) + simplify(a, index) + simplify(index, b) + } + } + simplify(0, count) + const floors: TerrainSection['floors'] = [] + for (const { frame, plane, floors: slabs } of houses) + for (const slab of slabs) { + let start = -1 + const gaps: number[] = [] + const close = (end: number) => { + if (start < 0) return + floors.push({ + slabId: slab.id, + fromM: round((length * start) / count), + toM: round((length * end) / count), + topM: round(plane + floorTopOf(nodes, slab)), + overGroundM: rangeOf(gaps), + }) + start = -1 + gaps.length = 0 + } + for (let i = 0; i <= count; i++) { + const [x, z] = frame.toLocal(...at(i)) + if (onOrInPolygon([x, z], slab.polygon)) { + if (start < 0) start = i + gaps.push(plane + floorTopOf(nodes, slab) - (heights[i] as number)) + } else close(i - 1) + } + close(count) + } + return { + from, + to, + lengthM: round(length), + ground: [...keep] + .sort((a, b) => a - b) + .map((i) => ({ sM: round((length * i) / count), groundM: round(heights[i] as number) })), + floors, + } +} + +/** + * A house against a face: the least distance from the corners and mid-sides of its ground floor + * to the face's line, and whether the ground the house stands on is the higher or the lower of + * the two beside the face there. `null` beyond 10 m, and for a face the house's own floor covers + * (the face that holds the ground against a house backed into a slope). + */ +function houseAtFace( + building: BuildingNode, + line: Pt[], + ground: Ground, + nodes: SceneNodes, +): { standsAt: 'top' | 'foot'; distanceM: number } | null { + const record = nodes as Record + const frame = frameOf(building) + const level = groundLevel(record, building) + if (!frame || !level) return null + let best: { distance: number; from: Pt; to: Pt } | null = null + for (const slab of floorSlabsOf(record, level)) { + const points = slab.polygon.flatMap((corner, i) => { + const next = slab.polygon[(i + 1) % slab.polygon.length] as Pt + return [corner as Pt, [(corner[0] + next[0]) / 2, (corner[1] + next[1]) / 2] as Pt] + }) + for (const local of points) { + const from = frame.toSite(local[0], local[1]) + for (let i = 0; i + 1 < line.length; i++) { + const [ax, az] = line[i] as Pt + const [bx, bz] = line[i + 1] as Pt + const dx = bx - ax + const dz = bz - az + const lengthSq = dx * dx + dz * dz + const t = lengthSq + ? Math.max(0, Math.min(1, ((from[0] - ax) * dx + (from[1] - az) * dz) / lengthSq)) + : 0 + const to: Pt = [ax + dx * t, az + dz * t] + const distance = Math.hypot(from[0] - to[0], from[1] - to[1]) + if (!best || distance < best.distance) best = { distance, from, to } + } + } + } + if (!best || best.distance > 10 || best.distance < 0.25) return null + // The ground 0.3 m each side of the face, along the way from the house to it. + const way: Pt = [ + (best.to[0] - best.from[0]) / best.distance, + (best.to[1] - best.from[1]) / best.distance, + ] + const near = ground(best.to[0] - way[0] * 0.3, best.to[1] - way[1] * 0.3) + const far = ground(best.to[0] + way[0] * 0.3, best.to[1] + way[1] * 0.3) + if (Math.abs(near - far) < 0.3) return null + return { standsAt: near > far ? 'top' : 'foot', distanceM: round(best.distance) } +} + +const FLAT_NOTE = + 'No relief is shaped on this site: the ground is the flat datum plane at y = 0, and every fact here is measured against it.' + +export type TerrainFactsOptions = { section?: { from: Pt; to: Pt } } + +/** `null` for a scene with no single site: there is no ground to measure against. */ +export function terrainFacts( + nodes: SceneNodes, + options: TerrainFactsOptions = {}, +): TerrainFacts | null { + const sites = queryNodes(nodes, { type: 'site' }) + const site = sites[0] + if (sites.length !== 1 || !site) return null + const field = persistedTerrainFieldOf(site, nodes) + const ground: Ground = (x, z) => (field ? heightAt(field, x, z) : 0) + const L = TERRAIN_FACT_LIMITS + const record = nodes as Record + + const buildings = queryNodes(nodes, { type: 'building' }) + const houses = buildings.flatMap((building) => { + const facts = houseFacts(building, site, ground, nodes) + return facts ? [facts] : [] + }) + const doors = houses.flatMap((house) => house.doors) + const surfaces = queryNodes(nodes, { type: 'slab' }).flatMap((node) => { + if (!isSiteFlatwork(node)) return [] + const facts = surfaceFacts(node, field, ground, nodes) + return facts ? [facts] : [] + }) + const steps = queryNodes(nodes, { type: 'stair' }).flatMap((node) => { + if (node.toLevelId) return [] + const facts = stepsFacts(node, ground, nodes, doors) + return facts ? [facts] : [] + }) + for (const flight of steps) { + const door = doors.find((each) => each.doorId === flight.doorId) + if (door && !door.servedBy) door.servedBy = flight.stairId + } + const ramps = queryNodes(nodes, { type: 'ramp' }).map((node) => + rampGroundFacts(node, ground, nodes), + ) + const retaining = field + ? terrainBreaksOf(site, nodes).map((boundary) => { + const facts = terrainBreakFacts(boundary, field) + return { + breakId: boundary.id, + kind: boundary.kind, + lengthM: round(facts.lengthM), + heightM: { min: round(facts.dropMinM), max: round(facts.dropMaxM) }, + houses: buildings.flatMap((building) => { + const stands = houseAtFace(building, boundary.line as Pt[], ground, nodes) + return stands ? [{ buildingId: building.id, ...stands }] : [] + }), + } + }) + : [] + + // The lot: banks no face holds, and the earth moved against the base ground. + const lot = lotSamples(site) + let steepestDeg = 0 + let bankM2 = 0 + let cutM3 = 0 + let fillM3 = 0 + const tiles = queryNodes(nodes, { type: 'terrain-tile', parentId: site.id }).length > 0 + const base = + tiles && site.terrain + ? persistedTerrainFieldOf({ terrain: site.terrain, polygon: site.polygon }) + : null + if (field) + for (const [x, z] of lot.points) { + const deg = (slopeAt(field, x, z) * 180) / Math.PI + steepestDeg = Math.max(steepestDeg, deg) + if (deg > L.bankDeg) bankM2 += lot.cellM2 + if (tiles) { + const moved = heightAt(field, x, z) - (base ? heightAt(base, x, z) : 0) + if (moved < 0) cutM3 += -moved * lot.cellM2 + else fillM3 += moved * lot.cellM2 + } + } + + const open: TerrainFinding[] = [] + const say = (code: TerrainFinding['code'], id: string, value: number, message: string) => + open.push({ code, id, value: round(value), message }) + for (const house of houses) { + if (house.floorOverGroundM.min < -L.groundOverM) + say( + 'ground_over_floor', + house.levelId, + -house.floorOverGroundM.min, + `The ground stands up to ${(-house.floorOverGroundM.min).toFixed(2)} m over the floor of ${house.levelId} (floor ${house.floorM.min.toFixed(2)} m, ground up to ${house.groundM.highest.toFixed(2)} m), over ${Math.round(house.groundOverFloorShare * 100)} % of it.`, + ) + if (house.followingFloorOverBaseM > L.floorLiftM) + say( + 'floor_lifted_by_ground', + house.levelId, + house.followingFloorOverBaseM, + `The floor of ${house.levelId} rests on the ground and the ground at its walls stands up to ${(house.followingFloorOverBaseM - 0.05).toFixed(2)} m over the level's base (${house.levelBaseM.toFixed(2)} m): the floor follows it to ${(house.levelBaseM + house.followingFloorOverBaseM).toFixed(2)} m, the storey's top does not, and the storey keeps ${house.clearHeightM.toFixed(2)} m of its ${house.storeyHeightM.toFixed(2)} m.`, + ) + if (house.floorOverGroundM.max > L.floorInAirM && house.floorInAirShare > 0) + say( + 'floor_in_air', + house.levelId, + house.floorOverGroundM.max, + `The floor of ${house.levelId} stands up to ${house.floorOverGroundM.max.toFixed(2)} m over the ground under it (floor ${house.floorM.max.toFixed(2)} m, ground down to ${house.groundM.lowest.toFixed(2)} m), over ${Math.round(house.floorInAirShare * 100)} % of it.`, + ) + for (const wall of house.walls) + if (wall.fallsTowardLengthM >= L.fallTowardLengthM) + say( + 'ground_falls_to_wall', + wall.wallId, + wall.fallAwayPercent.min, + `The ground climbs from the foot of ${wall.wallId}${wall.side ? ` (${wall.side})` : ''} along ${wall.fallsTowardLengthM.toFixed(1)} m of it, by up to ${(-wall.fallAwayPercent.min).toFixed(1)} % over ${L.fallReachM} m, with no lower line between the wall and that rise: water runs to the wall.`, + ) + for (const wall of house.walls) + for (const window of wall.windows) + if (window.underGroundM > L.groundOverM) + say( + 'window_below_ground', + window.windowId, + window.underGroundM, + `The ground outside ${window.windowId} stands ${window.underGroundM.toFixed(2)} m over its sill (sill ${window.sillM.toFixed(2)} m, ground ${window.outsideM.toFixed(2)} m).`, + ) + for (const room of house.roomsAgainstEarth) + if (room.openingsUnderGround > 0 && room.openingsClear === 0 && !room.declared) + say( + 'room_light_behind_earth', + room.zoneId, + room.earthFrontageM, + `${room.name} (${room.zoneId}) lies along ${room.earthFrontageM.toFixed(1)} m of wall that holds earth, and each of its ${room.openingsUnderGround} openings to the outside has the ground over its sill: it takes no daylight, and states no artificial light and ventilation.`, + ) + for (const door of house.doors) { + if (door.stepM < -L.groundOverM) + say( + 'door_below_ground', + door.doorId, + -door.stepM, + `The ${door.outside} outside ${door.doorId} stands ${(-door.stepM).toFixed(2)} m over its sill (sill ${door.sillM.toFixed(2)} m, outside ${door.outsideM.toFixed(2)} m).`, + ) + else if (door.stepM > L.doorStepM && !door.servedBy) + say( + 'door_above_ground', + door.doorId, + door.stepM, + `${door.doorId} opens ${door.stepM.toFixed(2)} m over the ${door.outside} outside it (sill ${door.sillM.toFixed(2)} m, outside ${door.outsideM.toFixed(2)} m), with no steps or ramp to it.`, + ) + } + } + // A floor stored thinner than a slab can be: its underside stands at or over its top. + for (const slab of queryNodes(nodes, { type: 'slab' })) + if (!isSiteFlatwork(slab) && !slab.recessed && slab.thickness < MIN_SLAB_THICKNESS) + say( + 'floor_without_thickness', + slab.id, + slab.thickness, + `The floor ${slab.id} is stored ${slab.thickness.toFixed(2)} m thick (top ${slab.elevation.toFixed(2)} m over its level's base, underside ${(slab.elevation - slab.thickness).toFixed(2)} m): a floor is at least ${MIN_SLAB_THICKNESS} m thick.`, + ) + for (const surface of surfaces) { + if (surface.overGroundM.max > L.surfaceOffGroundM) + say( + 'surface_off_ground', + surface.slabId, + surface.overGroundM.max, + `The ${surface.kind} ${surface.slabId} (${surface.mode}) stands up to ${surface.overGroundM.max.toFixed(2)} m over the ground under it.`, + ) + if (surface.overGroundM.min < -L.groundOverM - 0.03) + say( + 'surface_under_ground', + surface.slabId, + -surface.overGroundM.min, + `The ground stands up to ${(-surface.overGroundM.min).toFixed(2)} m over the ${surface.kind} ${surface.slabId} (${surface.mode}).`, + ) + const limit = + surface.kind === 'driveway' ? L.drivePercent : surface.kind === 'walk' ? L.walkPercent : null + if (limit !== null && surface.slopePercent.max > limit) + say( + 'surface_steep', + surface.slabId, + surface.slopePercent.max, + `The ${surface.kind} ${surface.slabId} slopes up to ${surface.slopePercent.max.toFixed(1)} % (mean ${surface.slopePercent.mean.toFixed(1)} %), over the ${limit} % stated here for a ${surface.kind}.`, + ) + } + for (const flight of steps) { + if (Math.abs(flight.footOverGroundM) > L.meetM) + say( + 'steps_off_ground', + flight.stairId, + flight.footOverGroundM, + `The foot of ${flight.stairId} stands ${Math.abs(flight.footOverGroundM).toFixed(2)} m ${flight.footOverGroundM > 0 ? 'over' : 'under'} the ground (foot ${flight.footM.toFixed(2)} m, ground ${flight.groundAtFootM.toFixed(2)} m).`, + ) + if (flight.topOverSillM !== undefined && Math.abs(flight.topOverSillM) > L.meetM) + say( + 'steps_miss_door', + flight.stairId, + flight.topOverSillM, + `The top of ${flight.stairId} stands ${Math.abs(flight.topOverSillM).toFixed(2)} m ${flight.topOverSillM > 0 ? 'over' : 'under'} the sill of ${flight.doorId} (top ${flight.topM.toFixed(2)} m).`, + ) + } + for (const ramp of ramps) { + for (const end of ramp.ends) + if (Math.abs(end.overGroundM) > L.meetM) + say( + 'ramp_end_off_ground', + ramp.rampId, + end.overGroundM, + `The end of ${ramp.rampId} at [${end.at[0]}, ${end.at[1]}] stands ${Math.abs(end.overGroundM).toFixed(2)} m ${end.overGroundM > 0 ? 'over' : 'under'} the ground beyond it (end ${end.heightM.toFixed(2)} m, ground ${end.groundBeyondM.toFixed(2)} m).`, + ) + if (ramp.sides.unheldLengthM >= 1) + say( + 'ramp_side_unheld', + ramp.rampId, + Math.max(ramp.sides.cutMaxM, ramp.sides.fillMaxM), + `Beside ${ramp.rampId} the ground stands up to ${ramp.sides.cutMaxM.toFixed(2)} m over its surface and up to ${ramp.sides.fillMaxM.toFixed(2)} m under it, along ${ramp.sides.unheldLengthM.toFixed(1)} m of its sides, and its retaining sides are ${ramp.sides.retainingHeightM.toFixed(2)} m high: a face stands there that nothing holds.`, + ) + if (ramp.maximumSlopePercent > ramp.statedLimitPercent + 1e-6) + say( + 'ramp_steep', + ramp.rampId, + ramp.maximumSlopePercent, + `${ramp.rampId} reaches ${ramp.maximumSlopePercent.toFixed(1)} %, over its stated ${ramp.statedLimitPercent} %.`, + ) + } + for (const face of retaining) + for (const house of face.houses) + if ( + house.standsAt === 'top' && + house.distanceM < L.dropEdgeM && + face.heightM.max >= L.dropHeightM + ) + say( + 'house_at_drop_edge', + house.buildingId, + house.distanceM, + `${house.buildingId} stands ${house.distanceM.toFixed(2)} m from the top of ${face.breakId} (${face.kind}), a drop of up to ${face.heightM.max.toFixed(2)} m.`, + ) + if (bankM2 >= L.bankAreaM2) + say( + 'steep_bank', + site.id, + steepestDeg, + `${bankM2.toFixed(0)} m2 of the lot is ground steeper than ${L.bankDeg} degrees (up to ${steepestDeg.toFixed(0)}) that no wall or face holds.`, + ) + + const sectionHouses = buildings.flatMap((building) => { + const frame = frameOf(building) + const level = groundLevel(record, building) + const plane = level ? levelPlaneWorldY(record, level.id) : null + return frame && level && plane !== null + ? [{ frame, plane, floors: floorSlabsOf(record, level) }] + : [] + }) + return { + hasTerrain: field !== null, + houses, + surfaces, + steps, + ramps, + retaining, + banks: { steepestDeg: round(steepestDeg, 1), areaM2: round(bankM2, 1) }, + ...(field && tiles + ? { + earthwork: { + cutM3: round(cutM3, 1), + fillM3: round(fillM3, 1), + against: base ? 'base_field' : 'datum', + }, + } + : {}), + open, + limits: L, + ...(options.section + ? { + section: sectionOf( + options.section.from, + options.section.to, + ground, + nodes, + sectionHouses, + ), + } + : {}), + ...(field ? {} : { note: FLAT_NOTE }), + } +} diff --git a/packages/core/src/agent-operations/terrain-flat-ground.test.ts b/packages/core/src/agent-operations/terrain-flat-ground.test.ts new file mode 100644 index 0000000000..63117ef9c3 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-flat-ground.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, test } from 'bun:test' +import { z } from 'zod' +import { + AGENT_OPERATIONS, + describeTerrainUnderHouse, + readSiteTerrain, + readTerrainContours, + sampleTerrainLine, +} from '../agent-operations' +import { isAgentRefusal } from '../agent-tools' +import { siteTerrainOutput } from '../agent-tools/terrain' +import { type AnyNode, BuildingNode, LevelNode, SiteNode, SlabNode } from '../schema' +import { terrainHouseScene, terrainRampScene } from './__fixtures__/terrain-cases' + +type Nodes = Record +const context = { activeLevelId: null } + +// A site nobody has shaped keeps `terrain` absent: its ground is the flat datum plane, y = 0. +const lot: [number, number][] = [ + [0, 0], + [20, 0], + [20, 10], + [0, 10], +] +const flatSite = (id = 'site_flat') => + SiteNode.parse({ id, polygon: { type: 'polygon', points: lot } }) +const flat = (): Nodes => ({ site_flat: flatSite() }) + +/** A house slab at 0.4 m on the flat lot: the ground under it is the datum. */ +function flatHouse(): Nodes { + const site = flatSite() + const building = BuildingNode.parse({ id: 'building_house', parentId: site.id }) + const level = LevelNode.parse({ id: 'level_house', parentId: building.id, level: 0, height: 3 }) + const slab = SlabNode.parse({ + id: 'slab_house', + parentId: level.id, + boundary: 'auto', + polygon: [ + [4, 2], + [12, 2], + [12, 8], + [4, 8], + ], + elevation: 0.4, + }) + return { + [site.id]: { ...site, children: [building.id] }, + [building.id]: { ...building, children: [level.id] }, + [level.id]: { ...level, children: [slab.id] }, + [slab.id]: slab, + } +} + +function refusalCode(call: () => unknown): string | null { + try { + call() + } catch (error) { + if (isAgentRefusal(error)) return error.code + throw error + } + return null +} + +describe('read_site_terrain on a site with no shaped ground', () => { + test('answers with the flat datum facts, not an error', () => { + const { result } = readSiteTerrain(flat(), {}, context) + + expect(result).toMatchObject({ + hasTerrain: false, + flat: true, + reliefM: 0, + minM: 0, + maxM: 0, + datumM: 0, + slopeMeanDeg: 0, + slopeMaxDeg: 0, + areaAboveGradeM2: 0, + areaBelowGradeM2: 0, + }) + }) + + test('gives every corner of the footprint a level normal and every edge no drop', () => { + const { result } = readSiteTerrain(flat(), {}, context) + + expect(result.slopeAtCorners).toEqual( + lot.map(([x, z]) => ({ x, z, slopeDeg: 0, normal: [0, 1, 0] })), + ) + expect(result.edgeDrops).toHaveLength(4) + for (const edge of result.edgeDrops as { dropM: number; maxSlopeDeg: number }[]) + expect(edge).toMatchObject({ dropM: 0, maxSlopeDeg: 0 }) + }) + + test('says that no relief is shaped and that the ground is the datum plane', () => { + const { result } = readSiteTerrain(flat(), {}, context) + + expect(result.note).toBe( + 'No relief is shaped on this site: the ground is the flat datum plane at y = 0. Relief is shaped with shape_site_terrain and carve_terrain_pad.', + ) + }) + + test('reads the footprint it is given', () => { + const footprint = [ + [2, 2], + [6, 2], + [6, 5], + ] + + const { result } = readSiteTerrain(flat(), { footprint }, context) + + expect(result.slopeAtCorners).toHaveLength(3) + expect(result.hasTerrain).toBe(false) + }) + + test('is valid output of the contract, as a shaped site is', () => { + const output = z.object(siteTerrainOutput) + + expect(output.safeParse(readSiteTerrain(flat(), {}, context).result).success).toBe(true) + const shaped = readSiteTerrain(terrainRampScene().nodes as Nodes, {}, context).result + expect(output.safeParse(shaped).success).toBe(true) + expect(shaped.hasTerrain).toBe(true) + }) + + test('a shaped site has no note', () => { + const { result } = readSiteTerrain(terrainRampScene().nodes as Nodes, {}, context) + + expect(result.note).toBeUndefined() + }) +}) + +describe('the other reads on a site with no shaped ground', () => { + test('sample_terrain_line is level ground along the segment', () => { + const { result } = sampleTerrainLine(flat(), { from: [1, 1], to: [3, 1] }, context) + + const points = result.points as { yM: number; slopeDeg: number }[] + expect(points.length).toBeGreaterThan(2) + expect(points.every((point) => point.yM === 0 && point.slopeDeg === 0)).toBe(true) + expect(result.note).toContain('flat datum plane') + }) + + test('read_terrain_contours has no contour lines to report', () => { + const { result } = readTerrainContours(flat(), {}, context) + + expect(result).toMatchObject({ datum: 0, lines: [] }) + expect(result.note).toContain('flat datum plane') + }) + + test('describe_terrain_under_house puts the datum under the slab', () => { + const { result } = describeTerrainUnderHouse(flatHouse(), {}, context) + + expect(result).toMatchObject({ + slabId: 'slab_house', + slabTopM: 0.4, + highestM: 0, + lowestM: 0, + reliefM: 0, + clearanceUnderSlabM: 0.4, + }) + expect((result.dropAtEdges as { dropM: number }[]).every((edge) => edge.dropM === 0.4)).toBe( + true, + ) + expect(result.needsGuardAt).toEqual([]) + expect(result.note).toContain('flat datum plane') + }) + + test('the shaped house read is unchanged', () => { + const { result } = describeTerrainUnderHouse(terrainHouseScene().nodes as Nodes, {}, context) + + expect(result.note).toBeUndefined() + expect(result.reliefM).toBeGreaterThan(0) + }) +}) + +describe('the refusals that are real still refuse', () => { + const reads = { + read_site_terrain: {}, + sample_terrain_line: { from: [1, 1], to: [2, 1] }, + read_terrain_contours: {}, + } as const + + test('no site', () => { + for (const [tool, input] of Object.entries(reads)) { + const operation = AGENT_OPERATIONS[tool as keyof typeof reads] + expect(refusalCode(() => operation({}, input as never, context))).toBe('no_site') + } + }) + + test('several sites', () => { + const nodes = { ...flat(), site_other: flatSite('site_other') } + + expect(refusalCode(() => readSiteTerrain(nodes, {}, context))).toBe('ambiguous_site') + }) + + test('a persisted field that cannot be read is not flat ground', () => { + const nodes = terrainRampScene().nodes as Nodes + const site = nodes.site_terrain as SiteNode + const broken = { ...site, terrain: { ...site.terrain, heights: 'broken' } } as SiteNode + + expect(refusalCode(() => readSiteTerrain({ site_terrain: broken }, {}, context))).toBe( + 'no_terrain', + ) + }) + + test('an empty or self-crossing footprint', () => { + expect(refusalCode(() => readSiteTerrain(flat(), { footprint: [] }, context))).toBe( + 'footprint_empty', + ) + const bowtie = [ + [0, 0], + [4, 4], + [4, 0], + [0, 4], + ] + expect(refusalCode(() => readSiteTerrain(flat(), { footprint: bowtie }, context))).toBe( + 'invalid_polygon', + ) + }) + + test('a house read still needs a slab to stand on', () => { + expect(refusalCode(() => describeTerrainUnderHouse(flat(), {}, context))).toBe( + 'footprint_empty', + ) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-flat-writes.test.ts b/packages/core/src/agent-operations/terrain-flat-writes.test.ts new file mode 100644 index 0000000000..4f8882774d --- /dev/null +++ b/packages/core/src/agent-operations/terrain-flat-writes.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, test } from 'bun:test' +import { clearSceneHistory, heightAt, persistedTerrainFieldOf, useScene } from '@pascal-app/core' +import { + applySceneChanges, + carveTerrainPad, + shapeSiteTerrain, +} from '@pascal-app/core/agent-operations' +import { isAgentRefusal } from '@pascal-app/core/agent-tools' +import { type AnyNode, SiteNode } from '@pascal-app/core/schema' +import type { AgentOperationOutcome } from './types' + +type Nodes = Record +const context = { activeLevelId: null } + +// B1 writes only the touched 0.5 m tiles; an untouched lot has no terrain payload. +function lot(width: number, depth: number): Nodes { + const site = SiteNode.parse({ + id: 'site_flat', + polygon: { + type: 'polygon', + points: [ + [0, 0], + [width, 0], + [width, depth], + [0, depth], + ], + }, + }) + return { [site.id]: site } +} + +const raise = { verb: 'raise', area: { x: 10, z: 5, radiusM: 2 }, heightM: 0.5 } as const +const pad: [number, number][] = [ + [8, 3], + [12, 3], + [12, 7], + [8, 7], +] + +const applied = (nodes: Nodes, outcome: AgentOperationOutcome): Nodes => + outcome.changes ? (applySceneChanges(nodes, outcome.changes) as Nodes) : nodes + +function refusalOf(call: () => unknown): { code: string; message: string } | null { + try { + call() + } catch (error) { + if (isAgentRefusal(error)) return { code: error.code, message: error.message } + throw error + } + return null +} + +describe('shaping a site with no shaped ground', () => { + test('shape_site_terrain starts from flat ground and persists only touched tiles', () => { + const nodes = lot(20, 10) + + const outcome = shapeSiteTerrain(nodes, raise, context) + + const after = applied(nodes, outcome) + const field = persistedTerrainFieldOf(after.site_flat as SiteNode, after) + expect(field?.spacing).toBe(0.5) + expect((after.site_flat as SiteNode).terrain).toBeUndefined() + expect(Object.values(after).filter((node) => node.type === 'terrain-tile')).toHaveLength(1) + expect(heightAt(field as never, 10, 5)).toBe(0.5) + expect(outcome.result).toMatchObject({ + beforeMinMaxM: { minM: 0, maxM: 0 }, + afterMinMaxM: { minM: 0.5, maxM: 0.5 }, + }) + expect(outcome.result.changedSamples).toBeGreaterThan(0) + }) + + test('carve_terrain_pad levels a pad on it', () => { + const outcome = carveTerrainPad(lot(20, 10), { pad, padHeightM: 0.5 }, context) + + expect(outcome.result.cutVolumeM3).toBe(0) + expect(outcome.result.fillVolumeM3).toBeGreaterThan(0) + expect(outcome.result.padHeightM).toBeCloseTo(0.5, 6) + }) + + test('tile creation and the shape are one undo step', () => { + const original = useScene.getState() + try { + const before = lot(20, 10) + useScene.setState({ nodes: before, rootNodeIds: ['site_flat'] } as never) + clearSceneHistory() + const outcome = shapeSiteTerrain(before, raise, context) + useScene.setState({ nodes: applied(before, outcome) } as never) + expect( + Object.values(useScene.getState().nodes).some((node) => node.type === 'terrain-tile'), + ).toBe(true) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + const restored = useScene.getState().nodes as Nodes + expect((restored.site_flat as SiteNode).terrain).toBeUndefined() + expect(restored).toEqual(before) + } finally { + useScene.setState(original) + clearSceneHistory() + } + }) + + test('a shape that moves nothing writes no field', () => { + const outcome = refusalOf(() => + shapeSiteTerrain(lot(20, 10), { verb: 'flatten', area: raise.area, heightM: 0 }, context), + ) + + expect(outcome?.code).toBe('no_change') + }) +}) + +describe('the size of one terrain write', () => { + // The former 62 m limit came from serializing one monolithic field, not the lot. + for (const width of [62, 63, 128]) { + test(`a ${width} m lot supports repeated bounded tile writes`, () => { + let nodes = lot(width, 80) + for (const x of [10, 40]) { + nodes = applied( + nodes, + shapeSiteTerrain(nodes, { ...raise, area: { x, z: 5, radiusM: 2 } }, context), + ) + } + nodes = applied(nodes, carveTerrainPad(nodes, { pad, padHeightM: 1 }, context)) + const field = persistedTerrainFieldOf(nodes.site_flat as SiteNode, nodes) + expect(heightAt(field as never, 10, 5)).toBe(1) + expect(heightAt(field as never, 40, 5)).toBe(0.5) + expect((nodes.site_flat as SiteNode).terrain).toBeUndefined() + const tiles = Object.values(nodes).filter((node) => node.type === 'terrain-tile') + expect(tiles).toHaveLength(2) + for (const tile of tiles) + expect( + new TextEncoder().encode(JSON.stringify({ from: tile, to: tile })).length, + ).toBeLessThan(64 * 1024) + }) + } + + test('a small lot is shaped again and again', () => { + let nodes = lot(20, 10) + for (const x of [6, 10, 14]) { + const area = { x, z: 5, radiusM: 2 } + nodes = applied(nodes, shapeSiteTerrain(nodes, { ...raise, area }, context)) + } + + const field = persistedTerrainFieldOf(nodes.site_flat as SiteNode, nodes) + for (const x of [6, 10, 14]) expect(heightAt(field as never, x, 5)).toBe(0.5) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-grade-stacked.test.ts b/packages/core/src/agent-operations/terrain-grade-stacked.test.ts new file mode 100644 index 0000000000..fabc5e0df9 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-grade-stacked.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, test } from 'bun:test' +import { isAgentRefusal } from '../agent-tools/refusal' +import { type AnyNode, LevelNode, SlabNode } from '../schema' +import { GROUNDS, groundAt, type Pt, runTool, slopedLot } from './__fixtures__/sloped-lots' + +/* + * grade_around_house `pads`: one pad per level of a split-level house, side by side. Storeys that + * stand one over the other are not a split level: the upper pad would win everywhere and bury the + * ground floor under a platform at the upper floor's height. + */ + +const upper = (polygon: Pt[]): AnyNode[] => [ + LevelNode.parse({ + id: 'level_upper', + parentId: 'building_house', + level: 1, + name: 'Upper floor', + height: 2.7, + }), + SlabNode.parse({ id: 'slab_upper', parentId: 'level_upper', polygon, elevation: 0.05 }), +] +const refusal = (run: () => unknown) => { + try { + run() + } catch (error) { + if (isAgentRefusal(error)) return { code: error.code, message: error.message } + throw error + } + return undefined +} +const PADS = { pads: [{ levelId: 'level_ground' }, { levelId: 'level_upper' }] } + +describe('grade_around_house: pads are side by side, not stacked', () => { + test('two storeys one over the other are refused, and the ground is left as it was', () => { + const house = slopedLot({ + ground: GROUNDS.steep, + extra: upper([ + [-6, -4], + [6, -4], + [6, 4], + [-6, 4], + ]), + }) + const refused = refusal(() => runTool(house, 'grade_around_house', PADS)) + expect(refused?.code).toBe('invalid_input') + expect(refused?.message).toContain('level_upper') + expect(refused?.message).toContain('one over the other') + }) + + test('a split level, its upper half beside the lower one, is graded with a pad each', () => { + // The upper level's floor lies behind the ground floor's plate (z -12 to -4 against -4 to 4): + // the plan a split level has. + const house = slopedLot({ + ground: GROUNDS.steep, + extra: upper([ + [-6, -12], + [6, -12], + [6, -4], + [-6, -4], + ]), + }) + const { nodes, result } = runTool(house, 'grade_around_house', PADS) + expect((result.pads as unknown[]).length).toBe(2) + expect(groundAt(nodes, 0, 0)).toBeCloseTo(0, 1) + expect(groundAt(nodes, 0, -8)).toBeCloseTo(2.6, 1) + }) + + test('outlines that share a wall line (the width of a wall) are still side by side', () => { + const house = slopedLot({ + ground: GROUNDS.steep, + extra: upper([ + [-6, -12], + [6, -12], + [6, -3.8], + [-6, -3.8], + ]), + }) + expect(refusal(() => runTool(house, 'grade_around_house', PADS))).toBeUndefined() + }) +}) diff --git a/packages/core/src/agent-operations/terrain-grade.test.ts b/packages/core/src/agent-operations/terrain-grade.test.ts new file mode 100644 index 0000000000..4e4f799f7c --- /dev/null +++ b/packages/core/src/agent-operations/terrain-grade.test.ts @@ -0,0 +1,878 @@ +import { describe, expect, test } from 'bun:test' +import { + clearSceneHistory, + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + type TerrainField, + terrainBreakFacts, + useScene, +} from '@pascal-app/core' +import { + AGENT_OPERATIONS, + applySceneChanges, + gradeAroundHouse, +} from '@pascal-app/core/agent-operations' +import { + AGENT_TOOL_CONTRACTS, + gradeAroundHouseTool, + isAgentRefusal, +} from '@pascal-app/core/agent-tools' +import { + type AnyNode, + BuildingNode, + LevelNode, + SiteNode, + SlabNode, + type TerrainBreakNode, +} from '@pascal-app/core/schema' +import type { AgentOperationOutcome } from './types' + +/* + * The ground around a house as a function of the distance to its outline: a pad, then a batter to the + * ground that was there. Every scene here is a 40 x 40 m lot (−20…20) on a 0.5 m field; the house is + * the rectangle x −5…5, z 0…6 and its rear (the uphill side where there is one) is toward −z. + */ + +type Nodes = Record +type Point = [number, number] +const context = { activeLevelId: null } +const HOUSE: Point[] = [ + [-5, 0], + [5, 0], + [5, 6], + [-5, 6], +] + +/** A lot whose natural ground is `ground(x, z)` metres. */ +function lot( + ground: (x: number, z: number) => number, + extra: AnyNode[] = [], + siteFields: Record = {}, +): Nodes { + const field = createTerrainField({ origin: [-20, -20], spacing: 0.5, cols: 81, rows: 81 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = Math.round( + ground(-20 + col * 0.5, -20 + row * 0.5) / field.step, + ) + const site = SiteNode.parse({ + id: 'site_grade', + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [20, -20], + [20, 20], + [-20, 20], + ], + }, + terrain: encodeTerrainField(field), + children: extra.map((node) => node.id), + ...siteFields, + }) + return { [site.id]: site, ...Object.fromEntries(extra.map((node) => [node.id, node])) } +} + +const grade = (nodes: Nodes, input: Record = {}) => { + const outcome = gradeAroundHouse( + nodes, + { footprint: HOUSE, padHeightM: 0, scope: 'context', ...input }, + context, + ) + return { outcome, after: applied(nodes, outcome) } +} + +function applied(nodes: Nodes, outcome: AgentOperationOutcome): Nodes { + return outcome.changes ? (applySceneChanges(nodes, outcome.changes) as Nodes) : nodes +} + +function fieldOf(nodes: Nodes): TerrainField { + const field = persistedTerrainFieldOf(nodes.site_grade as SiteNode, nodes) + if (!field) throw new Error('expected a persisted field') + return field +} + +const groundAt = (nodes: Nodes, x: number, z: number) => heightAt(fieldOf(nodes), x, z) +const refusalCode = (run: () => unknown) => { + try { + run() + } catch (error) { + if (isAgentRefusal(error)) return error.code + throw error + } + return undefined +} + +/** The lot's street edge is its +z side: the rear is −z, where ground rises. */ +const STREET_AT_PLUS_Z = { frontEdge: 2 } + +/** Ground that rises toward −z at `slope` metres per metre. */ +const risingBehind = (slope: number) => (_x: number, z: number) => Math.max(0, -z) * slope + +describe('grade_around_house: the batter', () => { + test('rises at the stated run from the pad edge, in a cut', () => { + const { after, outcome } = grade(lot(risingBehind(1)), { run: 2, marginM: 1 }) + // −z is uphill; the pad reaches 1 m beyond the wall (z = −1), then 1 m of height per 2 m of ground. + for (const [z, rise] of [ + [-1, 0], + [-3, 1], + [-5, 2], + [-7, 3], + ] as const) + expect(groundAt(after, 0, z)).toBeCloseTo(rise, 1) + expect(outcome.result.batterSlopeDeg).toBeCloseTo(26.57, 1) + expect(outcome.result.cutVolumeM3).toBeGreaterThan(0) + expect(outcome.result.fillVolumeM3).toBe(0) + }) + + test('falls at the stated run, in a fill, and stops where it meets the ground', () => { + const { after, outcome } = grade( + lot(() => -1.5), + { run: 2, marginM: 1 }, + ) + // The ground is 1.5 m under the pad: the batter falls 1 m per 2 m and daylights 3 m from the pad edge. + expect(groundAt(after, 0, -3)).toBeCloseTo(-1, 1) + expect(groundAt(after, 0, -4)).toBeCloseTo(-1.5, 1) + expect(groundAt(after, 0, -9)).toBeCloseTo(-1.5, 2) + expect(outcome.result.fillVolumeM3).toBeGreaterThan(0) + expect(outcome.result.cutVolumeM3).toBe(0) + expect(outcome.result.daylight).toMatchObject({ reached: true }) + }) + + test('a gentler ground than the batter is left as it is, past the daylight line', () => { + const natural = risingBehind(0.25) + const { after, outcome } = grade(lot(natural), { run: 2, marginM: 1 }) + // 1:4 ground against a 1:2 batter: the line meets it 2 m behind the wall; beyond that nothing moves. + expect(groundAt(after, 0, -6)).toBeCloseTo(natural(0, -6), 2) + expect(groundAt(after, 0, -2)).toBeCloseTo(0.5, 1) + expect((outcome.result.daylight as { farthestChangeM: number }).farthestChangeM).toBeLessThan(2) + }) + + test('never raises ground on a cut side nor lowers it on a fill side', () => { + const lowAndHigh = (x: number) => (x < 0 ? 3 : -3) + const { after } = grade( + lot((x) => lowAndHigh(x)), + { run: 2 }, + ) + const before = fieldOf(lot((x) => lowAndHigh(x))) + for (const x of [-12, -8, 8, 12]) { + const was = heightAt(before, x, 3) + const now = groundAt(after, x, 3) + if (was > 0) expect(now).toBeLessThanOrEqual(was + 1e-9) + else expect(now).toBeGreaterThanOrEqual(was - 1e-9) + } + }) +}) + +describe('grade_around_house: terraces', () => { + test('the batter is cut into treads run times as wide as the riser, on the lattice', () => { + const { after, outcome } = grade(lot(risingBehind(2)), { + run: 2, + marginM: 1, + terraceRiserM: 0.5, + }) + // Tread 1 m: the ground is at 0 up to u = 1 m, 0.5 to 2 m, 1.0 to 3 m … (u from the pad edge, z = −1 − u). + const heights = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4].map((u) => groundAt(after, 0, -1 - u)) + expect(heights.map((height) => Math.round(height * 100) / 100)).toEqual([ + 0, 0.5, 0.5, 1, 1, 1.5, 1.5, 2, + ]) + for (const z of [-2, -3, -4, -5, -6]) { + const level = groundAt(after, 0, z) / 0.5 + expect(level).toBeCloseTo(Math.round(level), 1) + } + expect(outcome.result.terraces).toEqual({ riserM: 0.5, treadM: 1, resolutionM: 0.5 }) + }) +}) + +describe('grade_around_house: it follows the outline', () => { + test('equal distances from a convex corner are equal heights: the slope is rounded there', () => { + const { after } = grade( + lot(() => 3), + { run: 2, marginM: 1 }, + ) + // The house's rear-right corner is (5, 0); both points are 2.5 m from it (a 3-4-5 triangle). + const along = groundAt(after, 7.5, 0) + const around = groundAt(after, 6.5, -2) + expect(along).toBeCloseTo((2.5 - 1) / 2, 1) + expect(around).toBeCloseTo(along, 2) + // A square offset would put the diagonal point 2.0 m out, not 2.5 m: 0.5 m of batter, not 0.75 m. + expect(Math.abs(around - 0.5)).toBeGreaterThan(0.2) + }) + + test('a bent outline gives the batter its offset', () => { + const lShape: Point[] = [ + [-5, 0], + [5, 0], + [5, 6], + [0, 6], + [0, 3], + [-5, 3], + ] + const { after } = grade( + lot(() => 3), + { footprint: lShape, run: 2, marginM: 1 }, + ) + // The inner corner (0, 3): the point 2 m into the notch's corner region is 2 m from both walls. + const inNotch = groundAt(after, -2, 5) + expect(inNotch).toBeCloseTo((2 - 1) / 2, 1) + }) +}) + +describe('grade_around_house: a declared wall', () => { + test('makes a vertical step at the pad edge where it is declared, and none where it is not', () => { + const base = lot(risingBehind(2)) + const walled = grade(base, { run: 2, marginM: 1, wallM: 1.3 }) + const plain = grade(base, { run: 2, marginM: 1 }) + const step = (nodes: Nodes) => groundAt(nodes, 0, -1.5) - groundAt(nodes, 0, -1) + expect(step(walled.after)).toBeGreaterThan(1.3) + expect(step(plain.after)).toBeLessThan(0.5) + expect(walled.outcome.result.wall).toMatchObject({ + heightM: 1.3, + exact: false, + resolutionM: 0.5, + }) + expect(plain.outcome.result.wall).toBeUndefined() + }) +}) + +describe('grade_around_house: where it meets other terrain', () => { + test('ground an earlier pad leveled is cut where it stands above the batter and left where it is below', () => { + const early = AGENT_OPERATIONS.carve_terrain_pad!( + lot(risingBehind(1)), + { + pad: [ + [-6, -10], + [6, -10], + [6, -4], + [-6, -4], + ], + padHeightM: 2.5, + blendM: 1, + }, + context, + ) + const padded = applied(lot(risingBehind(1)), early) + const { after } = grade(padded, { run: 2, marginM: 1 }) + // The batter line at z = −5 is 2 m high, at z = −8 it is 3.5 m: the 2.5 m pad is cut at the first, kept at the second. + expect(groundAt(after, 0, -5)).toBeCloseTo(2, 1) + expect(groundAt(after, 0, -8)).toBeCloseTo(2.5, 1) + }) + + test('a numeric terrain break sets its heights whatever the batter writes under it', () => { + const base = lot(risingBehind(0.5)) + const wall = AGENT_OPERATIONS.add_terrain_break!( + base, + { + line: [ + [-20, -10], + [20, -10], + ], + kind: 'retaining', + left: 'ground', + right: 4, + }, + context, + ) + const walled = applied(base, wall) + const { after } = grade(walled, { run: 2, reachM: 30 }) + // The ground behind z = −10 is the break's 4 m plane; the batter's own (reaching there) does not change it. + expect(groundAt(after, 0, -14)).toBeCloseTo(4, 2) + expect(groundAt(after, 0, -6)).toBeLessThan(4) + }) +}) + +describe('grade_around_house: the house comes from the scene', () => { + function withHouse(slabElevation = 0.3): Nodes { + const building = BuildingNode.parse({ + id: 'building_g', + parentId: 'site_grade', + children: ['level_g'], + }) + const level = LevelNode.parse({ + id: 'level_g', + parentId: building.id, + level: 0, + height: 3, + children: ['slab_g'], + }) + const slab = SlabNode.parse({ + id: 'slab_g', + parentId: level.id, + boundary: 'auto', + polygon: HOUSE, + elevation: slabElevation, + }) + return lot(risingBehind(1), [building, level, slab]) + } + + test('the lowest slab is the outline and the pad stands under its top', () => { + const outcome = gradeAroundHouse(withHouse(0.3), {}, context) + expect(outcome.result).toMatchObject({ levelId: 'level_g', slabId: 'slab_g', slabTopM: 0.3 }) + expect(outcome.result.padHeightM).toBeCloseTo(0.15, 6) + expect(outcome.result.footprint).toEqual(HOUSE) + }) + + test('is one undo step, and undo restores the ground byte for byte', () => { + const original = useScene.getState() + try { + const before = withHouse() + const beforeTerrain = JSON.stringify((before.site_grade as SiteNode).terrain) + useScene.setState({ nodes: before, rootNodeIds: ['site_grade'] } as never) + clearSceneHistory() + const outcome = gradeAroundHouse(before, {}, context) + useScene.setState({ nodes: applied(before, outcome) } as never) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + const restored = useScene.getState().nodes as Nodes + expect(JSON.stringify((restored.site_grade as SiteNode).terrain)).toBe(beforeTerrain) + } finally { + useScene.setState(original) + clearSceneHistory() + } + }) + + test('the agent tool contract and the operation are registered under one name', () => { + expect(AGENT_TOOL_CONTRACTS).toContain(gradeAroundHouseTool) + expect(AGENT_OPERATIONS.grade_around_house).toBe(gradeAroundHouse) + }) +}) + +describe('grade_around_house: refusals', () => { + test.each([ + ['a given footprint needs its pad height', { footprint: HOUSE }, 'invalid_input'], + [ + 'a level and a footprint are not both given', + { levelId: 'level_x', footprint: HOUSE, padHeightM: 0 }, + 'invalid_input', + ], + [ + 'an outline outside the property', + { + footprint: [ + [30, 30], + [34, 30], + [34, 34], + [30, 34], + ], + padHeightM: 0, + }, + 'outside_property', + ], + [ + 'a run flatter than the schema allows', + { footprint: HOUSE, padHeightM: 0, run: 0.1 }, + 'invalid_input', + ], + ['a house with no slab', {}, 'footprint_empty'], + ] as const)('%s', (_name, input, code) => { + expect( + refusalCode(() => + gradeAroundHouse( + lot(() => 1), + input as never, + context, + ), + ), + ).toBe(code) + }) + + test('grading ground that is already graded writes nothing', () => { + const first = grade(lot(risingBehind(1)), { run: 2 }) + expect( + refusalCode(() => + gradeAroundHouse( + first.after, + { footprint: HOUSE, padHeightM: 0, run: 2, scope: 'context' }, + context, + ), + ), + ).toBe('no_change') + }) +}) + +const breaksOf = (nodes: Nodes) => + Object.values(nodes).filter((node): node is TerrainBreakNode => node.type === 'terrain-break') +const roundedTo = (value: number, places = 2) => Math.round(value * 10 ** places) / 10 ** places + +describe('grade_around_house: a lawn after the bank', () => { + test('raises low ground to the lawn level through a bank at the stated run, and cuts high ground to it', () => { + for (const natural of [0, 5]) { + const { after, outcome } = grade( + lot(() => natural), + { scope: 'lot', run: 2, marginM: 1, upperLevelM: 2 }, + ) + // The pad edge is 1 m from the wall (z = −1): 1 m of height per 2 m of ground, then 2 m flat, to the lot's edge. + for (const [z, level] of [ + [-1, 0], + [-3, 1], + [-5, 2], + [-18, 2], + ] as const) + expect(groundAt(after, 0, z)).toBeCloseTo(level, 1) + expect(groundAt(after, 18, 18)).toBeCloseTo(2, 2) + expect(outcome.result.lawn).toMatchObject({ levelM: 2, bankRunM: 4 }) + } + }) + + test('a lawn below the pad is a fill held up by the wall, and stops at the reach in scope context', () => { + const { after, outcome } = grade( + lot(() => 0), + { scope: 'context', run: 2, marginM: 1, upperLevelM: -1, wallM: 0.5, reachM: 6 }, + ) + // Under the pad by wallM at the edge, then 1 m per 2 m down to the lawn at −1; nothing beyond 6 m from the pad edge. + expect(groundAt(after, 0, -1.5)).toBeCloseTo(-0.75, 1) + expect(groundAt(after, 0, -3)).toBeCloseTo(-1, 1) + expect(groundAt(after, 0, -10)).toBeCloseTo(0, 2) + expect(outcome.result.lawn).toMatchObject({ levelM: -1, bankRunM: 1 }) + }) +}) + +describe('grade_around_house: a wall on the fill side', () => { + test('stands below the pad by wallM, as it stands above it on the cut side', () => { + const { after } = grade( + lot(() => -3), + { run: 2, marginM: 1, wallM: 1 }, + ) + // −1 m at the edge (the wall), then 1 m per 2 m down to the ground at −3. + expect(groundAt(after, 0, -1.5)).toBeCloseTo(-1.25, 1) + expect(groundAt(after, 0, -4)).toBeCloseTo(-2.5, 1) + expect(groundAt(after, 0, -6)).toBeCloseTo(-3, 1) + }) +}) + +describe('grade_around_house: a band across the lot', () => { + const rising = () => lot(risingBehind(1), [], STREET_AT_PLUS_Z) + + test('grades the rear edge across the whole width of the lot, not around the outline', () => { + const ring = grade(rising(), { run: 2, marginM: 1 }) + const band = grade(rising(), { run: 2, marginM: 1, edge: { facing: 'rear' } }) + // 2 m behind the pad edge the batter is 1 m up, at the house's width and 15 m to the side of it alike. + for (const x of [0, 4, 15]) expect(groundAt(band.after, x, -3)).toBeCloseTo(1, 1) + expect(groundAt(ring.after, 0, -3)).toBeCloseTo(1, 1) + expect(groundAt(ring.after, 15, -3)).toBeCloseTo(3, 1) + expect(band.outcome.result.edge).toMatchObject({ role: 'rear', normal: [0, -1] }) + }) + + test('the pad is the strip from the front of the outline to the edge, across the lot', () => { + const sideways = (x: number) => 0.3 * x + const band = grade(lot(sideways, [], STREET_AT_PLUS_Z), { + scope: 'lot', + marginM: 1, + edge: { facing: 'rear' }, + }) + // Beside the house, inside the strip's depth (z 0…6), the ground is the pad's 0 out to the lot's side; in front of the strip it batters back to the ground. + expect(groundAt(band.after, 15, 3)).toBeCloseTo(0, 2) + expect(groundAt(band.after, -15, 3)).toBeCloseTo(0, 2) + expect(groundAt(band.after, 15, 17)).toBeCloseTo(4.5, 1) + }) + + test('the lawn applies beyond the edge only; the front of the strip meets the ground as a ring does', () => { + const { after } = grade( + lot(() => -3, [], STREET_AT_PLUS_Z), + { scope: 'lot', run: 2, marginM: 1, upperLevelM: 2, edge: { facing: 'rear' } }, + ) + expect(groundAt(after, 0, -18)).toBeCloseTo(2, 2) + expect(groundAt(after, 15, -18)).toBeCloseTo(2, 2) + expect(groundAt(after, 0, 18)).toBeCloseTo(-3, 2) + }) + + test('a direction and a line on the outline name the same edge as the lot side facing that way', () => { + const facing = grade(rising(), { run: 2, edge: { facing: 'rear' } }) + for (const edge of [ + { direction: [0, -3] }, + { + line: [ + [-20, 0], + [20, 0], + ], + }, + ]) { + const other = grade(rising(), { run: 2, edge }) + for (const [x, z] of [ + [0, -3], + [12, -5], + [-12, 3], + ] as const) + expect(groundAt(other.after, x, z)).toBeCloseTo(groundAt(facing.after, x, z), 2) + } + // A line beyond the outline moves the edge out with it. + const beyond = grade(rising(), { + run: 2, + marginM: 1, + edge: { + line: [ + [-20, -2], + [20, -2], + ], + }, + }) + expect(groundAt(beyond.after, 0, -3)).toBeCloseTo(0, 1) + expect(groundAt(beyond.after, 0, -5)).toBeCloseTo(1, 1) + }) + + test.each([ + ['none of facing, direction, line', { edge: {} }], + ['two of them', { edge: { facing: 'rear', direction: [0, -1] } }], + [ + 'a line across the house', + { + edge: { + line: [ + [-20, 3], + [20, 3], + ], + }, + }, + ], + ['a direction with no length', { edge: { direction: [0, 0] } }], + ])('an edge with %s is refused', (_name, input) => { + expect( + refusalCode(() => + gradeAroundHouse( + rising(), + { footprint: HOUSE, padHeightM: 0, scope: 'context', ...input } as never, + context, + ), + ), + ).toBe('invalid_input') + }) +}) + +describe('grade_around_house: an exact wall', () => { + const faceOf = (after: Nodes) => { + const [wall] = breaksOf(after) + return terrainBreakFacts(wall as TerrainBreakNode, fieldOf(after)) + } + + test('is a retaining terrain-break whose pad side is the numeric plane, as high as declared on the cut side', () => { + // Ground that climbs to 3 m within a metre behind the house: cut to the pad, then the wall, then a bank back up. + const base = lot((_x, z) => Math.min(3, Math.max(0, -z * 3))) + const { after, outcome } = grade(base, { run: 2, marginM: 1, wallM: 1, exactWall: true }) + const [wall] = breaksOf(after) + expect(breaksOf(after)).toHaveLength(1) + expect(wall).toMatchObject({ kind: 'retaining', left: 0, right: 'ground' }) + expect(wall?.line[0]).toEqual(wall?.line.at(-1)) + expect(outcome.result.wall).toMatchObject({ + heightM: 1, + exact: true, + kind: 'retaining', + breakId: wall?.id, + }) + expect(outcome.changes?.create?.some(({ node }) => node.type === 'terrain-break')).toBe(true) + // The face stands exactly 1 m on the cut (rear) side; no lattice smears it. + expect(roundedTo(faceOf(after).dropMaxM, 1)).toBe(1) + expect(groundAt(after, 0, -0.9)).toBeCloseTo(0, 2) + expect(groundAt(after, 0, -1.1)).toBeCloseTo(1.05, 1) + }) + + test('its face is not counted among the sampled slopes, as a lattice step is', () => { + const lawn = { scope: 'lot', run: 2, marginM: 1, wallM: 1, upperLevelM: 2 } + const exact = grade( + lot(() => 0), + { ...lawn, exactWall: true }, + ) + const lattice = grade( + lot(() => 0), + lawn, + ) + // The bank is 1:2 (26.6 degrees); a 1 m step on the 0.5 m lattice reads 63 degrees. + expect(exact.outcome.result.steepestSampledSlopeDeg as number).toBeLessThan(30) + expect(lattice.outcome.result.steepestSampledSlopeDeg as number).toBeGreaterThan(55) + }) + + test('stands on the fill side too', () => { + const { after } = grade( + lot(() => -3), + { run: 2, marginM: 1, wallM: 1, exactWall: true }, + ) + expect(roundedTo(faceOf(after).dropMaxM, 1)).toBe(1) + expect(groundAt(after, 0, -0.9)).toBeCloseTo(0, 2) + expect(groundAt(after, 0, -1.1)).toBeCloseTo(-1.05, 1) + }) + + test('rings the convex hull: a notch in the outline is filled into the pad', () => { + const lShape: Point[] = [ + [-5, 0], + [5, 0], + [5, 6], + [0, 6], + [0, 3], + [-5, 3], + ] + const { after } = grade( + lot(() => 3), + { footprint: lShape, run: 2, marginM: 1, wallM: 1, exactWall: true }, + ) + expect(groundAt(after, -3, 4.5)).toBeCloseTo(0, 2) + }) + + test('a second call for the same house replaces its wall', () => { + const first = grade(lot(risingBehind(2)), { run: 2, marginM: 1, wallM: 1, exactWall: true }) + const [old] = breaksOf(first.after) + const second = grade(first.after, { run: 2, marginM: 1, wallM: 0.5, exactWall: true }) + expect(breaksOf(second.after)).toHaveLength(1) + expect(breaksOf(second.after)[0]?.id).not.toBe(old?.id) + expect(roundedTo(faceOf(second.after).dropMaxM, 1)).toBe(0.5) + }) + + test('along a band it is one closed ring around the pad strip, clipped to the property', () => { + const sideways = (x: number, z: number) => 0.3 * x + Math.max(0, -z) + const { after, outcome } = grade(lot(sideways, [], STREET_AT_PLUS_Z), { + scope: 'lot', + run: 2, + marginM: 1, + wallM: 1, + exactWall: true, + edge: { facing: 'rear' }, + }) + // The house is z 0…6: the strip runs from 1 m in front of it (z = 7) to 1 m behind it (z = −1), across the lot (x −20…20). + const [wall] = breaksOf(after) + expect(breaksOf(after)).toHaveLength(1) + expect(wall?.line[0]).toEqual(wall?.line.at(-1)) + expect(new Set(wall?.line.map(([x]) => x)).size).toBe(2) + expect(new Set(wall?.line.map(([, z]) => z))).toEqual(new Set([-1, 7])) + expect(outcome.result.wall).toMatchObject({ exact: true, lengthM: 2 * (40 + 8) }) + expect(outcome.result.wall).not.toHaveProperty('levelledHouseSide') + expect(outcome.result.edge).toMatchObject({ padStripM: { fromM: -7, toM: 1 } }) + // Level inside the strip across the lot; beyond it the ground is the lot's own. + expect(groundAt(after, 15, 3)).toBeCloseTo(0, 2) + expect(groundAt(after, -15, 3)).toBeCloseTo(0, 2) + expect(groundAt(after, 15, 15)).toBeCloseTo(4.5, 1) + expect(groundAt(after, 0, -2.5)).toBeGreaterThan(1) + }) + + test('a lot that falls to the street keeps its fall in front of the strip, with no step at the property line', () => { + const toTheStreet = (_x: number, z: number) => (z > 6 ? -(z - 6) / 7 : Math.max(0, -z) * 0.5) + const base = lot(toTheStreet, [], STREET_AT_PLUS_Z) + const { after } = grade(base, { + scope: 'lot', + run: 2, + marginM: 1, + wallM: 1, + exactWall: true, + edge: { facing: 'rear' }, + }) + // Level to the strip's front (z = 7); beyond it, and at the property line (z = 20), the ground is the lot's own fall. + expect(groundAt(after, 0, 5)).toBeCloseTo(0, 2) + for (const z of [10, 15, 19.5, 20]) + expect(groundAt(after, 0, z)).toBeCloseTo(toTheStreet(0, z), 1) + expect(groundAt(after, 15, 20)).toBeCloseTo(toTheStreet(15, 20), 1) + }) + + test('a lot whose strip is not convex refuses an exact wall, and a lattice wall still grades', () => { + // A lot with its front right corner cut away (x > 5, z > 2): the strip across z −1…7 has a reflex corner at (5, 2). + const notched = { + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [20, -20], + [20, 2], + [5, 2], + [5, 20], + [-20, 20], + ], + }, + } + const input = { + footprint: [ + [-5, 0], + [4, 0], + [4, 6], + [-5, 6], + ], + padHeightM: 0, + scope: 'lot', + marginM: 1, + wallM: 1, + edge: { facing: 'rear' }, + } + const lotWithNotch = lot(risingBehind(1), [], { ...STREET_AT_PLUS_Z, ...notched }) + expect( + refusalCode(() => + gradeAroundHouse(lotWithNotch, { ...input, exactWall: true } as never, context), + ), + ).toBe('unsupported_geometry') + expect( + refusalCode(() => gradeAroundHouse(lotWithNotch, input as never, context)), + ).toBeUndefined() + }) + + test.each([ + ['needs wallM', { exactWall: true }, 'invalid_input'], + [ + 'takes one pad', + { + pads: [ + { footprint: HOUSE, padHeightM: 0 }, + { + footprint: [ + [8, 0], + [12, 0], + [12, 4], + [8, 4], + ], + padHeightM: 0, + }, + ], + wallM: 1, + exactWall: true, + }, + 'invalid_input', + ], + [ + 'leaves the property', + { + footprint: [ + [14, 0], + [19.5, 0], + [19.5, 6], + [14, 6], + ], + scope: 'lot', + wallM: 1, + exactWall: true, + }, + 'outside_property', + ], + ])('%s', (_name, input, code) => { + expect( + refusalCode(() => + gradeAroundHouse( + lot(risingBehind(1)), + { footprint: HOUSE, padHeightM: 0, scope: 'context', ...input } as never, + context, + ), + ), + ).toBe(code) + }) + + test('refuses where it would meet another break', () => { + const across = AGENT_OPERATIONS.add_terrain_break!( + lot(risingBehind(1)), + { + line: [ + [-20, 3], + [20, 3], + ], + kind: 'retaining', + left: 'ground', + right: 2, + }, + context, + ) + expect( + refusalCode(() => + gradeAroundHouse( + applied(lot(risingBehind(1)), across), + { footprint: HOUSE, padHeightM: 0, scope: 'context', wallM: 1, exactWall: true }, + context, + ), + ), + ).toBe('crossing_breaks') + }) +}) + +describe('grade_around_house: one pad per level', () => { + const street: Point[] = [ + [-5, 0], + [5, 0], + [5, 6], + [-5, 6], + ] + const lower: Point[] = [ + [-5, -6], + [5, -6], + [5, 0], + [-5, 0], + ] + const pads = [ + { footprint: street, padHeightM: 0 }, + { footprint: lower, padHeightM: -1.45, marginM: 2 }, + ] + const twoFloors = () => lot(() => -1.45) + + test('each pad has its height and its margin, and abutting pads meet in a step along their shared edge', () => { + const { after, outcome } = grade(twoFloors(), { + pads, + footprint: undefined, + padHeightM: undefined, + marginM: 1, + }) + expect(groundAt(after, 0, 0.5)).toBeCloseTo(0, 2) + expect(groundAt(after, 0, -0.5)).toBeCloseTo(-1.45, 2) + // Beside the street pad (margin 1) the batter falls from 0 at x = 6; beside the lower pad (margin 2) it is level to x = 7. + expect(groundAt(after, 6.5, 3)).toBeCloseTo(-0.25, 1) + expect(groundAt(after, 6.5, -3)).toBeCloseTo(-1.45, 2) + expect(outcome.result.pads).toMatchObject([ + { padHeightM: 0, marginM: 1 }, + { padHeightM: -1.45, marginM: 2 }, + ]) + expect(outcome.result.levelId).toBeUndefined() + }) + + test('each pad batters to the ground on its own', () => { + const { after } = grade( + lot(() => -3), + { pads, footprint: undefined, padHeightM: undefined, run: 2 }, + ) + // 2 m past each pad's edge the fall is 1 m: from the street pad's 0 in front, from the lower pad's −1.45 behind it. + expect(groundAt(after, 0, 9)).toBeCloseTo(-1, 1) + expect(groundAt(after, 0, -10)).toBeCloseTo(-2.45, 1) + }) + + test.each([ + ['a top-level level with pads', { levelId: 'level_x' }], + ['a pad with neither level nor footprint', { pads: [{ padHeightM: 0 }] }], + ['the same level twice', { pads: [{ levelId: 'level_x' }, { levelId: 'level_x' }] }], + ['an edge with several pads', { pads, edge: { facing: 'rear' } }], + ])('%s is refused', (_name, input) => { + expect( + refusalCode(() => + gradeAroundHouse(twoFloors(), { pads, scope: 'context', ...input } as never, context), + ), + ).toBe('invalid_input') + }) +}) + +describe('grade_around_house: the section of a lot with a rear lawn, from one call', () => { + // A 8 m deep house whose street is at +z. Behind it: 2.1 m of level yard, a 1.3 m retaining wall, a bank at 1:1.5 and a flat lawn 2.95 m up. + const REAR_LAWN = { + footprint: [ + [-5, 0], + [5, 0], + [5, 8], + [-5, 8], + ], + padHeightM: 0, + scope: 'lot', + edge: { facing: 'rear' }, + marginM: 2.1, + run: 1.5, + wallM: 1.3, + upperLevelM: 2.95, + exactWall: true, + } + + test.each([ + ['a hillside', risingBehind(0.25)], + ['level ground', () => 0], + ])('on %s it makes the wall, the 33.7 degree bank and the lawn', (_name, natural) => { + const { after, outcome } = grade(lot(natural, [], STREET_AT_PLUS_Z), REAR_LAWN) + const behind = (z: number) => groundAt(after, 0, z) + expect(behind(0.5)).toBeCloseTo(0, 2) + expect(behind(-2.0)).toBeCloseTo(0, 2) + // The wall stands at z = −2.1 (2.1 m behind the rear wall) and is 1.3 m high; the bank then climbs 1.65 m over 2.475 m. + expect(behind(-2.2)).toBeCloseTo(1.3 + 0.1 / 1.5, 1) + expect(behind(-4)).toBeCloseTo(1.3 + 1.9 / 1.5, 1) + expect(behind(-4.7)).toBeCloseTo(2.95, 1) + expect(behind(-18)).toBeCloseTo(2.95, 2) + for (const x of [-15, 15]) expect(groundAt(after, x, -3)).toBeCloseTo(behind(-3), 2) + expect(outcome.result.batterSlopeDeg as number).toBeCloseTo(33.69, 1) + expect(outcome.result.steepestSampledSlopeDeg as number).toBeLessThan(35) + expect(outcome.result.lawn).toMatchObject({ levelM: 2.95 }) + expect(breaksOf(after)).toHaveLength(1) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-grade.ts b/packages/core/src/agent-operations/terrain-grade.ts new file mode 100644 index 0000000000..8913d24c06 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-grade.ts @@ -0,0 +1,729 @@ +import { heightAt, quantize, type TerrainField } from '../lib/terrain-field' +import { distance2D, pointInPolygon, type Vec2 } from './plan-geometry' + +/** + * Ground as a function of the distance to a house: a pad at the house's height as far as `marginM` from + * its outline, then a batter, 1 metre of height for every `run` metres, to the ground that was there (the + * daylight line) or to a stated lawn level. Distance is Euclidean to the outline, so the batter's contours + * are the outline's offsets, rounded at convex corners and straight along walls: a curved house gets a + * curved slope with no further rule. + * + * Several pads (one per level of a split-level house) each have their own height and margin; a sample + * follows the pad whose outline is nearest. A band replaces the ring by a straight edge: the outline + * extended across the lot along that edge, so the wall and bank run its whole width. + */ +export type GradePad = { + /** The house outline of this pad in the site frame. */ + outline: Vec2[] + /** Height of the pad, metres above datum. */ + heightM: number + /** The pad reaches this far beyond its outline. */ + marginM: number + /** + * The pad and its batter only cut: ground that already lies under them is left as it is. The + * high side of a house whose low side walks out: the hill is cut back where it stands over the + * floor and keeps its own slope where it does not. + */ + cutOnly?: boolean +} + +/** The strip a band grades: the outline's extent along `normal`, unbounded across it. */ +export type GradeBand = { + /** Unit vector pointing from the house toward the edge. */ + normal: Vec2 + /** The strip's front: the outline's least distance along `normal`. */ + frontM: number + /** The strip's edge: the line the wall and bank stand beyond, along `normal`. */ + edgeM: number +} + +export type GradeSettings = { + pads: GradePad[] + /** Grade across the lot along one edge instead of around the outline; takes exactly one pad. */ + band?: GradeBand + /** Horizontal metres per metre of height in the batter (2 is 1:2). */ + run: number + /** The batter is looked for this far beyond the pad; the ground beyond is not touched (a lawn aside). */ + reachM: number + /** Terraces: the batter in steps of this riser, each tread `run` times as wide as the riser is tall. */ + riserM?: number + /** A retaining wall: the ground beyond the pad edge starts this much above (or below) the pad. */ + wallM?: number + /** After the bank, a flat lawn at this level: the ground is raised or cut to it. */ + upperLevelM?: number + /** The lawn holds out to the edge of the written region; false stops it at `reachM`. */ + lawnToEdge?: boolean + /** The wall is an exact terrain break: the pad side is its numeric plane. Its face is not read from the tiles. */ + exactWall?: boolean + /** + * The pad falls away from the outline by this many metres per metre, out to its margin: water + * leaves the walls, and under a rising bank the pad's edge is the low line that carries it round. + * The batter and the wall start from the pad's edge height. Default 0, a level pad. + */ + padFallPerM?: number + /** The rectangle the batter may write in; default each pad's outline out to its margin and `reachM`. */ + region?: { minX: number; minZ: number; maxX: number; maxZ: number } + /** + * The first pad's high side is held, not battered back: ground that stands over the pad stays + * against a face `atM` beyond the outline, as high as `heightM` over the pad; above that it is + * cut back at the batter. Ground under the pad is filled to it as without. One pad, no band. + */ + retain?: GradeRetain + /** A low line between the first pad and the ground that rises beyond it. One pad, no band. */ + lowLine?: GradeLowLine +} + +export type GradeRetain = { atM: number; heightM: number } + +/** + * The line water follows round the high side of a pad instead of running to the walls: a level + * bottom `widthM` wide (a lattice cell and a half: it survives sampling) that falls along its + * length from its summit to where it comes out on lower ground. Beside a pad it starts at the + * pad's edge and the pad falls to it; before held ground it stands `offM` beyond the face, + * `depthM` under the ground that is there, and the ground between falls to it. + */ +export type GradeLowLine = { + widthM: number + /** Fall along the line, metres per metre. */ + fallPerM: number + /** Beside a pad: how far under the pad's edge the line's summit stands. */ + underPadM: number + /** Held ground only: the line's near edge from the face, its depth under the ground, the fall of the ground from the face to it. */ + offM: number + depthM: number + faceFallPerM: number + /** How far past the last ground that rises the line is carried down to find lower ground. */ + daylightM: number +} + +export type LowLineFacts = { + lengthM: number + /** Its highest and lowest bottom, metres above datum. */ + summitM: number + lowestM: number + /** The deepest it stands under the ground that was there. */ + deepestCutM: number + /** Ends that came out on lower ground, and ends that did not within `daylightM`. */ + outlets: number + blindEnds: number + /** The ground rises on every side: the line is a ring with nowhere to run to. */ + closed: boolean +} + +export type GradeOutcome = { + heights: Int16Array + changedSamples: number + cutVolumeM3: number + fillVolumeM3: number + padAreaM2: number + /** Per pad, the area of the ground it levelled. */ + padAreasM2: number[] + /** The farthest a changed sample lies from the pad edge. */ + farthestChangeM: number + /** Samples the batter would have changed beyond the property, which were left as they were. */ + outsideLotSamples: number + /** The most one of them would have moved: the step the ground makes at the property line. */ + outsideLotMaxM: number + /** The ground a lawn holds at its level, inside the property. */ + lawnAreaM2: number + steepestSlopeDeg: number + lowLine?: LowLineFacts +} + +const EPS_M = 0.005 + +function distanceToSegment(point: Vec2, from: Vec2, to: Vec2): number { + const dx = to[0] - from[0] + const dz = to[1] - from[1] + const lengthSq = dx * dx + dz * dz + const t = + lengthSq === 0 + ? 0 + : Math.max(0, Math.min(1, ((point[0] - from[0]) * dx + (point[1] - from[1]) * dz) / lengthSq)) + return distance2D(point, [from[0] + dx * t, from[1] + dz * t]) +} + +/** Signed Euclidean distance to the outline: negative inside. */ +export function outlineDistance(point: Vec2, outline: Vec2[]): number { + let nearest = Number.POSITIVE_INFINITY + for (let i = 0; i < outline.length; i++) { + const to = outline[(i + 1) % outline.length] as Vec2 + nearest = Math.min(nearest, distanceToSegment(point, outline[i] as Vec2, to)) + } + return pointInPolygon(point, outline, true) ? -nearest : nearest +} + +/** How far the batter has risen (or fallen) `u` metres from the pad edge. */ +export function batterRise(u: number, run: number, riserM?: number): number { + if (!riserM) return u / run + return riserM * Math.floor(u / (run * riserM) + 1e-9) +} + +/** The horizontal run of a bank that climbs `heightM`: where `batterRise` first reaches it. */ +export function bankRunM(heightM: number, run: number, riserM?: number): number { + if (heightM <= 0) return 0 + return riserM ? Math.ceil(heightM / riserM - 1e-9) * run * riserM : heightM * run +} + +/** The convex hull of a set of points, counter-clockwise in the site frame (shoelace area positive). */ +export function convexHull(points: Vec2[]): Vec2[] { + const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]) + const cross = (o: Vec2, a: Vec2, b: Vec2) => + (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) + const half = (list: Vec2[]) => { + const chain: Vec2[] = [] + for (const p of list) { + while ( + chain.length >= 2 && + cross(chain[chain.length - 2] as Vec2, chain[chain.length - 1] as Vec2, p) <= 0 + ) + chain.pop() + chain.push(p) + } + chain.pop() + return chain + } + return [...half(sorted), ...half([...sorted].reverse())] +} + +const LOW_STATION_M = 0.25 +/** The most corners and stations an outline may have for a low line to be solved round it. */ +export const MAX_LOW_LINE_CORNERS = 256 +const MAX_LOW_LINE_STATIONS = 4000 +/** The most stations a line is carried along the house past the end of a stretch. */ +const MAX_CARRY_STEPS = 64 + +type LowLine = { + /** Per edge of the outline: its first station and how many it holds. */ + edges: { first: number; count: number }[] + /** The bottom of the line at each station round the outline; NaN where there is none. */ + bottoms: Float64Array + /** Stations where an earlier seating's line lies: the ground there is left as it is. */ + kept: boolean[] + /** Where a stretch ends the line leaves the house and runs down the ground to come out. */ + tails: LowTail[] + /** Absent when every stretch was already there. */ + facts: LowLineFacts | undefined +} + +/** A straight run from `from` along the unit `way`, `lengthM` long, its bottom `fromM` falling `fallPerM`. */ +type LowTail = { from: Vec2; way: Vec2; lengthM: number; fromM: number; fallPerM: number } + +/** The nearest point of an outline: how far (negative inside), on which edge, how far along it (0..1). */ +function nearestOnOutline(point: Vec2, outline: Vec2[]) { + let distance = Number.POSITIVE_INFINITY + let edge = 0 + let along = 0 + for (let i = 0; i < outline.length; i++) { + const from = outline[i] as Vec2 + const to = outline[(i + 1) % outline.length] as Vec2 + const dx = to[0] - from[0] + const dz = to[1] - from[1] + const lengthSq = dx * dx + dz * dz + const t = + lengthSq === 0 + ? 0 + : Math.max( + 0, + Math.min(1, ((point[0] - from[0]) * dx + (point[1] - from[1]) * dz) / lengthSq), + ) + const d = Math.hypot(point[0] - from[0] - dx * t, point[1] - from[1] - dz * t) + if (d < distance) { + distance = d + edge = i + along = t + } + } + return { distance: pointInPolygon(point, outline, true) ? -distance : distance, edge, along } +} + +/** + * The low line round a pad's high side. Stations stand every quarter metre round the outline; + * each reads the ground on the line's centre. Where that ground rises over the pad the line + * exists: at the pad's edge height beside a pad, `depthM` under the ground before held ground. + * Each stretch then falls from its summit both ways and is carried on down past its ends until + * the ground is lower than it. + */ +function solveLowLine( + pad: GradePad, + low: GradeLowLine, + padFallPerM: number, + retain: GradeRetain | undefined, + ground: (point: Vec2, distance: number) => number, +): LowLine | undefined { + const outline = pad.outline + const count = outline.length + // The line is solved station by station round the outline: an outline of more corners or more + // stations than a house has is not walked. + if (count < 3 || count > MAX_LOW_LINE_CORNERS) return undefined + let perimeter = 0 + for (let i = 0; i < count; i++) { + const from = outline[i] as Vec2 + const to = outline[(i + 1) % count] as Vec2 + perimeter += Math.max(LOW_STATION_M, Math.hypot(to[0] - from[0], to[1] - from[1])) + } + if (perimeter / LOW_STATION_M > MAX_LOW_LINE_STATIONS) return undefined + const signed = outline.reduce((sum, a, i) => { + const b = outline[(i + 1) % count] as Vec2 + return sum + a[0] * b[1] - b[0] * a[1] + }, 0) + const turn = signed >= 0 ? 1 : -1 + const normalOf = (i: number): Vec2 => { + const from = outline[i] as Vec2 + const to = outline[(i + 1) % count] as Vec2 + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) || 1 + return [(turn * (to[1] - from[1])) / length, (-turn * (to[0] - from[0])) / length] + } + const padEdgeM = pad.heightM - padFallPerM * pad.marginM + const nearM = retain ? retain.atM + low.offM : pad.marginM + const centreM = nearM + low.widthM / 2 + const edges: LowLine['edges'] = [] + const natural: number[] = [] + const spacing: number[] = [] + const centres: Vec2[] = [] + const normals: Vec2[] = [] + const tails: LowTail[] = [] + const beyond: number[] = [] + const kept: boolean[] = [] + for (let i = 0; i < count; i++) { + const from = outline[i] as Vec2 + const to = outline[(i + 1) % count] as Vec2 + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + const stations = Math.max(1, Math.ceil(length / LOW_STATION_M)) + edges.push({ first: natural.length, count: stations }) + const normal = normalOf(i) + const before = normalOf((i + count - 1) % count) + for (let k = 0; k < stations; k++) { + // The corner station looks out along the bisector of the two walls that meet there. + let [nx, nz] = normal + if (k === 0) { + const bx = normal[0] + before[0] + const bz = normal[1] + before[1] + const b = Math.hypot(bx, bz) + if (b > 1e-6) [nx, nz] = [bx / b, bz / b] + } + const x = from[0] + ((to[0] - from[0]) * k) / stations + nx * centreM + const z = from[1] + ((to[1] - from[1]) * k) / stations + nz * centreM + const here = ground([x, z], centreM) + natural.push(here) + spacing.push(length / stations) + centres.push([x, z]) + normals.push([nx, nz]) + // A line an earlier seating left: the ground on the centre lower than on both sides of it + // (and, beside a pad, no higher than this pad would put it). It is kept as it lies. + const side = (distance: number) => + ground([x + nx * (distance - centreM), z + nz * (distance - centreM)], distance) + // Past the lattice cell at the face, where the tiles under a face's plane still show. + const inner = side(retain ? retain.atM + 0.55 : nearM - 0.3) + const outer = side(nearM + low.widthM + 1.5) + beyond.push(outer) + kept.push( + here < outer - 0.1 && + here < inner - 0.005 && + (retain !== undefined || here <= padEdgeM - low.underPadM + 0.015), + ) + } + } + const total = natural.length + // A gap of a station or three in a line that is there (a corner the lattice reads badly) is the line too. + for (let index = 0; index < total; index++) { + if (kept[index] || !kept[(index + total - 1) % total]) continue + let gap = 1 + while (gap <= 3 && !kept[(index + gap) % total]) gap++ + if (gap <= 3) for (let k = 0; k < gap; k++) kept[(index + k) % total] = true + } + // Where the line is wanted, and the height it starts from before it is made to fall. + const start = natural.map((height, index) => + kept[index] + ? Number.NaN + : retain + ? height > pad.heightM + 0.05 + ? Math.min( + height - low.depthM, + // Under ground cut back to what the face holds, the line is the foot of that cut. + pad.heightM + retain.heightM - low.faceFallPerM * low.offM, + ) + : Number.NaN + : // Beside a pad: wherever the ground on the line, or past it, stands over the pad's edge. + Math.max(height, beyond[index] as number) > padEdgeM + 0.03 + ? padEdgeM - low.underPadM + : Number.NaN, + ) + const wanted = start.map((height) => !Number.isNaN(height)) + if (!wanted.some(Boolean) && !kept.some(Boolean)) return undefined + const bottoms = new Float64Array(total).fill(Number.NaN) + const facts: LowLineFacts = { + lengthM: 0, + summitM: Number.NEGATIVE_INFINITY, + lowestM: Number.POSITIVE_INFINITY, + deepestCutM: 0, + outlets: 0, + blindEnds: 0, + closed: wanted.every(Boolean), + } + if (!wanted.some(Boolean)) return { edges, bottoms, kept, tails, facts: undefined } + const lower = (index: number, height: number) => { + const held = bottoms[index] as number + bottoms[index] = Number.isNaN(held) ? height : Math.min(held, height) + } + if (facts.closed) for (let index = 0; index < total; index++) lower(index, start[index] as number) + else { + // Each stretch of stations that want the line, the first after one that does not. + for (let first = 0; first < total; first++) { + if (!wanted[first] || wanted[(first + total - 1) % total]) continue + let length = 1 + while (wanted[(first + length) % total]) length++ + const at = (k: number) => (first + k + total) % total + // The summit: the highest start, the middle of the stations that share it. + let top = Number.NEGATIVE_INFINITY + for (let k = 0; k < length; k++) top = Math.max(top, start[at(k)] as number) + const tops: number[] = [] + for (let k = 0; k < length; k++) if ((start[at(k)] as number) > top - 0.005) tops.push(k) + const summit = tops[Math.floor(tops.length / 2)] as number + lower(at(summit), start[at(summit)] as number) + for (const way of [1, -1] as const) { + let height = start[at(summit)] as number + let k = summit + // Down the stretch: never above its start, never flatter than the fall. + for (;;) { + const next = k + way + if (next < 0 || next >= length) break + height = Math.min( + start[at(next)] as number, + height - low.fallPerM * (spacing[at(way === 1 ? k : next)] as number), + ) + lower(at(next), height) + k = next + } + // Past its end the line is carried on along the house while the ground there still runs + // back to it, and leaves the house where the ground falls away: straight down the ground, + // falling as it goes, until the ground is lower than it. + let carried = 0 + let out = false + for (let step = 0; step < Math.min(total, MAX_CARRY_STEPS); step++) { + const index = at(k + way * step) + const from = centres[index] as Vec2 + const slopeX = + (ground([from[0] + 1, from[1]], centreM) - ground([from[0] - 1, from[1]], centreM)) / 2 + const slopeZ = + (ground([from[0], from[1] + 1], centreM) - ground([from[0], from[1] - 1], centreM)) / 2 + const slope = Math.hypot(slopeX, slopeZ) + const downhill: Vec2 = slope > 1e-6 ? [-slopeX / slope, -slopeZ / slope] : [0, 0] + const outward = normals[index] as Vec2 + if (slope > 0.005 && downhill[0] * outward[0] + downhill[1] * outward[1] >= 0) { + for (let run = LOW_STATION_M; run <= low.daylightM - carried; run += LOW_STATION_M) { + const there: Vec2 = [from[0] + downhill[0] * run, from[1] + downhill[1] * run] + if (ground(there, centreM) > height - low.fallPerM * run + 0.01) continue + out = true + tails.push({ + from, + way: downhill, + lengthM: run, + fromM: height, + fallPerM: low.fallPerM, + }) + facts.lengthM += run + facts.lowestM = Math.min(facts.lowestM, height - low.fallPerM * run) + break + } + break + } + const next = at(k + way * (step + 1)) + // It meets the line an earlier seating left: that line is its way out. + if (kept[next]) { + out = true + break + } + const run = spacing[way === 1 ? index : next] as number + carried += run + height -= low.fallPerM * run + if ((natural[next] as number) <= height + 0.01) { + out = true + break + } + if (carried > low.daylightM || wanted[next]) break + lower(next, height) + } + if (out) facts.outlets++ + else facts.blindEnds++ + } + } + } + for (let index = 0; index < total; index++) { + const bottom = bottoms[index] as number + if (Number.isNaN(bottom)) continue + facts.lengthM += spacing[index] as number + facts.summitM = Math.max(facts.summitM, bottom) + facts.lowestM = Math.min(facts.lowestM, bottom) + facts.deepestCutM = Math.max(facts.deepestCutM, (natural[index] as number) - bottom) + } + return { edges, bottoms, kept, tails, facts } +} + +/** The line's bottom abreast of a point of the outline, between its two stations there. */ +function lowLineBottom(line: LowLine, edge: number, along: number): number { + const { first, count } = line.edges[edge] as LowLine['edges'][number] + const u = Math.max(0, Math.min(1, along)) * count + const k = Math.min(count - 1, Math.floor(u)) + const a = line.bottoms[first + k] as number + const b = line.bottoms[(first + k + 1) % line.bottoms.length] as number + if (Number.isNaN(a)) return b + if (Number.isNaN(b)) return a + return a + (b - a) * (u - k) +} + +/** Whether the line an earlier seating left runs abreast of a point of the outline. */ +function lowLineKept(line: LowLine, edge: number, along: number): boolean { + const { first, count } = line.edges[edge] as LowLine['edges'][number] + const k = Math.min(count - 1, Math.floor(Math.max(0, Math.min(1, along)) * count)) + return ( + (line.kept[first + k] as boolean) || (line.kept[(first + k + 1) % line.kept.length] as boolean) + ) +} + +type Governing = { + pad: number + /** Distance beyond the pad edge (negative inside the pad). */ + u: number + /** The sample lies beyond the band's edge, not before its front. */ + onEdgeSide: boolean +} + +/** + * The ground the pads, batter, wall and lawn make over `field`. `inside` keeps the write on the property: a + * sample outside it is left as it was, and counted when the rule would have moved it. + */ +export function gradeGround( + field: TerrainField, + settings: GradeSettings, + inside: (point: Vec2) => boolean = () => true, +): GradeOutcome { + const { + pads, + band, + run, + reachM, + riserM = 0, + wallM = 0, + upperLevelM, + exactWall = false, + } = settings + const lawnToEdge = settings.lawnToEdge ?? false + const padFallPerM = settings.padFallPerM ?? 0 + const riser = riserM || undefined + const governing = (point: Vec2): Governing => { + if (band) { + const pad = pads[0] as GradePad + const along = point[0] * band.normal[0] + point[1] * band.normal[1] + const rear = along - band.edgeM - pad.marginM + const front = band.frontM - along - pad.marginM + return { + pad: 0, + u: Math.max(rear, front), + onEdgeSide: rear >= front, + } + } + let inZone: Governing | undefined + let inZoneD = Number.POSITIVE_INFINITY + let nearest: Governing | undefined + pads.forEach((pad, index) => { + const distance = outlineDistance(point, pad.outline) + const u = distance - pad.marginM + if (u <= 0 && distance < inZoneD) { + inZoneD = distance + inZone = { pad: index, u, onEdgeSide: true } + } + if (!nearest || u < nearest.u) nearest = { pad: index, u, onEdgeSide: true } + }) + return (inZone ?? nearest) as Governing + } + const span = Math.max(...pads.map((pad) => pad.marginM)) + reachM + field.spacing + const region = settings.region ?? { + minX: Math.min(...pads.flatMap((pad) => pad.outline.map((p) => p[0]))) - span, + minZ: Math.min(...pads.flatMap((pad) => pad.outline.map((p) => p[1]))) - span, + maxX: Math.max(...pads.flatMap((pad) => pad.outline.map((p) => p[0]))) + span, + maxZ: Math.max(...pads.flatMap((pad) => pad.outline.map((p) => p[1]))) + span, + } + const col0 = Math.max(0, Math.floor((region.minX - field.origin[0]) / field.spacing)) + const col1 = Math.min(field.cols - 1, Math.ceil((region.maxX - field.origin[0]) / field.spacing)) + const row0 = Math.max(0, Math.floor((region.minZ - field.origin[1]) / field.spacing)) + const row1 = Math.min(field.rows - 1, Math.ceil((region.maxZ - field.origin[1]) / field.spacing)) + const heights = new Int16Array(field.heights) + const reached = new Float32Array(field.heights.length).fill(Number.NaN) + const cell = field.spacing * field.spacing + const padSamples = pads.map(() => 0) + const first = pads[0] as GradePad + const retain = band ? undefined : settings.retain + /** Ground the first pad's face holds: as it was, cut back only over what the face can hold. */ + const low = settings.lowLine + // Over the face the cut starts past the low line, so the line is its foot and not the face's top. + const heldFromM = retain ? retain.atM + (low && !band ? low.offM + low.widthM : 0) : 0 + const held = (beforeM: number, distance: number) => + retain + ? Math.min( + beforeM, + first.heightM + + retain.heightM + + batterRise(Math.max(0, distance - heldFromM), run, riser), + ) + : beforeM + const line = + low && !band + ? solveLowLine(first, low, padFallPerM, retain, (point, distance) => + held(heightAt(field, point[0], point[1]), distance), + ) + : undefined + /** The most the ground may stand at a point beside the first pad for the low line to run there. */ + const lowLineCap = (point: Vec2): number => { + if (!line || !low) return Number.POSITIVE_INFINITY + const { distance, edge, along } = nearestOnOutline(point, first.outline) + const near = retain ? retain.atM + low.offM : first.marginM + // The pad itself, and an areaway before a face, are as they were made. + if (distance <= (retain ? retain.atM : near)) return Number.POSITIVE_INFINITY + let cap = Number.POSITIVE_INFINITY + const bottom = lowLineBottom(line, edge, along) + if (!Number.isNaN(bottom)) + cap = + distance < near + ? bottom + (near - distance) * low.faceFallPerM + : distance <= near + low.widthM + ? bottom + : bottom + batterRise(distance - near - low.widthM, run, riser) + for (const tail of line.tails) { + const dx = point[0] - tail.from[0] + const dz = point[1] - tail.from[1] + const along = dx * tail.way[0] + dz * tail.way[1] + if (along < 0 || along > tail.lengthM) continue + const beside = Math.abs(dx * tail.way[1] - dz * tail.way[0]) - low.widthM / 2 + cap = Math.min( + cap, + tail.fromM - tail.fallPerM * along + (beside > 0 ? batterRise(beside, run, riser) : 0), + ) + } + return cap + } + let changedSamples = 0 + let cutVolumeM3 = 0 + let fillVolumeM3 = 0 + let farthestChangeM = 0 + let outsideLotSamples = 0 + let outsideLotMaxM = 0 + let lawnSamples = 0 + const changed: number[] = [] + for (let row = row0; row <= row1; row++) { + for (let col = col0; col <= col1; col++) { + const index = row * field.cols + col + const point: Vec2 = [ + field.origin[0] + col * field.spacing, + field.origin[1] + row * field.spacing, + ] + const { pad: padIndex, u, onEdgeSide } = governing(point) + const lawn = upperLevelM !== undefined && onEdgeSide + if (u > reachM && !(lawn && lawnToEdge)) continue + reached[index] = u + const pad = pads[padIndex] as GradePad + // The pad's height at its edge, where the batter and the wall start. + const padHeightM = pad.heightM - padFallPerM * pad.marginM + const beforeQ = field.heights[index] ?? 0 + const beforeM = beforeQ * field.step + const rise = () => batterRise(u, run, riser) + let target = beforeM + // Beside a pad that holds its high side: ground over the pad's own surface stays, held. + const distance = u + pad.marginM + const surfaceM = + u <= 0 ? pad.heightM - padFallPerM * Math.max(0, distance) : padHeightM - rise() + if (retain && padIndex === 0 && distance > 0 && beforeM > surfaceM + EPS_M) + target = distance <= retain.atM ? pad.heightM : held(beforeM, distance) + else if (u <= 0) target = pad.heightM - padFallPerM * Math.max(0, u + pad.marginM) + else if (lawn) + target = + upperLevelM >= padHeightM + ? Math.min(upperLevelM, padHeightM + wallM + rise()) + : Math.max(upperLevelM, padHeightM - wallM - rise()) + else if (beforeM > padHeightM + EPS_M) target = Math.min(beforeM, padHeightM + wallM + rise()) + else if (beforeM < padHeightM - EPS_M) target = Math.max(beforeM, padHeightM - wallM - rise()) + if (pad.cutOnly && target > beforeM) target = beforeM + if (line && low && padIndex === 0) { + target = Math.min(target, lowLineCap(point)) + // A line already there is not filled back in. + const near = retain ? retain.atM + low.offM : pad.marginM + if (target > beforeM && distance > near - 0.01 && distance < near + low.widthM + 2) { + const { edge, along } = nearestOnOutline(point, first.outline) + if (lowLineKept(line, edge, along)) target = beforeM + } + } + const nextQ = quantize(field, target) + const here = inside(point) + if (here && u <= 0) padSamples[padIndex] = (padSamples[padIndex] ?? 0) + 1 + if (nextQ === beforeQ) { + if (here && lawn && u > 0 && nextQ === quantize(field, upperLevelM)) lawnSamples++ + continue + } + if (!here) { + outsideLotSamples++ + outsideLotMaxM = Math.max(outsideLotMaxM, Math.abs(nextQ - beforeQ) * field.step) + continue + } + heights[index] = nextQ + changedSamples++ + changed.push(index) + if (lawn && u > 0 && nextQ === quantize(field, upperLevelM)) lawnSamples++ + if (u > 0) farthestChangeM = Math.max(farthestChangeM, u) + const movedM = (nextQ - beforeQ) * field.step + if (movedM < 0) cutVolumeM3 += -movedM * cell + else fillVolumeM3 += movedM * cell + } + } + return { + heights, + changedSamples, + cutVolumeM3, + fillVolumeM3, + padAreaM2: padSamples.reduce((sum, count) => sum + count, 0) * cell, + padAreasM2: padSamples.map((count) => count * cell), + farthestChangeM, + outsideLotSamples, + outsideLotMaxM, + lawnAreaM2: lawnSamples * cell, + steepestSlopeDeg: steepestSlope(field, heights, changed, exactWall ? reached : undefined), + ...(line?.facts ? { lowLine: line.facts } : {}), + } +} + +/** + * The steepest central-difference slope, in degrees, over the changed samples and their neighbours. With an + * exact wall the face between the pad and the bank is not ground the tiles describe: samples within a cell + * of the pad edge are left out. + */ +function steepestSlope( + field: TerrainField, + heights: Int16Array, + changed: number[], + reached?: Float32Array, +): number { + const clamp = (col: number, row: number) => + Math.max(0, Math.min(field.rows - 1, row)) * field.cols + + Math.max(0, Math.min(field.cols - 1, col)) + const at = (col: number, row: number) => (heights[clamp(col, row)] ?? 0) * field.step + const nearPadEdge = (col: number, row: number) => + [ + [0, 0], + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ].some(([dc, dr]) => { + const u = reached?.[clamp(col + (dc as number), row + (dr as number))] + return u === undefined || Number.isNaN(u) || u <= 0 + }) + let steepest = 0 + for (const index of changed) { + const col = index % field.cols + const row = Math.floor(index / field.cols) + if (reached && nearPadEdge(col, row)) continue + const dhdx = (at(col + 1, row) - at(col - 1, row)) / (2 * field.spacing) + const dhdz = (at(col, row + 1) - at(col, row - 1)) / (2 * field.spacing) + steepest = Math.max(steepest, Math.atan(Math.hypot(dhdx, dhdz))) + } + return (steepest * 180) / Math.PI +} diff --git a/packages/core/src/agent-operations/terrain-seated-ground.test.ts b/packages/core/src/agent-operations/terrain-seated-ground.test.ts new file mode 100644 index 0000000000..4f33897a7c --- /dev/null +++ b/packages/core/src/agent-operations/terrain-seated-ground.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, test } from 'bun:test' +import { levelBaseElevationAt } from '../lib/terrain-support-query' +import type { AnyNode, StairNode } from '../schema' +import { levelPlaneWorldY } from '../services/storey' +import { stairBaseElevation } from '../systems/stair/stair-base-elevation' +import { GROUNDS, groundAt, runTool, slopedLot } from './__fixtures__/sloped-lots' + +/* + * A house seated on a slope (set_ground_level moves the building in height) is still carried by the + * ground: what stands outside its slab on the ground level (outside steps, a fence, a post) reads + * the terrain, as it does while the building stands at y = 0. + */ + +type Nodes = Record + +/** Outside steps with their foot 4 m in front of the house; the gap between that foot and the ground. */ +function stepsFootGap(nodes: Nodes): number { + const after = runTool(nodes, 'add_steps', { x: 0, z: 8, rise: 0.5, rotation: 180 }).nodes + const stair = Object.values(after).find((node): node is StairNode => node.type === 'stair') + if (!stair) throw new Error('no steps') + const plane = levelPlaneWorldY(after, 'level_ground') ?? 0 + const building = after.building_house as AnyNode & { position: [number, number, number] } + const foot = plane + stairBaseElevation(stair, after, 'level_ground') + return foot - groundAt(after, building.position[0], building.position[2] + 8) +} + +describe('a seated house is carried by the ground', () => { + const lots = [ + { name: 'a lot falling to the rear', ground: GROUNDS.fallToRear, movedBy: -1 }, + { name: 'a lot rising to the rear', ground: GROUNDS.riseToRear, movedBy: 1 }, + ] + for (const { name, ground, movedBy } of lots) { + // Skipped in this cut: it needs add_steps (outside steps, a sibling of terrain), which this PR does not carry. + test.skip(`${name}: outside steps stand on the ground before and after set_ground_level`, () => { + const built = slopedLot({ ground }) + expect(stepsFootGap(built)).toBeCloseTo(0, 2) + const seated = runTool(built, 'set_ground_level', { levelId: 'level_ground' }) + expect(seated.result.movedBuildingBy as number).toBeCloseTo(movedBy, 1) + expect(stepsFootGap(seated.nodes)).toBeCloseTo(0, 2) + }) + } + + test('the level base of a seated ground level is the ground, measured from its own plane', () => { + const seated = runTool(slopedLot({ ground: GROUNDS.fallToRear }), 'set_ground_level', { + levelId: 'level_ground', + }).nodes + const plane = levelPlaneWorldY(seated, 'level_ground') ?? 0 + expect(plane).toBeCloseTo(-1, 1) + expect(plane + levelBaseElevationAt(seated, 'level_ground', 0, 8)).toBeCloseTo( + groundAt(seated, 0, 8), + 6, + ) + }) +}) diff --git a/packages/core/src/agent-operations/terrain-shaping.test.ts b/packages/core/src/agent-operations/terrain-shaping.test.ts new file mode 100644 index 0000000000..d0fbee6ec2 --- /dev/null +++ b/packages/core/src/agent-operations/terrain-shaping.test.ts @@ -0,0 +1,850 @@ +import { describe, expect, test } from 'bun:test' +import { + clearSceneHistory, + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + type TerrainField, + useLiveTerrain, + useScene, +} from '@pascal-app/core' +import { + AGENT_OPERATIONS, + applySceneChanges, + carveTerrainPad, + describeTerrainUnderHouse, + shapeSiteTerrain, + UNGUARDED_DROP_THRESHOLD_M, +} from '@pascal-app/core/agent-operations' +import { + AGENT_TOOL_CONTRACTS, + carveTerrainPadTool, + describeTerrainUnderHouseTool, + isAgentRefusal, + shapeSiteTerrainTool, +} from '@pascal-app/core/agent-tools' +import { type AnyNode, BuildingNode, LevelNode, SiteNode, SlabNode } from '@pascal-app/core/schema' +import type { AgentOperationOutcome } from './types' + +type Nodes = Record +const context = { activeLevelId: null } +const MAX_OPERATION_BYTES = 64 * 1024 +/** The pad used across the ramp tests: samples at cols/rows 2..4 of the 9×9 field. */ +const PAD: [number, number][] = [ + [2, 2], + [4, 2], + [4, 4], + [2, 4], +] + +/** y = x − 3 on a 9 × 9 field at 1 m spacing; the lot is [1,1]–[7,7]. */ +function rampField(): TerrainField { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = (col - 3) * 100 + return field +} + +function rampScene(field: TerrainField = rampField()): Nodes { + const site = SiteNode.parse({ + id: 'site_terrain', + polygon: { + type: 'polygon', + points: [ + [1, 1], + [7, 1], + [7, 7], + [1, 7], + ], + }, + terrain: encodeTerrainField(field), + }) + return { [site.id]: site } +} + +function refusalCode(call: () => unknown): string | null { + try { + call() + } catch (error) { + return isAgentRefusal(error) ? error.code : `threw: ${String(error)}` + } + return null +} + +function applied(nodes: Nodes, outcome: AgentOperationOutcome): Nodes { + return outcome.changes ? (applySceneChanges(nodes, outcome.changes) as Nodes) : nodes +} + +function fieldOf(nodes: Nodes): TerrainField { + const site = nodes.site_terrain as SiteNode + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error('expected a persisted field after the write') + return field +} + +const sampleAt = (field: TerrainField, x: number, z: number) => + Math.round(heightAt(field, x, z) / field.step) + +describe('terrain shaping contracts', () => { + for (const operation of ['shape', 'pad'] as const) + test(`${operation} overlays arbitrary legacy grids without rewriting their bytes`, () => { + for (const grid of [ + { spacing: 1, origin: [0, 0] as [number, number] }, + { spacing: 0.5, origin: [0.1, 0.1] as [number, number] }, + { spacing: 0.95, origin: [0.13, 0.27] as [number, number] }, + ]) { + const legacy = createTerrainField({ cols: 69, rows: 69, ...grid }) + for (let row = 0; row < legacy.rows; row++) + for (let col = 0; col < legacy.cols; col++) + legacy.heights[row * legacy.cols + col] = 113 + 19 * col + 38 * row + const nodes = rampScene(legacy) + const frozen = JSON.stringify(nodes) + const before = fieldOf(nodes) + const outcome = + operation === 'shape' + ? shapeSiteTerrain(nodes, { verb: 'flatten', area: PAD, heightM: 0.25 }, context) + : carveTerrainPad(nodes, { pad: PAD, padHeightM: 0.25, blendM: 1 }, context) + const after = applied(nodes, outcome) + const field = fieldOf(after) + for (let z = 2; z <= 4; z += 0.5) + for (let x = 2; x <= 4; x += 0.5) expect(heightAt(field, x, z)).toBe(0.25) + const tiles = Object.values(after).filter((node) => node.type === 'terrain-tile') + expect(tiles).toHaveLength(1) + expect(tiles[0]).toMatchObject({ parentId: 'site_terrain', ix: 0, iz: 0 }) + for (const [x, z] of [ + [6.25, 5.75], + [20.13, 20.27], + ] as const) + expect(Math.abs(heightAt(field, x, z) - heightAt(before, x, z))).toBeLessThanOrEqual(0.01) + expect(heightAt(field, 32.75, 8.25)).toBe(heightAt(before, 32.75, 8.25)) + expect(JSON.stringify((after.site_terrain as SiteNode).terrain)).toBe( + JSON.stringify((nodes.site_terrain as SiteNode).terrain), + ) + expect(JSON.stringify(nodes)).toBe(frozen) + } + }) + + test('exports one contract and operation per new tool', () => { + const contracts = AGENT_TOOL_CONTRACTS.map((tool) => tool.name) + expect(contracts).toContain('shape_site_terrain') + expect(contracts).toContain('carve_terrain_pad') + expect(contracts).toContain('describe_terrain_under_house') + expect(AGENT_OPERATIONS.shape_site_terrain).toBe(shapeSiteTerrain) + expect(AGENT_OPERATIONS.carve_terrain_pad).toBe(carveTerrainPad) + expect(AGENT_OPERATIONS.describe_terrain_under_house).toBe(describeTerrainUnderHouse) + expect(describeTerrainUnderHouseTool.annotations?.readOnlyHint).toBe(true) + expect(shapeSiteTerrainTool.name).toBe('shape_site_terrain') + expect(carveTerrainPadTool.name).toBe('carve_terrain_pad') + }) + + test('the guard advisory reuses the verify_scene unguarded_drop threshold', () => { + expect(UNGUARDED_DROP_THRESHOLD_M).toBe(0.5) + }) +}) + +describe('carve_terrain_pad', () => { + test('a context pad leaves the legacy bytes alone and excludes outside-lot soil from cut/fill facts', () => { + const nodes = rampScene() + const outside: [number, number][] = [ + [40, 2], + [42, 2], + [42, 4], + [40, 4], + ] + expect( + refusalCode(() => carveTerrainPad(nodes, { pad: outside, padHeightM: 2 }, context)), + ).toBe('outside_property') + const outcome = carveTerrainPad( + nodes, + { pad: outside, padHeightM: 2, scope: 'context' }, + context, + ) + const after = applied(nodes, outcome) + expect(heightAt(fieldOf(after), 41, 3)).toBe(2) + expect(outcome.result.cutVolumeM3).toBe(0) + expect(outcome.result.fillVolumeM3).toBe(0) + expect(outcome.result.netM3).toBe(0) + expect((after.site_terrain as SiteNode).terrain).toEqual( + (nodes.site_terrain as SiteNode).terrain, + ) + }) + + test('pad samples equal the target height exactly, in quantized units', () => { + const nodes = rampScene() + const outcome = carveTerrainPad(nodes, { pad: PAD, padHeightM: 0, blendM: 2 }, context) + const field = fieldOf(applied(nodes, outcome)) + for (let row = 2; row <= 4; row++) + for (let col = 2; col <= 4; col++) expect(sampleAt(field, col, row)).toBe(0) + expect(outcome.result.padHeightM).toBe(0) + expect(outcome.result.padAreaM2).toBe(4) + }) + + // The pad is an exact soil face, so its volumes are the plan-area integral of the ground against + // the pad height: the ground is y = x − 3, the pad [2,4]² at 0, so each of the two halves of + // the pad holds ∫₃⁴ (x − 3) dx × 2 m = 1 m³ of cut, and 1 m³ of fill. + test('cut, fill and net match the hand-computed ramp and cut − fill = net', () => { + const outcome = carveTerrainPad(rampScene(), { pad: PAD, padHeightM: 0, blendM: 0 }, context) + const { cutVolumeM3, fillVolumeM3, netM3 } = outcome.result as { + cutVolumeM3: number + fillVolumeM3: number + netM3: number + } + expect(cutVolumeM3).toBeCloseTo(1, 6) + expect(fillVolumeM3).toBeCloseTo(1, 6) + expect(netM3).toBeCloseTo(cutVolumeM3 - fillVolumeM3, 6) + expect(netM3).toBeCloseTo(0, 6) + expect(outcome.result.sampling).toMatchObject({ + approximate: true, + method: 'midpoint_plan_area_integral', + }) + }) + + test('blend-ring cut volume includes axial and diagonal half-metre samples', () => { + const flat = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + flat.heights.fill(100) + const outcome = carveTerrainPad( + rampScene(flat), + { pad: PAD, padHeightM: 0, blendM: 1 }, + context, + ) + // 25 pad samples cut 1 m, 20 axial samples cut .5 m, four diagonals + // cut .29 m after centimetre quantization. Each sample represents .25 m². + expect(outcome.result.cutVolumeM3).toBeCloseTo(9.04, 6) + expect(outcome.result.fillVolumeM3).toBe(0) + expect(outcome.result.netM3).toBeCloseTo(9.04, 6) + }) + + test('the blend is monotone along a row and never overshoots pad or original height', () => { + const nodes = rampScene() + const before = fieldOf(nodes) + const after = fieldOf( + applied(nodes, carveTerrainPad(nodes, { pad: PAD, padHeightM: 0, blendM: 2 }, context)), + ) + const row = Array.from({ length: 9 }, (_, col) => sampleAt(after, col, 3)) + expect(row).toEqual([...row].sort((a, b) => a - b)) + for (let z = 0; z <= 8; z += 0.5) { + for (let x = 0; x <= 8; x += 0.5) { + const original = sampleAt(before, x, z) + const next = sampleAt(after, x, z) + expect(next).toBeLessThanOrEqual(Math.max(original, 0)) + expect(next).toBeGreaterThanOrEqual(Math.min(original, 0)) + } + } + // Beyond the blend ring the ground is untouched. + expect(sampleAt(after, 0, 3)).toBe(sampleAt(before, 0, 3)) + expect(sampleAt(after, 8, 3)).toBe(sampleAt(before, 8, 3)) + }) + + test('the blend ring never raises ground outside the pad', () => { + // Flat 1 m ground with one dip at (5,3), just outside the pad's east edge. + // Blending that sample toward the 0 m pad height would raise it to −1 m — + // a cubic metre of fill outside a pad that only cuts. The ring may only + // cut: outside the pad, ground never ends up higher than it started. + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + field.heights.fill(100) + field.heights[3 * 9 + 5] = -200 + const nodes = rampScene(field) + const outcome = carveTerrainPad(nodes, { pad: PAD, padHeightM: 0, blendM: 2 }, context) + const after = fieldOf(applied(nodes, outcome)) + expect(sampleAt(after, 5, 3)).toBe(-200) + for (let row = 0; row < 9; row++) + for (let col = 0; col < 9; col++) { + const inPad = col >= 2 && col <= 4 && row >= 2 && row <= 4 + if (!inPad) expect(sampleAt(after, col, row)).toBeLessThanOrEqual(sampleAt(field, col, row)) + } + expect(outcome.result.fillVolumeM3).toBe(0) + expect(outcome.result.netM3).toBe(outcome.result.cutVolumeM3) + }) + + test('retaining height is the original ground above the pad at each edge', () => { + const outcome = carveTerrainPad(rampScene(), { pad: PAD, padHeightM: 0, blendM: 2 }, context) + const heights = (outcome.result.retainingHeightM as { heightM: number }[]).map( + (edge) => edge.heightM, + ) + // The ramp is 1 m above the pad at x=4 and 1 m below it at x=2. + expect(heights).toEqual([1, 1, 1, 0]) + const slope = outcome.result.maxSlopeIntoPadDeg as number + // At x=5.5, the half-metre central difference spans y=1 to y=3: + // a roughly 2:1 grade (63.4°), steeper than the original 45° hill. + expect(slope).toBeGreaterThan(60) + expect(slope).toBeLessThan(65) + }) + + test('padFromHighestM cuts below the highest ground under the pad', () => { + const nodes = rampScene() + const outcome = carveTerrainPad(nodes, { pad: PAD, padFromHighestM: 1.2 }, context) + // Highest sample under the pad is 1 m (col 4); 1 − 1.2 = −0.2 m = −20 units. + expect(outcome.result.padHeightM).toBeCloseTo(-0.2, 6) + const field = fieldOf(applied(nodes, outcome)) + expect(sampleAt(field, 3, 3)).toBe(-20) + }) + + test('a pad reaching outside the property is refused', () => { + const outside: [number, number][] = [ + [6, 2], + [8, 2], + [8, 4], + [6, 4], + ] + expect( + refusalCode(() => carveTerrainPad(rampScene(), { pad: outside, padHeightM: 0 }, context)), + ).toBe('outside_property') + }) + + test('a pad sharing the property line is inside the property', () => { + const nodes = rampScene() + // Shares the lot's left and bottom edges ([1,1]–[7,7]) in part. + const outcome = carveTerrainPad( + nodes, + { + pad: [ + [1, 1], + [4, 1], + [4, 4], + [1, 4], + ], + padHeightM: 0, + }, + context, + ) + expect(outcome.result.padHeightM).toBe(0) + expect(sampleAt(fieldOf(applied(nodes, outcome)), 1, 1)).toBe(0) + // And a pad over the whole lot. + const whole = carveTerrainPad( + rampScene(), + { + pad: [ + [1, 1], + [7, 1], + [7, 7], + [1, 7], + ], + padHeightM: 0.25, + }, + context, + ) + expect(whole.result.padAreaM2).toBe(36) + }) + + test('a pad holding no field sample is too small', () => { + const tiny: [number, number][] = [ + [2.2, 2.2], + [2.4, 2.2], + [2.4, 2.4], + [2.2, 2.4], + ] + expect( + refusalCode(() => carveTerrainPad(rampScene(), { pad: tiny, padHeightM: 0 }, context)), + ).toBe('pad_too_small') + }) + + test('giving both pad heights, or neither, is refused', () => { + expect( + refusalCode(() => + carveTerrainPad(rampScene(), { pad: PAD, padHeightM: 0, padFromHighestM: 1 }, context), + ), + ).toBe('invalid_input') + expect(refusalCode(() => carveTerrainPad(rampScene(), { pad: PAD }, context))).toBe( + 'invalid_input', + ) + }) + + test('a scene without a site is refused', () => { + expect(refusalCode(() => carveTerrainPad({}, { pad: PAD, padHeightM: 0 }, context))).toBe( + 'no_site', + ) + }) + + test('undo restores site.terrain byte for byte in one history step', () => { + const original = useScene.getState() + try { + const before = rampScene() + const beforeTerrain = JSON.stringify((before.site_terrain as SiteNode).terrain) + useScene.setState({ nodes: before, rootNodeIds: ['site_terrain'] } as never) + clearSceneHistory() + const outcome = carveTerrainPad(before, { pad: PAD, padHeightM: 0, blendM: 2 }, context) + useScene.setState({ nodes: applied(before, outcome) } as never) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + const restored = useScene.getState().nodes as Nodes + expect(JSON.stringify((restored.site_terrain as SiteNode).terrain)).toBe(beforeTerrain) + } finally { + useScene.setState(original) + clearSceneHistory() + } + }) + + test('a live sculpt stroke is ended before the write, and refused calls keep it', () => { + const nodes = rampScene() + const liveField = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + useLiveTerrain.getState().begin('site_terrain', liveField) + try { + expect( + refusalCode(() => + carveTerrainPad( + nodes, + { + pad: [ + [2.2, 2.2], + [2.4, 2.2], + [2.4, 2.4], + [2.2, 2.4], + ], + padHeightM: 0, + }, + context, + ), + ), + ).toBe('pad_too_small') + expect(useLiveTerrain.getState().strokeOf('site_terrain')).toBeDefined() + const outcome = carveTerrainPad(nodes, { pad: PAD, padHeightM: 0 }, context) + expect(outcome.changes).toBeDefined() + expect(useLiveTerrain.getState().strokeOf('site_terrain')).toBeUndefined() + // The write was computed from the persisted ramp, not the flat live field. + expect(sampleAt(fieldOf(applied(nodes, outcome)), 0, 0)).toBe(-300) + } finally { + useLiveTerrain.getState().end('site_terrain') + } + }) + + test('a large pad writes bounded tiles instead of sending the frozen oversized legacy field', () => { + const field = createTerrainField({ cols: 129, rows: 129, spacing: 0.5, step: 0.01 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) field.heights[row * field.cols + col] = col + const site = SiteNode.parse({ + id: 'site_terrain', + polygon: { + type: 'polygon', + points: [ + [2, 2], + [62, 2], + [62, 62], + [2, 62], + ], + }, + terrain: encodeTerrainField(field), + }) + const nodes: Nodes = { [site.id]: site } + const write = () => + carveTerrainPad( + nodes, + { + pad: [ + [10, 10], + [54, 10], + [54, 54], + [10, 54], + ], + padHeightM: 0.2, + blendM: 4, + }, + context, + ) + + const outcome = write() + const after = applied(nodes, outcome) + expect((after.site_terrain as SiteNode).terrain).toEqual(site.terrain) + const tiles = Object.values(after).filter((node) => node.type === 'terrain-tile') + expect(tiles.length).toBeGreaterThan(1) + for (const tile of tiles) + expect( + new TextEncoder().encode(JSON.stringify({ from: tile, to: tile })).length, + ).toBeLessThan(MAX_OPERATION_BYTES) + expect(heightAt(fieldOf(after), 32, 32)).toBe(0.2) + }) +}) + +describe('shape_site_terrain', () => { + test('flatten sets every sample in a polygon to the height, exactly', () => { + const nodes = rampScene() + const outcome = shapeSiteTerrain(nodes, { verb: 'flatten', area: PAD, heightM: 0.5 }, context) + const field = fieldOf(applied(nodes, outcome)) + for (let row = 2; row <= 4; row++) + for (let col = 2; col <= 4; col++) expect(sampleAt(field, col, row)).toBe(50) + expect(outcome.result).toMatchObject({ + changedSamples: 20, + beforeMinMaxM: { minM: -1, maxM: 1 }, + afterMinMaxM: { minM: 0.5, maxM: 0.5 }, + touchedM2: 6.25, + }) + // Samples outside the polygon keep the ramp. + expect(sampleAt(field, 1, 3)).toBe(-200) + }) + + test('raise over a circle moves only the samples inside the radius', () => { + const nodes = rampScene() + const outcome = shapeSiteTerrain( + nodes, + { verb: 'raise', area: { x: 3, z: 3, radiusM: 1 }, heightM: 0.5 }, + context, + ) + const field = fieldOf(applied(nodes, outcome)) + expect(outcome.result.changedSamples).toBe(13) + expect(sampleAt(field, 3, 3)).toBe(50) + expect(sampleAt(field, 2, 3)).toBe(-50) + // The diagonal sample is √2 away: outside a 1 m circle. + expect(sampleAt(field, 2, 2)).toBe(-100) + }) + + test('lower over a polygon subtracts the height', () => { + const nodes = rampScene() + const outcome = shapeSiteTerrain(nodes, { verb: 'lower', area: PAD, heightM: 0.25 }, context) + const field = fieldOf(applied(nodes, outcome)) + expect(sampleAt(field, 3, 3)).toBe(-25) + expect(sampleAt(field, 4, 4)).toBe(75) + }) + + test('raise without a height moves the ground by the brush stroke metre', () => { + const nodes = rampScene() + const outcome = shapeSiteTerrain(nodes, { verb: 'raise', area: PAD }, context) + expect(sampleAt(fieldOf(applied(nodes, outcome)), 3, 3)).toBe(100) + }) + + test('strength scales a flatten toward its target', () => { + const nodes = rampScene() + const outcome = shapeSiteTerrain( + nodes, + { verb: 'flatten', area: PAD, heightM: 1, strength: 0.5 }, + context, + ) + // Col 2 sits at −1 m; halfway to 1 m is 0. + expect(sampleAt(fieldOf(applied(nodes, outcome)), 2, 3)).toBe(0) + }) + + test('softness fades the effect over that many metres inside the edge', () => { + const nodes = rampScene() + const outcome = shapeSiteTerrain( + nodes, + { verb: 'raise', area: { x: 4, z: 4, radiusM: 2 }, heightM: 1, softness: 2 }, + context, + ) + const field = fieldOf(applied(nodes, outcome)) + // Centre is 2 m inside the edge: full metre. One metre in: half a metre. + expect(sampleAt(field, 4, 4)).toBe(200) + expect(sampleAt(field, 3, 4)).toBe(50) + }) + + test('smooth diffuses a step into its neighbours without exceeding it', () => { + // A step (not a spike): the brush diffusion this mirrors is a Jacobi + // filter, which oscillates on a single-sample spike but settles a step. + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + for (let row = 0; row < field.rows; row++) + for (let col = 4; col < field.cols; col++) field.heights[row * field.cols + col] = 100 + const nodes = rampScene(field) + const outcome = shapeSiteTerrain( + nodes, + { verb: 'smooth', area: { x: 4, z: 4, radiusM: 2 } }, + context, + ) + const after = fieldOf(applied(nodes, outcome)) + // The last low sample before the step rises; the first high one falls. + expect(sampleAt(after, 3, 4)).toBeGreaterThan(0) + expect(sampleAt(after, 4, 4)).toBeLessThan(100) + expect(sampleAt(after, 4, 4)).toBeGreaterThan(sampleAt(after, 3, 4)) + for (let z = 0; z <= 8; z += 0.5) + for (let x = 0; x <= 8; x += 0.5) { + expect(sampleAt(after, x, z)).toBeLessThanOrEqual(100) + expect(sampleAt(after, x, z)).toBeGreaterThanOrEqual(0) + } + }) + + test('flatten without a height is refused; an area outside the property too', () => { + expect( + refusalCode(() => shapeSiteTerrain(rampScene(), { verb: 'flatten', area: PAD }, context)), + ).toBe('invalid_input') + expect( + refusalCode(() => + shapeSiteTerrain( + rampScene(), + { verb: 'raise', area: { x: 6.5, z: 4, radiusM: 1 }, heightM: 1 }, + context, + ), + ), + ).toBe('outside_property') + }) + + test('explicit context shaping writes outside the property without changing the frozen base', () => { + const nodes = rampScene() + const snapshot = structuredClone(nodes) + const input = { verb: 'flatten', area: { x: 40, z: 3, radiusM: 1 }, heightM: 2 } as const + expect(refusalCode(() => shapeSiteTerrain(nodes, input, context))).toBe('outside_property') + expect(nodes).toEqual(snapshot) + const outcome = shapeSiteTerrain(nodes, { ...input, scope: 'context' }, context) + const after = applied(nodes, outcome) + expect(heightAt(fieldOf(after), 40, 3)).toBe(2) + expect((after.site_terrain as SiteNode).terrain).toEqual( + (nodes.site_terrain as SiteNode).terrain, + ) + expect(heightAt(fieldOf(after), 3, 3)).toBe(0) + expect(nodes).toEqual(snapshot) + }) + + test('a write that changes nothing is a no_change refusal with no changes', () => { + // Only the col-3 samples fall in this strip, and the ramp there is already 0 m. + const flatArea: [number, number][] = [ + [2.8, 2], + [3.2, 2], + [3.2, 4], + [2.8, 4], + ] + expect( + refusalCode(() => + shapeSiteTerrain(rampScene(), { verb: 'flatten', area: flatArea, heightM: 0 }, context), + ), + ).toBe('no_change') + expect( + refusalCode(() => + shapeSiteTerrain(rampScene(), { verb: 'raise', area: PAD, heightM: 0 }, context), + ), + ).toBe('no_change') + }) + + test('shaping back to the datum persists a zero override without erasing the legacy base', () => { + const flat = createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + flat.heights[3 * 9 + 3] = 40 + const nodes = rampScene(flat) + const outcome = shapeSiteTerrain( + nodes, + { verb: 'flatten', area: { x: 3, z: 3, radiusM: 0.6 }, heightM: 0 }, + context, + ) + const after = applied(nodes, outcome) + expect((after.site_terrain as SiteNode).terrain).toEqual( + (nodes.site_terrain as SiteNode).terrain, + ) + expect(Object.values(after).some((node) => node.type === 'terrain-tile')).toBe(true) + expect(heightAt(fieldOf(after), 3, 3)).toBe(0) + }) +}) + +type HouseOptions = { + flat?: boolean + elevation?: number + buildingPosition?: [number, number, number] + slabPolygon?: [number, number][] + withSlab?: boolean +} + +function houseScene(options: HouseOptions = {}): Nodes { + const field = options.flat + ? createTerrainField({ cols: 9, rows: 9, spacing: 1, step: 0.01 }) + : rampField() + const site = SiteNode.parse({ + id: 'site_terrain', + polygon: { + type: 'polygon', + points: [ + [1, 1], + [7, 1], + [7, 7], + [1, 7], + ], + }, + terrain: encodeTerrainField(field), + children: ['building_house'], + }) + const building = BuildingNode.parse({ + id: 'building_house', + parentId: site.id, + position: options.buildingPosition ?? [0, 0, 0], + children: ['level_house'], + }) + const withSlab = options.withSlab ?? true + const level = LevelNode.parse({ + id: 'level_house', + parentId: building.id, + level: 0, + height: 3, + children: withSlab ? ['slab_house'] : [], + }) + const nodes: Nodes = { [site.id]: site, [building.id]: building, [level.id]: level } + if (withSlab) { + const slab = SlabNode.parse({ + id: 'slab_house', + parentId: level.id, + boundary: 'auto', + polygon: options.slabPolygon ?? PAD, + elevation: options.elevation ?? 1.6, + }) + nodes[slab.id] = slab + } + return nodes +} + +describe('describe_terrain_under_house', () => { + test('edge drops on a wedge, with clearance under the raised slab', () => { + const outcome = describeTerrainUnderHouse(houseScene(), {}, context) + expect(outcome.changes).toBeUndefined() + expect(outcome.result).toMatchObject({ + levelId: 'level_house', + slabId: 'slab_house', + slabTopM: 1.6, + highestM: 1, + lowestM: -1, + reliefM: 2, + }) + expect(outcome.result.clearanceUnderSlabM).toBeCloseTo(0.6, 9) + const drops = (outcome.result.dropAtEdges as { dropM: number }[]).map((edge) => edge.dropM) + // Slab top 1.6 over ground falling 1 → −1 along +x edges; the x=4 edge + // stands 0.6 m over its ground. + expect(drops.map((drop) => Math.round(drop * 100))).toEqual([260, 60, 260, 260]) + }) + + test('needsGuardAt flags edges over the shared 0.5 m threshold, as advisory', () => { + const outcome = describeTerrainUnderHouse(houseScene(), {}, context) + const guarded = outcome.result.needsGuardAt as { dropM: number }[] + expect(guarded).toHaveLength(4) + expect(Math.min(...guarded.map((edge) => edge.dropM))).toBeGreaterThan( + UNGUARDED_DROP_THRESHOLD_M, + ) + expect(outcome.result.guardAdvisory).toMatchObject({ + advisory: true, + thresholdM: UNGUARDED_DROP_THRESHOLD_M, + }) + expect( + (outcome.result.guardAdvisory as { typicalRequirement: string }).typicalRequirement, + ).toContain('0.76') + }) + + test('a flat lot under a slab at grade reports zero drops and no guard edges', () => { + const outcome = describeTerrainUnderHouse(houseScene({ flat: true, elevation: 0 }), {}, context) + expect(outcome.result).toMatchObject({ reliefM: 0, clearanceUnderSlabM: 0 }) + expect((outcome.result.dropAtEdges as { dropM: number }[]).every((e) => e.dropM === 0)).toBe( + true, + ) + expect(outcome.result.needsGuardAt).toEqual([]) + }) + + test('the footprint is reported in the site frame, through the building offset', () => { + const outcome = describeTerrainUnderHouse( + houseScene({ + buildingPosition: [1, 0, 0], + slabPolygon: [ + [1, 2], + [3, 2], + [3, 4], + [1, 4], + ], + }), + {}, + context, + ) + expect(outcome.result.footprint).toEqual(PAD) + expect(outcome.result.highestM).toBe(1) + }) + + test('an explicit level is honoured and a missing one refused', () => { + const nodes = houseScene() + expect( + describeTerrainUnderHouse(nodes, { levelId: 'level_house' }, context).result.levelId, + ).toBe('level_house') + expect( + refusalCode(() => describeTerrainUnderHouse(nodes, { levelId: 'level_missing' }, context)), + ).toBe('level_not_found') + expect( + refusalCode(() => describeTerrainUnderHouse(nodes, { levelId: 'slab_house' }, context)), + ).toBe('not_a_level') + }) + + test('refuses no_site and a level with no slab footprint', () => { + expect(refusalCode(() => describeTerrainUnderHouse({}, {}, context))).toBe('no_site') + expect( + refusalCode(() => describeTerrainUnderHouse(houseScene({ withSlab: false }), {}, context)), + ).toBe('footprint_empty') + }) + + test('sampling counts every measured point, interior and boundary', () => { + const outcome = describeTerrainUnderHouse(houseScene(), {}, context) + // 2×2 m footprint at 1 m spacing: 4 cell-midpoint interior samples plus + // 3 sampled points along each of the 4 edges. + expect((outcome.result.sampling as { sampleCount: number }).sampleCount).toBe(16) + }) + + test('slabs are ranked by total area, and a disconnected largest slab is refused', () => { + const nodes = houseScene({ withSlab: false }) + // 6×4 m slab cut through by a 1 m strip: two 10 m² components, 20 m² in + // total. The separate solid slab is 12 m² — larger than either component, + // smaller than the slab it would silently replace. + const split = SlabNode.parse({ + id: 'slab_split', + parentId: 'level_house', + boundary: 'auto', + polygon: [ + [1, 1], + [7, 1], + [7, 5], + [1, 5], + ], + holes: [ + [ + [3.5, 0.5], + [4.5, 0.5], + [4.5, 5.5], + [3.5, 5.5], + ], + ], + elevation: 1.6, + }) + const solid = SlabNode.parse({ + id: 'slab_solid', + parentId: 'level_house', + boundary: 'auto', + polygon: [ + [1, 5], + [5, 5], + [5, 8], + [1, 8], + ], + elevation: 1.6, + }) + nodes[split.id] = split + nodes[solid.id] = solid + ;(nodes.level_house as LevelNode).children = [split.id, solid.id] + expect(refusalCode(() => describeTerrainUnderHouse(nodes, {}, context))).toBe( + 'disconnected_footprint', + ) + }) + + test('guard edges are terrain-only drops, and the advisory says so', () => { + const nodes = houseScene({ withSlab: false }) + const primary = SlabNode.parse({ + id: 'slab_primary', + parentId: 'level_house', + boundary: 'auto', + polygon: [ + [1, 2], + [4, 2], + [4, 5], + [1, 5], + ], + elevation: 2, + }) + const landing = SlabNode.parse({ + id: 'slab_landing', + parentId: 'level_house', + boundary: 'auto', + polygon: [ + [4, 2], + [6, 2], + [6, 5], + [4, 5], + ], + elevation: 1.8, + }) + nodes[primary.id] = primary + nodes[landing.id] = landing + ;(nodes.level_house as LevelNode).children = [primary.id, landing.id] + const outcome = describeTerrainUnderHouse(nodes, {}, context) + expect(outcome.result.slabId).toBe('slab_primary') + // The shared edge at x=4 stands 1 m over the terrain, so the terrain-only + // fact flags it — even though a landing, not open ground, lies beyond it + // and verify_scene would not. Only the threshold is shared. + const guarded = outcome.result.needsGuardAt as { from: number[]; to: number[] }[] + expect(guarded.some((edge) => edge.from[0] === 4 && edge.to[0] === 4)).toBe(true) + const basis = (outcome.result.guardAdvisory as { basis: string }).basis + expect(basis).toContain('Only the threshold is shared') + expect(basis).not.toContain('both flag the same') + }) +}) diff --git a/packages/core/src/agent-operations/terrain-soil-pad.test.ts b/packages/core/src/agent-operations/terrain-soil-pad.test.ts new file mode 100644 index 0000000000..f97e668f3f --- /dev/null +++ b/packages/core/src/agent-operations/terrain-soil-pad.test.ts @@ -0,0 +1,278 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + terrainBreaksOf, +} from '@pascal-app/core' +import { AGENT_OPERATIONS, applySceneChanges } from '@pascal-app/core/agent-operations' +import { isAgentRefusal } from '@pascal-app/core/agent-tools' +import { type AnyNode, SiteNode } from '@pascal-app/core/schema' + +/* + * Failure modes this file pins (the stair-step of 15 Oct, on pads): a pad with no blend is a + * vertical step, but it was written into the 0.5 m lattice, so the ground 3 cm inside its edge + * was up to 0.78 m off the pad height and 3 cm outside up to 0.81 m off the original ground. + */ + +type Nodes = Record +type Point = [number, number] +const context = { activeLevelId: null } +const PAD_HEIGHT = -0.6 + +function hillside(): Nodes { + const field = createTerrainField({ origin: [-20, -20], spacing: 0.5, cols: 81, rows: 81 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) { + const x = -20 + col * 0.5 + const z = -20 + row * 0.5 + field.heights[row * field.cols + col] = Math.round((0.06 * x + 0.04 * z) * 100) + } + const site = SiteNode.parse({ + id: 'site_pad', + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [20, -20], + [20, 20], + [-20, 20], + ], + }, + terrain: encodeTerrainField(field), + }) + return { [site.id]: site } +} + +/** A rectangle turned `degrees`, so no edge lies on the lattice. */ +function turned(centre: Point, width: number, depth: number, degrees: number): Point[] { + const c = Math.cos((degrees * Math.PI) / 180) + const s = Math.sin((degrees * Math.PI) / 180) + return ( + [ + [-width / 2, -depth / 2], + [width / 2, -depth / 2], + [width / 2, depth / 2], + [-width / 2, depth / 2], + ] as Point[] + ).map(([x, z]) => [centre[0] + x * c - z * s, centre[1] + x * s + z * c]) +} + +const ops = AGENT_OPERATIONS as unknown as Record< + string, + ( + nodes: Nodes, + input: unknown, + context: unknown, + ) => { + result: Record + changes?: Parameters[1] + } +> + +function carve(nodes: Nodes, input: Record) { + const outcome = ops.carve_terrain_pad!(nodes, input, context) + return { outcome, after: applySceneChanges(nodes, outcome.changes) as Nodes } +} + +function fieldOf(nodes: Nodes) { + const site = nodes.site_pad + if (site?.type !== 'site') throw new Error('Missing site') + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error('Missing terrain') + return field +} + +function refusal(call: () => unknown): string | null { + try { + call() + } catch (error) { + return isAgentRefusal(error) ? error.code : `threw: ${String(error)}` + } + return null +} + +/** Points a few centimetres to each side of the pad's edges, away from the corners. */ +function besideTheEdges(pad: Point[], offset: number) { + const inside: Point[] = [] + const outside: Point[] = [] + for (let i = 0; i < pad.length; i++) { + const a = pad[i] as Point + const b = pad[(i + 1) % pad.length] as Point + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + // The pad is counter-clockwise, so the left of a → b is inside. + const nx = -(b[1] - a[1]) / length + const nz = (b[0] - a[0]) / length + for (let k = 1; k < 60; k++) { + const t = k / 60 + const x = a[0] + (b[0] - a[0]) * t + const z = a[1] + (b[1] - a[1]) * t + inside.push([x + nx * offset, z + nz * offset]) + outside.push([x - nx * offset, z - nz * offset]) + } + } + return { inside, outside } +} + +describe('a pad with blendM 0 is an exact soil face', () => { + const nodes = hillside() + const natural = fieldOf(nodes) + const pad = turned([0, 0], 8, 6, 25) + + test('is written as one closed break of kind soil at the pad height, with no tile', () => { + const { outcome, after } = carve(nodes, { pad, padHeightM: PAD_HEIGHT }) + const breaks = terrainBreaksOf(after.site_pad as SiteNode, after) + expect(breaks).toHaveLength(1) + expect(breaks[0]).toMatchObject({ kind: 'soil', left: PAD_HEIGHT, right: 'ground' }) + expect(Object.values(after).filter((node) => node.type === 'terrain-tile')).toEqual([]) + expect((after.site_pad as SiteNode).terrain).toEqual((nodes.site_pad as SiteNode).terrain) + expect(outcome.result.changedSamples).toBe(0) + expect(outcome.result.edge).toBeUndefined() + expect(outcome.result.maxSlopeIntoPadDeg).toBe(90) + expect(outcome.result.padHeightM).toBe(PAD_HEIGHT) + expect((outcome.result.breaks as { kind: string; faceAreaM2: number }[])[0]).toMatchObject({ + kind: 'soil', + }) + }) + + test('the ground 3 cm inside the edge is the pad height, and 3 cm outside the original ground', () => { + const { after } = carve(nodes, { pad, padHeightM: PAD_HEIGHT }) + const field = fieldOf(after) + const { inside, outside } = besideTheEdges(pad, 0.03) + for (const [x, z] of inside) expect(heightAt(field, x, z)).toBeCloseTo(PAD_HEIGHT, 9) + for (const [x, z] of outside) + expect(heightAt(field, x, z)).toBeCloseTo(heightAt(natural, x, z), 9) + }) + + test('volumes are plan-area integrals, and padFromHighestM gives the same face', () => { + const { outcome } = carve(nodes, { pad, padHeightM: PAD_HEIGHT }) + const { cutVolumeM3, fillVolumeM3, netM3, padAreaM2 } = outcome.result as Record + expect(padAreaM2).toBeCloseTo(48, 6) + // The ground is a plane, so the integral is the mean height over the pad against the pad. + const mean = 0.06 * 0 + 0.04 * 0 + expect(netM3).toBeCloseTo((mean - PAD_HEIGHT) * 48, 1) + expect(netM3).toBeCloseTo(cutVolumeM3 - fillVolumeM3, 6) + const highest = carve(nodes, { pad, padFromHighestM: 0 }) + expect((highest.outcome.result.breaks as { kind: string }[])[0]).toMatchObject({ kind: 'soil' }) + }) + + test('a pad that already stands on the ground writes nothing', () => { + const flat = createTerrainField({ origin: [-20, -20], spacing: 0.5, cols: 81, rows: 81 }) + const site = SiteNode.parse({ + id: 'site_pad', + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [20, -20], + [20, 20], + [-20, 20], + ], + }, + terrain: encodeTerrainField(flat), + }) + expect( + refusal(() => ops.carve_terrain_pad!({ [site.id]: site }, { pad, padHeightM: 0 }, context)), + ).toBe('no_change') + }) + + test('a pad within half a centimetre of the ground is the lattice’s no_change too', () => { + const flat = createTerrainField({ origin: [-20, -20], spacing: 0.5, cols: 81, rows: 81 }) + const site = SiteNode.parse({ + id: 'site_pad', + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [20, -20], + [20, 20], + [-20, 20], + ], + }, + terrain: encodeTerrainField(flat), + }) + expect( + refusal(() => + ops.carve_terrain_pad!({ [site.id]: site }, { pad, padHeightM: 0.004 }, context), + ), + ).toBe('no_change') + }) + + test('a pad holding no lattice sample is still too small', () => { + const tiny: Point[] = [ + [2.1, 2.1], + [2.3, 2.1], + [2.3, 2.3], + [2.1, 2.3], + ] + expect( + refusal(() => ops.carve_terrain_pad!(nodes, { pad: tiny, padHeightM: 0 }, context)), + ).toBe('pad_too_small') + }) +}) + +describe('what stays on the lattice, and says so', () => { + const nodes = hillside() + + test('blendM above 0 is the blend ring on the lattice, as before', () => { + const { outcome, after } = carve(nodes, { + pad: turned([0, 0], 8, 6, 25), + padHeightM: PAD_HEIGHT, + blendM: 2, + }) + expect(terrainBreaksOf(after.site_pad as SiteNode, after)).toHaveLength(0) + expect( + Object.values(after).filter((node) => node.type === 'terrain-tile').length, + ).toBeGreaterThan(0) + expect(outcome.result.changedSamples).toBeGreaterThan(0) + expect(outcome.result.edge).toBeUndefined() + }) + + test('cliff and retaining edges are still exact breaks of their own kind', () => { + for (const edges of ['cliff', 'retaining'] as const) { + const { after } = carve(nodes, { + pad: turned([0, 0], 8, 6, 25), + padHeightM: PAD_HEIGHT, + edges, + }) + expect(terrainBreaksOf(after.site_pad as SiteNode, after)[0]).toMatchObject({ kind: edges }) + } + }) + + test('a pad that is not convex keeps the lattice write and states it as a fact', () => { + const lShape: Point[] = [ + [-4, -4], + [4, -4], + [4, 0], + [0, 0], + [0, 4], + [-4, 4], + ] + const { outcome, after } = carve(nodes, { pad: lShape, padHeightM: PAD_HEIGHT }) + expect(terrainBreaksOf(after.site_pad as SiteNode, after)).toHaveLength(0) + expect(outcome.result.changedSamples).toBeGreaterThan(0) + expect(outcome.result.edge).toMatchObject({ + kind: 'lattice_step', + exact: false, + reason: 'non_convex_pad', + resolutionM: 0.5, + }) + }) + + test('a pad whose break would cross another keeps the lattice write and says why', () => { + const first = carve(nodes, { + pad: turned([0, 0], 8, 6, 25), + padHeightM: PAD_HEIGHT, + edges: 'retaining', + }) + const second = carve(first.after, { pad: turned([3, 2], 8, 6, 10), padHeightM: -1.2 }) + expect(terrainBreaksOf(second.after.site_pad as SiteNode, second.after)).toHaveLength(1) + expect(second.outcome.result.changedSamples).toBeGreaterThan(0) + expect(second.outcome.result.edge).toMatchObject({ + kind: 'lattice_step', + exact: false, + reason: 'crossing_breaks', + }) + }) +}) diff --git a/packages/core/src/agent-operations/terrain.test.ts b/packages/core/src/agent-operations/terrain.test.ts new file mode 100644 index 0000000000..311106d320 --- /dev/null +++ b/packages/core/src/agent-operations/terrain.test.ts @@ -0,0 +1,352 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + persistedTerrainFieldOf, + useLiveTerrain, +} from '@pascal-app/core' +import { + AGENT_OPERATIONS, + readSiteTerrain, + readTerrainContours, + sampleTerrainLine, +} from '@pascal-app/core/agent-operations' +import { + AGENT_TOOL_CONTRACTS, + isAgentRefusal, + readSiteTerrainTool, + readTerrainContoursTool, + sampleTerrainLineTool, +} from '@pascal-app/core/agent-tools' +import { type AnyNode, SiteNode, TerrainTileNode } from '@pascal-app/core/schema' +import { TERRAIN_CASES, terrainRampScene } from './__fixtures__/terrain-cases' + +type Nodes = Record +const context = { activeLevelId: null } +const square: [number, number][] = [ + [1, 1], + [5, 1], + [5, 5], + [1, 5], +] + +function ramp(scale = 1): Nodes { + return terrainRampScene(scale).nodes as Nodes +} +function refusalCode(call: () => unknown): string | null { + try { + call() + } catch (error) { + if (isAgentRefusal(error)) return error.code + throw error + } + return null +} + +for (const entry of TERRAIN_CASES) { + test(`${entry.tool}: ${entry.name}`, () => { + const operation = AGENT_OPERATIONS[entry.tool as keyof typeof AGENT_OPERATIONS] + const nodes = entry.scene().nodes as Nodes + if ('refusal' in entry.expect) { + expect(refusalCode(() => operation(nodes, entry.input as never, context))).toBe( + entry.expect.refusal, + ) + } else { + const before = structuredClone(nodes) + const outcome = operation(nodes, entry.input as never, context) + expect(outcome.result).toMatchObject(entry.expect.result) + expect(entry.expect.check?.(outcome.result, nodes) ?? []).toEqual([]) + expect(Object.keys(outcome)).toEqual(['result']) + expect(nodes).toEqual(before) + } + }) +} + +describe('persisted terrain facts', () => { + for (const extent of ['large lot', 'distant tiles'] as const) { + test(`contours refuse an oversized ${extent} before sampling its union`, () => { + const base = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + base.heights[0] = 100 + const encoded = encodeTerrainField(base) + const site = SiteNode.parse({ + id: 'site_contour_budget', + ...(extent === 'large lot' + ? { + terrain: encoded, + polygon: { + type: 'polygon', + points: [ + [0, 0], + [10_000, 0], + [10_000, 10_000], + [0, 10_000], + ], + }, + } + : {}), + }) + const nodes: Nodes = { [site.id]: site } + if (extent === 'distant tiles') { + for (const ix of [0, 100_000]) { + const tile = TerrainTileNode.parse({ + id: `terrain-tile_budget_${ix}`, + parentId: site.id, + level: 0, + ix, + iz: 0, + step: 0.01, + heights: encoded.heights, + }) + nodes[tile.id] = tile + } + } + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error('Missing virtual terrain') + const descriptor = Object.getOwnPropertyDescriptor(field, 'readHeightAt') + if (!descriptor) throw new Error('Missing virtual sampling seam') + let samples = 0 + // A sentinel makes a misplaced guard fail immediately instead of hanging the runner. + Object.defineProperty(field, 'readHeightAt', { + ...descriptor, + value: () => { + samples++ + throw new Error('Oversized contour union sampled before refusal') + }, + }) + const before = structuredClone(nodes) + try { + expect(refusalCode(() => readTerrainContours(nodes, { intervalM: 1 }, context))).toBe( + 'contour_limit', + ) + expect(samples).toBe(0) + expect(nodes).toEqual(before) + } finally { + Object.defineProperty(field, 'readHeightAt', descriptor) + } + }) + } + + test('exports one read-only contract and operation per tool', () => { + for (const contract of [readSiteTerrainTool, sampleTerrainLineTool, readTerrainContoursTool]) { + expect(AGENT_TOOL_CONTRACTS).toContain(contract) + expect(contract.annotations.readOnlyHint).toBe(true) + expect(AGENT_OPERATIONS).toHaveProperty(contract.name) + } + }) + + test('ramp corners have unit normals and signed endpoint edge drops', () => { + const result = readSiteTerrain(ramp(), { footprint: square, cellM: 1 }, context).result + const corners = result.slopeAtCorners as { slopeDeg: number; normal: number[] }[] + expect(corners).toHaveLength(4) + for (const corner of corners) { + expect(corner.slopeDeg).toBeCloseTo(45) + expect(corner.normal[0]).toBeCloseTo(-Math.SQRT1_2) + expect(corner.normal[1]).toBeCloseTo(Math.SQRT1_2) + expect(corner.normal[2]).toBeCloseTo(0) + } + expect((result.edgeDrops as { dropM: number }[]).map((edge) => edge.dropM)).toEqual([ + -4, 0, 4, 0, + ]) + expect(result.edgeDrops).toEqual( + expect.arrayContaining([expect.objectContaining({ maxSlopeDeg: 45 })]), + ) + }) + + test('field-border slopes continue the ramp instead of halving it through clamping', () => { + const result = sampleTerrainLine(ramp(), { from: [0, 2], to: [8, 2], stepM: 8 }, context).result + const points = result.points as { slopeDeg: number }[] + // A one-metre finite difference spans the start of the 64 m decay band. + for (const point of points) { + expect(point.slopeDeg).toBeGreaterThan(44) + expect(point.slopeDeg).toBeLessThan(46) + } + }) + + test('finite large areas keep the mean slope finite', () => { + const spacing = 1e153 + const field = createTerrainField({ cols: 9, rows: 9, spacing, step: spacing }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) field.heights[row * field.cols + col] = col - 3 + const site = SiteNode.parse({ + id: 'site_large', + polygon: { + type: 'polygon', + points: square.map(([x, z]) => [x * spacing, z * spacing]), + }, + terrain: encodeTerrainField(field), + }) + const result = readSiteTerrain({ [site.id]: site }, { cellM: spacing }, context).result + expect(result.slopeMeanDeg).toBeCloseTo(45) + }) + + test('a wedge reports its interior peak rather than only its corners', () => { + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) + field.heights[row * field.cols + col] = (2 - Math.abs(col - 3)) * 100 + const footprint = [ + [1, 1], + [5, 1], + [5, 5], + [1, 5], + ] + const site = SiteNode.parse({ + id: 'site_wedge', + polygon: { type: 'polygon', points: footprint }, + terrain: encodeTerrainField(field), + }) + const result = readSiteTerrain({ [site.id]: site }, { cellM: 0.4 }, context).result + expect(result.minM).toBe(0) + // Ten edge intervals land on x=3, the peak; the four corners alone are all at zero. + expect(result.maxM).toBeCloseTo(2) + expect(result.reliefM).toBeCloseTo(2) + expect(result.slopeMaxDeg).toBeCloseTo(45) + expect(result.slopeMeanDeg as number).toBeGreaterThan(0) + expect(result.slopeMeanDeg as number).toBeLessThan(45) + }) + + test('changing only persisted terrain changes facts and emits no changes', () => { + const before = ramp() + const after = ramp(2) + const first = readSiteTerrain(before, {}, context) + const second = readSiteTerrain(after, {}, context) + expect(first.result.reliefM).toBe(4) + expect(second.result.reliefM).toBe(8) + expect(Object.keys(first)).toEqual(['result']) + expect(Object.keys(second)).toEqual(['result']) + expect(before).toEqual(ramp()) + expect(after).toEqual(ramp(2)) + }) + + test('reads persisted terrain even during a different live stroke', () => { + const nodes = ramp() + const field = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) + useLiveTerrain.getState().begin('site_terrain', field) + try { + expect(readSiteTerrain(nodes, {}, context).result.reliefM).toBe(4) + } finally { + useLiveTerrain.getState().end('site_terrain') + } + }) + + test('two segment calls form a polyline without duplicate joints', () => { + const first = sampleTerrainLine(ramp(), { from: [1, 2], to: [3, 2], stepM: 1 }, context).result + .points as { x: number; z: number; yM: number }[] + const second = sampleTerrainLine(ramp(), { from: [3, 2], to: [3, 4], stepM: 1 }, context).result + .points as { x: number; z: number; yM: number }[] + expect([...first, ...second.slice(1)].map(({ x, z, yM }) => [x, z, yM])).toEqual([ + [1, 2, -2], + [2, 2, -1], + [3, 2, 0], + [3, 3, 0], + [3, 4, 0], + ]) + }) + + test('ramp contours have equal height with labelled marching-squares approximation', () => { + const result = readTerrainContours(ramp(), { intervalM: 1 }, context).result + const lines = result.lines as { levelM: number; points: number[][] }[] + expect(lines.map((line) => line.levelM)).toContain(0) + for (const line of lines) + for (const point of line.points) expect((point[0] ?? NaN) - 3).toBeCloseTo(line.levelM) + expect(result.sampling).toMatchObject({ + approximate: true, + method: 'marching_squares_midpoint_mask', + intervalM: 1, + }) + }) + + test('an encoded flat field is measured flat, unlike an absent field', () => { + const site = SiteNode.parse({ + id: 'site_flat', + polygon: { type: 'polygon', points: square }, + terrain: encodeTerrainField(createTerrainField({ cols: 9, rows: 9, spacing: 1 })), + }) + const nodes = { [site.id]: site } + expect(readSiteTerrain(nodes, {}, context).result).toMatchObject({ + hasTerrain: true, + flat: true, + reliefM: 0, + slopeMeanDeg: 0, + areaAboveGradeM2: 0, + areaBelowGradeM2: 0, + }) + expect(readTerrainContours(nodes, {}, context).result.lines).toEqual([]) + }) + + test('a footprint whose grid misses its interior refuses unknown areas', () => { + expect( + refusalCode(() => + readSiteTerrain( + ramp(), + { + footprint: [ + [1, 1], + [5, 5], + [5, 5.01], + ], + cellM: 4, + }, + context, + ), + ), + ).toBe('sampling_insufficient') + }) + + test('self-crossing footprints are refused', () => { + expect( + refusalCode(() => + readSiteTerrain( + ramp(), + { + footprint: [ + [1, 1], + [5, 5], + [1, 5], + [5, 1], + ], + }, + context, + ), + ), + ).toBe('invalid_polygon') + }) + + test('multiple sites do not silently select one', () => { + const nodes = ramp() + const site = SiteNode.parse({ id: 'site_other' }) + expect(refusalCode(() => readSiteTerrain({ ...nodes, [site.id]: site }, {}, context))).toBe( + 'ambiguous_site', + ) + }) + + test('bad fields refuse no_terrain instead of measuring zero', () => { + const nodes = ramp() + const site = nodes.site_terrain as SiteNode + expect( + refusalCode(() => + readSiteTerrain( + { + ...nodes, + [site.id]: { ...site, terrain: { ...site.terrain, heights: 'broken' } } as SiteNode, + }, + {}, + context, + ), + ), + ).toBe('no_terrain') + }) + + for (const input of [ + { cellM: 0 }, + { cellM: -1 }, + { cellM: Infinity }, + { footprint: [[1, NaN]] }, + { invented: true }, + ]) + test(`invalid terrain input refuses with a code: ${JSON.stringify(input)}`, () => { + expect(refusalCode(() => readSiteTerrain(ramp(), input as never, context))).toBe( + 'invalid_input', + ) + }) +}) diff --git a/packages/core/src/agent-operations/terrain.ts b/packages/core/src/agent-operations/terrain.ts new file mode 100644 index 0000000000..b3b90d2335 --- /dev/null +++ b/packages/core/src/agent-operations/terrain.ts @@ -0,0 +1,1763 @@ +import { z } from 'zod' +import { isAgentRefusal, refuse } from '../agent-tools/refusal' +import { + carveTerrainPadTool, + describeTerrainUnderHouseTool, + gradeAroundHouseTool, + readSiteTerrainTool, + readTerrainContoursTool, + sampleTerrainLineTool, + shapeSiteTerrainTool, +} from '../agent-tools/terrain' +import { intersection, area as sharedArea } from '../lib/polygon-boolean' +import { segmentsIntersect } from '../lib/polygon-relations' +import { classifyEdges, edgeLength, outwardNormal, resolveFrontEdge } from '../lib/setback-envelope' +import { terrainBreakFacts, terrainBreaksOf, validateTerrainBreak } from '../lib/terrain-breaks' +import { diffuseHeights, RAISE_METRES_PER_STROKE } from '../lib/terrain-brush' +import { terrainContours } from '../lib/terrain-contours' +import { + createTerrainField, + DEFAULT_TERRAIN_SPACING, + heightAt, + normalAt, + quantize, + sampleRangeOver, + slopeAt, + type TerrainField, +} from '../lib/terrain-field' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import { planTerrainTileChanges } from '../lib/terrain-tile-changes' +import { terrainEditField } from '../lib/terrain-tile-write' +import { queryNodes } from '../runtime/node-queries' +import type { AnyNode, SiteNode } from '../schema' +import { TerrainBreakNode } from '../schema/nodes/terrain-break' +import { getLevelElevations } from '../services/storey' +import useLiveTerrain from '../store/use-live-terrain' +import { distance2D, pointInPolygon, polygonArea, polygonBounds, type Vec2 } from './plan-geometry' +import { addTerrainBreak, validateTerrainBreakPlacement } from './terrain-break' +import { + bankRunM, + convexHull, + type GradeLowLine, + type GradePad, + type GradeRetain, + gradeGround, +} from './terrain-grade' +import type { AgentOperation, SceneChanges, SceneNodes } from './types' +import { + type SlabSurface, + slabSurfaces, + UNGUARDED_DROP_THRESHOLD_M, +} from './unguarded-drop-observations' + +const MAX_SAMPLES = 20_000 +const MAX_EDIT_SAMPLES = 2_000_000 +const MAX_CONTOUR_VISITS = 2_000_000 +const readInput = z.strictObject(readSiteTerrainTool.input) +const lineInput = z.strictObject(sampleTerrainLineTool.input) +const contoursInput = z.strictObject(readTerrainContoursTool.input) +const shapeInput = z.strictObject(shapeSiteTerrainTool.input) +const padInput = z.strictObject(carveTerrainPadTool.input) +const underHouseInput = z.strictObject(describeTerrainUnderHouseTool.input) +const gradeInput = z.strictObject(gradeAroundHouseTool.input) + +type TerrainPoint = { x: number; z: number; yM: number; slopeDeg: number } +type TerrainEdge = { from: Vec2; to: Vec2; dropM: number; maxSlopeDeg: number } +type TerrainSample = TerrainPoint & { areaM2: number } + +export function parseInput( + schema: Schema, + input: unknown, +): z.output { + const parsed = schema.safeParse(input) + if (!parsed.success) refuse('invalid_input', parsed.error.message) + return parsed.data +} + +/** What a read says where nobody has shaped the ground: it is the datum plane. */ +const FLAT_GROUND_NOTE = + 'No relief is shaped on this site: the ground is the flat datum plane at y = 0. Relief is shaped with shape_site_terrain and carve_terrain_pad.' + +/** The sampling label of a flat-datum answer: nothing was sampled, the plane is the same everywhere. */ +const FLAT_SAMPLING = { + approximate: true, + method: 'flat_datum', + spacingM: 0, + heightStepM: 0, +} as const + +/** No authored ground means datum; an unreadable legacy field must not masquerade as flat. */ +export function groundOf(nodes: SceneNodes): { site: SiteNode; field: TerrainField | null } { + const sites = queryNodes(nodes, { type: 'site' }).filter( + (node): node is SiteNode => node.type === 'site', + ) + if (!sites.length) refuse('no_site', 'The scene has no site to read terrain from.') + if (sites.length > 1) + refuse('ambiguous_site', 'The scene has more than one site; its terrain is ambiguous.') + const site = sites[0] + if (!site) refuse('no_site', 'The scene has no site to read terrain from.') + const field = persistedTerrainFieldOf(site, nodes) + if ((!field && site.terrain !== undefined) || (field && !finiteField(field))) + refuse('no_terrain', 'The persisted terrain field of the site cannot be read.') + return { site, field } +} + +function finiteField(field: TerrainField): boolean { + const maxX = field.origin[0] + (field.cols - 1) * field.spacing + const maxZ = field.origin[1] + (field.rows - 1) * field.spacing + return ( + Number.isFinite(maxX) && + Number.isFinite(maxZ) && + field.heights.every((height) => Number.isFinite(height * field.step)) + ) +} + +/** A datum field wide enough to hold the footprint: every height is 0, so any spacing is exact. */ +function flatFieldOver(footprint: Vec2[]): TerrainField { + const bounds = polygonBounds(footprint) + const spacing = Math.max(DEFAULT_TERRAIN_SPACING, Math.max(bounds.width, bounds.depth) / 100) + return createTerrainField({ + origin: [bounds.minX - spacing, bounds.minZ - spacing], + spacing, + cols: Math.ceil(bounds.width / spacing) + 3, + rows: Math.ceil(bounds.depth / spacing) + 3, + }) +} + +export function pointOf(point: number[]): Vec2 { + const [x, z] = point + if (x === undefined || z === undefined || !Number.isFinite(x) || !Number.isFinite(z)) + refuse('invalid_input', 'A terrain point must be two finite coordinates [x,z].') + return [x, z] +} + +export function polygonEdges(polygon: Vec2[]): [Vec2, Vec2][] { + return polygon.map((from, index) => { + const to = polygon[(index + 1) % polygon.length] + if (!to) refuse('footprint_empty', 'The footprint has no next corner.') + return [from, to] + }) +} + +export function footprintOf(points: number[][]): Vec2[] { + if (points.length < 3) + refuse('footprint_empty', 'A footprint needs at least three corners enclosing area.') + if (points.length > 512) refuse('sampling_limit', 'A footprint can have at most 512 corners.') + const polygon = points.map(pointOf) + const edges = polygonEdges(polygon) + for (const [index, [from, to]] of edges.entries()) { + if (distance2D(from, to) === 0) refuse('invalid_polygon', 'The footprint has a collapsed edge.') + for (let next = index + 2; next < edges.length; next++) { + if (index === 0 && next === edges.length - 1) continue + const edge = edges[next] + if (edge && segmentsIntersect(from, to, edge[0], edge[1])) + refuse('invalid_polygon', 'The footprint intersects itself.') + } + } + const area = polygonArea(polygon) + if (!Number.isFinite(area)) refuse('invalid_polygon', 'The footprint area is not finite.') + if (area <= 1e-10) refuse('footprint_empty', 'The footprint encloses no measurable area.') + return polygon +} + +function requireBudget(count: number): void { + if (!Number.isFinite(count) || count > MAX_SAMPLES) + refuse( + 'sampling_limit', + `The request exceeds ${MAX_SAMPLES} terrain samples; use a larger cellM or stepM.`, + ) +} + +function samplePoint(field: TerrainField, point: Vec2): TerrainPoint { + const [x, z] = point + const yM = heightAt(field, x, z) + const slopeDeg = (slopeAt(field, x, z) * 180) / Math.PI + if (!Number.isFinite(yM) || !Number.isFinite(slopeDeg)) + refuse('no_terrain', 'The persisted terrain cannot produce finite ground facts.') + return { x, z, yM, slopeDeg } +} + +function segmentSteps(from: Vec2, to: Vec2, stepM: number): number { + return Math.ceil(distance2D(from, to) / stepM) +} + +function segmentPoints(from: Vec2, to: Vec2, steps: number): Vec2[] { + if (steps === 0) return [from] + return Array.from({ length: steps + 1 }, (_, index): Vec2 => { + if (index === 0) return from + if (index === steps) return to + const fraction = index / steps + return [from[0] + (to[0] - from[0]) * fraction, from[1] + (to[1] - from[1]) * fraction] + }) +} + +function gridFor(polygon: Vec2[], cellM: number) { + const bounds = polygonBounds(polygon) + const cols = Math.max(1, Math.ceil(bounds.width / cellM)) + const rows = Math.max(1, Math.ceil(bounds.depth / cellM)) + const edgeCount = polygonEdges(polygon).reduce( + (sum, [from, to]) => sum + segmentSteps(from, to, cellM) + 1, + 0, + ) + requireBudget(cols * rows + edgeCount + polygon.length) + return { ...bounds, cols, rows, widthM: bounds.width / cols, depthM: bounds.depth / rows } +} + +function interiorSamples( + field: TerrainField, + polygon: Vec2[], + grid: ReturnType, +): TerrainSample[] { + const samples: TerrainSample[] = [] + for (let row = 0; row < grid.rows; row++) { + for (let col = 0; col < grid.cols; col++) { + const point: Vec2 = [ + grid.minX + (col + 0.5) * grid.widthM, + grid.minZ + (row + 0.5) * grid.depthM, + ] + if (!pointInPolygon(point, polygon)) continue + samples.push({ ...samplePoint(field, point), areaM2: grid.widthM * grid.depthM }) + } + } + if (!samples.length) + refuse( + 'sampling_insufficient', + 'No interior midpoint was sampled; ground areas and mean slope are unknown. Use a finer cellM.', + ) + return samples +} + +function edgeSamples(field: TerrainField, polygon: Vec2[], cellM: number) { + const samples: TerrainPoint[] = [] + const edges: TerrainEdge[] = [] + for (const [from, to] of polygonEdges(polygon)) { + const points = segmentPoints(from, to, segmentSteps(from, to, cellM)).map((point) => + samplePoint(field, point), + ) + samples.push(...points) + edges.push({ + from, + to, + dropM: heightAt(field, from[0], from[1]) - heightAt(field, to[0], to[1]), + maxSlopeDeg: Math.max(...points.map((point) => point.slopeDeg)), + }) + } + return { samples, edges } +} + +export function samplingOf(field: TerrainField, method: string, sampleCount: number) { + return { + approximate: true, + method, + spacingM: field.spacing, + heightStepM: field.step, + sampleCount, + } +} + +function cornerOf(field: TerrainField, point: Vec2) { + const sampled = samplePoint(field, point) + const normal = normalAt(field, point[0], point[1]) + if (!normal.every(Number.isFinite)) + refuse('no_terrain', 'The persisted terrain cannot produce a finite ground normal.') + return { x: sampled.x, z: sampled.z, slopeDeg: sampled.slopeDeg, normal } +} + +function summarizeSamples(samples: TerrainPoint[], interior: TerrainSample[]) { + const minM = Math.min(...samples.map((point) => point.yM)) + const maxM = Math.max(...samples.map((point) => point.yM)) + const areaM2 = interior.reduce((sum, point) => sum + point.areaM2, 0) + if (!Number.isFinite(maxM - minM) || !Number.isFinite(areaM2) || areaM2 <= 0) + refuse( + 'sampling_insufficient', + 'Sampled relief or area is not representable; terrain facts are unknown.', + ) + return { + hasTerrain: true, + flat: minM === maxM, + reliefM: maxM - minM, + minM, + maxM, + datumM: 0, + slopeMeanDeg: interior.reduce( + (sum, point) => sum + point.slopeDeg * (point.areaM2 / areaM2), + 0, + ), + slopeMaxDeg: Math.max(...samples.map((point) => point.slopeDeg)), + areaAboveGradeM2: interior.reduce((sum, point) => sum + (point.yM > 0 ? point.areaM2 : 0), 0), + areaBelowGradeM2: interior.reduce((sum, point) => sum + (point.yM < 0 ? point.areaM2 : 0), 0), + } +} + +/** The facts of ground nobody has shaped: level at the datum over the whole footprint. */ +function flatSiteTerrain(footprint: Vec2[], cellM: number | undefined) { + return { + hasTerrain: false, + flat: true, + reliefM: 0, + minM: 0, + maxM: 0, + datumM: 0, + slopeMeanDeg: 0, + slopeMaxDeg: 0, + slopeAtCorners: footprint.map(([x, z]) => ({ x, z, slopeDeg: 0, normal: [0, 1, 0] })), + edgeDrops: polygonEdges(footprint).map(([from, to]) => ({ + from, + to, + dropM: 0, + maxSlopeDeg: 0, + })), + areaAboveGradeM2: 0, + areaBelowGradeM2: 0, + note: FLAT_GROUND_NOTE, + sampling: { ...FLAT_SAMPLING, sampleCount: 0, cellM: cellM ?? 0 }, + } +} + +export const readSiteTerrain: AgentOperation> = (nodes, raw) => { + const input = parseInput(readInput, raw) + const { site, field } = groundOf(nodes) + const footprint = footprintOf(input.footprint ?? site.polygon.points) + if (!field) return { result: flatSiteTerrain(footprint, input.cellM) } + const cellM = input.cellM ?? field.spacing + const interior = interiorSamples(field, footprint, gridFor(footprint, cellM)) + const boundary = edgeSamples(field, footprint, cellM) + const samples = [...interior, ...boundary.samples] + const slopeAtCorners = footprint.map((point) => cornerOf(field, point)) + return { + result: { + ...summarizeSamples(samples, interior), + breaks: terrainBreaksOf(site, nodes).map((terrainBreak) => + terrainBreakFacts(terrainBreak, field), + ), + slopeAtCorners, + edgeDrops: boundary.edges, + sampling: { + ...samplingOf(field, 'midpoint_grid_and_boundary', samples.length + slopeAtCorners.length), + cellM, + }, + }, + } +} + +export const sampleTerrainLine: AgentOperation> = (nodes, raw) => { + const input = parseInput(lineInput, raw) + const { site, field } = groundOf(nodes) + const from = pointOf(input.from) + const to = pointOf(input.to) + const stepM = input.stepM ?? field?.spacing ?? DEFAULT_TERRAIN_SPACING + const steps = segmentSteps(from, to, stepM) + requireBudget(steps + 1) + const points = segmentPoints(from, to, steps).map((point) => + field ? samplePoint(field, point) : { x: point[0], z: point[1], yM: 0, slopeDeg: 0 }, + ) + const actualStepM = steps ? distance2D(from, to) / steps : 0 + if (!field) + return { + result: { + points, + note: FLAT_GROUND_NOTE, + sampling: { ...FLAT_SAMPLING, sampleCount: points.length, stepM, actualStepM }, + }, + } + return { + result: { + points, + breaks: terrainBreaksOf(site, nodes).map((terrainBreak) => + terrainBreakFacts(terrainBreak, field), + ), + sampling: { + ...samplingOf(field, 'even_segment_samples', points.length), + stepM, + actualStepM, + }, + }, + } +} + +function requireContourBudget(field: TerrainField, intervalM: number): void { + const sampleCount = field.cols * field.rows + if (!Number.isSafeInteger(sampleCount) || sampleCount > MAX_CONTOUR_VISITS) + refuse( + 'contour_limit', + 'The contour extent exceeds 2,000,000 samples; request contours on a smaller terrain extent.', + ) + let minM = Infinity + let maxM = -Infinity + for (let row = 0; row < field.rows; row++) { + for (let col = 0; col < field.cols; col++) { + const height = heightAt( + field, + field.origin[0] + col * field.spacing, + field.origin[1] + row * field.spacing, + ) + minM = Math.min(minM, height) + maxM = Math.max(maxM, height) + } + } + const first = Math.ceil(minM / intervalM) + const last = Math.floor(maxM / intervalM) + const levelCount = Math.max(0, last - first + 1) + // The primitive silently returns [] past 400 intervals; never mistake that for no contours. + if ( + !Number.isSafeInteger(first) || + !Number.isSafeInteger(last) || + last - first > 400 || + levelCount * (field.cols - 1) * (field.rows - 1) > MAX_CONTOUR_VISITS + ) + refuse( + 'contour_limit', + 'The contour request exceeds 400 level intervals or 2,000,000 cell-level visits; use a larger intervalM.', + ) +} + +export const readTerrainContours: AgentOperation> = (nodes, raw) => { + const input = parseInput(contoursInput, raw) + const { site, field } = groundOf(nodes) + const lot = footprintOf(site.polygon.points) + const intervalM = input.intervalM ?? 1 + if (!field) + return { + result: { + datum: 0, + lines: [], + note: FLAT_GROUND_NOTE, + sampling: { ...FLAT_SAMPLING, sampleCount: 0, intervalM }, + }, + } + requireContourBudget(field, intervalM) + const lines = terrainContours(field, intervalM, lot).map(({ levelM, points }) => ({ + levelM, + points, + })) + const sampleCount = lines.reduce((sum, line) => sum + line.points.length, 0) + if (sampleCount > MAX_SAMPLES) + refuse( + 'contour_limit', + `The contour result exceeds ${MAX_SAMPLES} vertices; use a larger intervalM.`, + ) + return { + result: { + datum: 0, + lines, + breaks: terrainBreaksOf(site, nodes).map((terrainBreak) => + terrainBreakFacts(terrainBreak, field), + ), + sampling: { + ...samplingOf( + field, + field.terrainBreaks?.length + ? 'marching_squares_break_cells_omitted' + : 'marching_squares_midpoint_mask', + sampleCount, + ), + intervalM, + }, + }, + } +} + +export type ShapingArea = + | { kind: 'polygon'; polygon: Vec2[] } + | { kind: 'circle'; center: Vec2; radiusM: number } + +export type FieldSample = { index: number; point: Vec2 } + +function pointToSegmentDistance(point: Vec2, from: Vec2, to: Vec2): number { + const dx = to[0] - from[0] + const dz = to[1] - from[1] + const lengthSq = dx * dx + dz * dz + const t = + lengthSq === 0 + ? 0 + : Math.max(0, Math.min(1, ((point[0] - from[0]) * dx + (point[1] - from[1]) * dz) / lengthSq)) + return distance2D(point, [from[0] + dx * t, from[1] + dz * t]) +} + +export function distanceToPolygonEdge(point: Vec2, polygon: Vec2[]): number { + return Math.min( + ...polygonEdges(polygon).map(([from, to]) => pointToSegmentDistance(point, from, to)), + ) +} + +export function areaBounds(area: ShapingArea) { + if (area.kind === 'polygon') return polygonBounds(area.polygon) + const [x, z] = area.center + return { + minX: x - area.radiusM, + maxX: x + area.radiusM, + minZ: z - area.radiusM, + maxZ: z + area.radiusM, + } +} + +export function insideArea(area: ShapingArea, point: Vec2): boolean { + return area.kind === 'polygon' + ? pointInPolygon(point, area.polygon) + : distance2D(point, area.center) <= area.radiusM +} + +/** How far inside the area boundary a point sits; negative outside it. */ +export function depthInsideArea(area: ShapingArea, point: Vec2): number { + if (area.kind === 'circle') return area.radiusM - distance2D(point, area.center) + const edge = distanceToPolygonEdge(point, area.polygon) + return pointInPolygon(point, area.polygon, false) ? edge : -edge +} + +export function shapingAreaOf(area: z.infer['area']): ShapingArea { + if (Array.isArray(area)) return { kind: 'polygon', polygon: footprintOf(area) } + if (!Number.isFinite(area.radiusM) || area.radiusM <= 0) + refuse('invalid_input', 'A circle area needs a positive finite radiusM.') + return { kind: 'circle', center: pointOf([area.x, area.z]), radiusM: area.radiusM } +} + +export function propertyOf(site: SiteNode): Vec2[] { + return footprintOf(site.polygon.points) +} + +/** A crossing through both segments' interiors. Touching at a corner or + * running along the boundary is not a crossing: a pad may share the + * property line. (`segmentsIntersect` counts touching, which is what a + * self-intersection check wants and a containment check does not.) */ +function edgesCrossProperly(a: Vec2, b: Vec2, c: Vec2, d: Vec2): boolean { + const cross = (o: Vec2, p: Vec2, q: Vec2) => + (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]) + const abC = cross(a, b, c) + const abD = cross(a, b, d) + const cdA = cross(c, d, a) + const cdB = cross(c, d, b) + return abC * abD < 0 && cdA * cdB < 0 +} + +/** + * The whole area must sit on the property: vertices inside is not enough on a + * non-convex lot, so edges may not cross the boundary and no boundary corner + * may poke into the area either. + */ +export function requireInsideProperty(area: ShapingArea, property: Vec2[]): void { + const outside = () => + refuse('outside_property', 'The area reaches outside the site polygon; nothing was written.') + if (area.kind === 'circle') { + if (!pointInPolygon(area.center, property)) outside() + if (distanceToPolygonEdge(area.center, property) < area.radiusM - 1e-9) outside() + return + } + if (!area.polygon.every((point) => pointInPolygon(point, property))) outside() + for (const [from, to] of polygonEdges(area.polygon)) { + const midpoint: Vec2 = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2] + if (!pointInPolygon(midpoint, property)) outside() + for (const [edgeFrom, edgeTo] of polygonEdges(property)) + if (edgesCrossProperly(from, to, edgeFrom, edgeTo)) outside() + } + if (property.some((point) => pointInPolygon(point, area.polygon, false))) outside() +} + +export function fieldSamplesIn( + field: TerrainField, + bounds: { minX: number; minZ: number; maxX: number; maxZ: number }, +): FieldSample[] { + const range = sampleRangeOver(field, bounds.minX, bounds.minZ, bounds.maxX, bounds.maxZ) + if (!range) return [] + const samples: FieldSample[] = [] + for (let row = range.row0; row <= range.row1; row++) + for (let col = range.col0; col <= range.col1; col++) + samples.push({ + index: row * field.cols + col, + point: [field.origin[0] + col * field.spacing, field.origin[1] + row * field.spacing], + }) + return samples +} + +const metresOf = (field: TerrainField, quantized: number) => quantized * field.step + +/** Persist only changed tiles, leaving the legacy ground byte-for-byte intact. */ +export function terrainWriteOutcome( + site: SiteNode, + nodes: SceneNodes, + before: TerrainField, + heights: Int16Array, + result: Record, + extra?: Pick, +) { + const tiles = planTerrainTileChanges(site, nodes, before, { ...before, heights }) + if ( + !tiles.create?.length && + !tiles.update?.length && + !extra?.create?.length && + !extra?.delete?.length + ) + refuse('no_change', 'No terrain sample would move; nothing was written.') + useLiveTerrain.getState().end(site.id) + const changes: SceneChanges = { + ...tiles, + create: [...(tiles.create ?? []), ...(extra?.create ?? [])], + ...(extra?.delete?.length ? { delete: extra.delete } : {}), + } + return { result, changes } +} + +export function editingField( + site: SiteNode, + nodes: SceneNodes, + area: ShapingArea, + haloM = 0, +): TerrainField { + const bounds = areaBounds(area) + const rect = { + minX: bounds.minX - haloM, + minZ: bounds.minZ - haloM, + maxX: bounds.maxX + haloM, + maxZ: bounds.maxZ + haloM, + } + const count = + (Math.ceil((rect.maxX - rect.minX) / DEFAULT_TERRAIN_SPACING) + 2) * + (Math.ceil((rect.maxZ - rect.minZ) / DEFAULT_TERRAIN_SPACING) + 2) + if (!Number.isFinite(count) || count > MAX_EDIT_SAMPLES) + refuse( + 'sampling_limit', + `The edit exceeds ${MAX_EDIT_SAMPLES} terrain samples; use a smaller area.`, + ) + return terrainEditField(site, nodes, rect) +} + +function shapedHeight( + verb: z.infer['verb'], + currentM: number, + weight: number, + heightM: number, + smoothedM: number, +): number { + switch (verb) { + case 'flatten': + return currentM + (heightM - currentM) * weight + case 'raise': + return currentM + heightM * weight + case 'lower': + return currentM - heightM * weight + case 'smooth': + return currentM + (smoothedM - currentM) * weight + } +} + +/** + * The height a shaping verb works with, validated: flatten's target height + * (required), or the metres raise/lower move — direction comes from the verb, + * so a negative distance is meaningless. Defaults to the sculpt stroke's metre. + */ +function shapeHeightMOf(input: z.infer): number { + if (input.verb === 'flatten' && input.heightM === undefined) + refuse('invalid_input', 'flatten needs heightM, the height to flatten to.') + if ( + (input.verb === 'raise' || input.verb === 'lower') && + input.heightM !== undefined && + input.heightM < 0 + ) + refuse( + 'invalid_input', + 'heightM for raise/lower is the metres to move, 0 or more; the verb gives the direction.', + ) + return input.heightM ?? RAISE_METRES_PER_STROKE +} + +/** The shaped field plus the height range it moved, over the touched samples. */ +function applyShaping( + field: TerrainField, + area: ShapingArea, + samples: FieldSample[], + input: z.infer, + heightM: number, +) { + const strength = input.strength ?? 1 + const softness = input.softness ?? 0 + const smoothed = input.verb === 'smooth' ? diffuseHeights(field) : null + const heights = new Int16Array(field.heights) + let beforeMin = Infinity + let beforeMax = -Infinity + let afterMin = Infinity + let afterMax = -Infinity + let changedSamples = 0 + for (const sample of samples) { + const beforeQ = field.heights[sample.index] ?? 0 + const edgeWeight = + softness > 0 ? Math.max(0, Math.min(1, depthInsideArea(area, sample.point) / softness)) : 1 + const nextM = shapedHeight( + input.verb, + metresOf(field, beforeQ), + strength * edgeWeight, + heightM, + metresOf(field, smoothed?.[sample.index] ?? beforeQ), + ) + const nextQ = quantize(field, nextM) + heights[sample.index] = nextQ + if (nextQ !== beforeQ) changedSamples++ + beforeMin = Math.min(beforeMin, metresOf(field, beforeQ)) + beforeMax = Math.max(beforeMax, metresOf(field, beforeQ)) + afterMin = Math.min(afterMin, metresOf(field, nextQ)) + afterMax = Math.max(afterMax, metresOf(field, nextQ)) + } + return { + heights, + changedSamples, + beforeMinMaxM: { minM: beforeMin, maxM: beforeMax }, + afterMinMaxM: { minM: afterMin, maxM: afterMax }, + } +} + +export const shapeSiteTerrain: AgentOperation> = (nodes, raw) => { + const input = parseInput(shapeInput, raw) + const { site } = groundOf(nodes) + const property = propertyOf(site) + const area = shapingAreaOf(input.area) + if (input.scope !== 'context') requireInsideProperty(area, property) + const field = editingField(site, nodes, area, input.verb === 'smooth' ? 4 : 0.5) + const heightM = shapeHeightMOf(input) + const samples = fieldSamplesIn(field, areaBounds(area)).filter( + (sample) => + insideArea(area, sample.point) && + (input.scope === 'context' || pointInPolygon(sample.point, property)), + ) + if (!samples.length) + refuse( + 'no_change', + 'The area holds no terrain sample inside the property; nothing was written.', + ) + const shaped = applyShaping(field, area, samples, input, heightM) + return terrainWriteOutcome(site, nodes, field, shaped.heights, { + changedSamples: shaped.changedSamples, + beforeMinMaxM: shaped.beforeMinMaxM, + afterMinMaxM: shaped.afterMinMaxM, + touchedM2: samples.length * field.spacing * field.spacing, + sampling: samplingOf(field, 'field_samples_in_area', samples.length), + }) +} + +function retainingHeights(field: TerrainField, pad: Vec2[], padHeightM: number) { + return polygonEdges(pad).map(([from, to]) => { + const points = segmentPoints(from, to, segmentSteps(from, to, field.spacing)) + const highest = Math.max(...points.map((point) => heightAt(field, point[0], point[1]))) + return { from, to, heightM: Math.max(0, highest - padHeightM) } + }) +} + +function steepestBlendSlopeDeg( + after: TerrainField, + padArea: ShapingArea, + ring: FieldSample[], +): number { + const outside = ring.filter((sample) => !insideArea(padArea, sample.point)) + const points = outside.length + ? outside.map((sample) => sample.point) + : polygonEdges(padArea.kind === 'polygon' ? padArea.polygon : []).flatMap(([from, to]) => + segmentPoints(from, to, segmentSteps(from, to, after.spacing)), + ) + if (!points.length) return 0 + return points.reduce( + (max, point) => Math.max(max, (slopeAt(after, point[0], point[1]) * 180) / Math.PI), + 0, + ) +} + +/** Samples in the pad plus its blend ring, clipped to the property. */ +function padRingSamples( + field: TerrainField, + padArea: { kind: 'polygon'; polygon: Vec2[] }, + blendM: number, + property: Vec2[] | null, +) { + const bounds = polygonBounds(padArea.polygon) + const ring = fieldSamplesIn(field, { + minX: bounds.minX - blendM, + minZ: bounds.minZ - blendM, + maxX: bounds.maxX + blendM, + maxZ: bounds.maxZ + blendM, + }).filter((sample) => !property || pointInPolygon(sample.point, property)) + const padSamples = ring.filter((sample) => insideArea(padArea, sample.point)) + if (!padSamples.length) + refuse( + 'pad_too_small', + 'No field sample falls inside the pad; at this spacing the pad cannot be levelled.', + ) + return { ring, padSamples } +} + +/** The carved field plus its earthwork, integrated sample by sample. */ +function carvedHeights( + field: TerrainField, + padArea: ShapingArea, + ring: FieldSample[], + targetQ: number, + blendM: number, + property: Vec2[], +) { + const padHeightM = metresOf(field, targetQ) + const heights = new Int16Array(field.heights) + const cellM2 = field.spacing * field.spacing + let cutVolumeM3 = 0 + let fillVolumeM3 = 0 + let changedSamples = 0 + for (const sample of ring) { + const beforeQ = field.heights[sample.index] ?? 0 + let nextQ = beforeQ + if (insideArea(padArea, sample.point)) { + nextQ = targetQ + } else if (blendM > 0) { + const depth = depthInsideArea(padArea, sample.point) + if (depth > -blendM) { + const weight = 1 + depth / blendM + const blendedQ = quantize( + field, + metresOf(field, beforeQ) + (padHeightM - metresOf(field, beforeQ)) * weight, + ) + // The ring only cuts: a sample below pad height would be raised by + // the lerp, and raising ground outside the pad — filling a dip the + // pad never asked about — is not this tool's to do. + nextQ = Math.min(beforeQ, blendedQ) + } + } + heights[sample.index] = nextQ + const movedM = metresOf(field, nextQ - beforeQ) + if (movedM !== 0) changedSamples++ + if (pointInPolygon(sample.point, property)) { + if (movedM < 0) cutVolumeM3 += -movedM * cellM2 + else fillVolumeM3 += movedM * cellM2 + } + } + return { heights, cutVolumeM3, fillVolumeM3, changedSamples } +} + +function closedCounterclockwise(pad: Vec2[]): Vec2[] { + const signedArea = pad.reduce((sum, from, index) => { + const to = pad[(index + 1) % pad.length] + return to ? sum + from[0] * to[1] - to[0] * from[1] : sum + }, 0) + const ordered = signedArea >= 0 ? pad : [...pad].reverse() + const first = ordered[0] + return first ? [...ordered, first] : ordered +} + +function sharpPadEarthwork(samples: TerrainSample[], property: Vec2[], padHeightM: number) { + const lotSamples = samples.filter((sample) => pointInPolygon([sample.x, sample.z], property)) + const cutVolumeM3 = lotSamples.reduce( + (sum, sample) => sum + Math.max(0, sample.yM - padHeightM) * sample.areaM2, + 0, + ) + const fillVolumeM3 = lotSamples.reduce( + (sum, sample) => sum + Math.max(0, padHeightM - sample.yM) * sample.areaM2, + 0, + ) + return { + cutVolumeM3, + fillVolumeM3, + netM3: cutVolumeM3 - fillVolumeM3, + sampleCount: lotSamples.length, + } +} + +function sharpPadEdgeHeights(field: TerrainField, pad: Vec2[], padHeightM: number) { + return polygonEdges(pad).map(([from, to]) => ({ + from, + to, + heightM: Math.max( + ...segmentPoints(from, to, segmentSteps(from, to, field.spacing)).map(([x, z]) => + Math.abs(heightAt(field, x, z) - padHeightM), + ), + ), + })) +} + +type PadEdgeKind = 'cliff' | 'retaining' | 'soil' + +function sharpPadOutcome( + nodes: SceneNodes, + input: z.infer, + site: SiteNode, + pad: Vec2[], + context: Parameters[2], + kind: PadEdgeKind, +) { + if (input.blendM) refuse('invalid_input', 'Sharp pad edges cannot also have a blendM slope.') + const field = persistedTerrainFieldOf(site, nodes) ?? flatFieldOver(pad) + const samples = interiorSamples(field, pad, gridFor(pad, DEFAULT_TERRAIN_SPACING)) + const boundary = edgeSamples(field, pad, DEFAULT_TERRAIN_SPACING) + const highestM = Math.max( + ...samples.map((sample) => sample.yM), + ...boundary.samples.map((sample) => sample.yM), + ) + const padHeightM = input.padHeightM ?? highestM - (input.padFromHighestM ?? 0) + const { sampleCount, ...earthwork } = sharpPadEarthwork(samples, propertyOf(site), padHeightM) + const retainingHeightM = sharpPadEdgeHeights(field, pad, padHeightM) + // The lattice write refuses a pad that moves nothing, to the half centimetre of its height step; + // the face of a pad that stands on the ground would be a break of no height. + if ( + kind === 'soil' && + earthwork.cutVolumeM3 + earthwork.fillVolumeM3 < 0.005 * polygonArea(pad) && + retainingHeightM.every((edge) => edge.heightM <= 0.005) + ) + refuse('no_change', 'The ground already stands at the pad height; nothing was written.') + const outcome = addTerrainBreak( + nodes, + { + line: closedCounterclockwise(pad), + kind, + left: padHeightM, + right: 'ground', + scope: input.scope, + }, + context, + ) + useLiveTerrain.getState().end(site.id) + return { + ...outcome, + result: { + ...earthwork, + padAreaM2: polygonArea(pad), + padHeightM, + maxSlopeIntoPadDeg: retainingHeightM.some((edge) => edge.heightM > 0) ? 90 : 0, + retainingHeightM, + changedSamples: 0, + breaks: [outcome.result], + sampling: samplingOf(field, 'midpoint_plan_area_integral', sampleCount), + }, + } +} + +/** The write lattice has a sample in the pad: the contract of a pad, whatever its edge. */ +function padHoldsLatticeSample(pad: Vec2[]): boolean { + const bounds = polygonBounds(pad) + const step = DEFAULT_TERRAIN_SPACING + for (let ix = Math.ceil(bounds.minX / step); ix <= Math.floor(bounds.maxX / step); ix++) + for (let iz = Math.ceil(bounds.minZ / step); iz <= Math.floor(bounds.maxZ / step); iz++) + if (pointInPolygon([ix * step, iz * step], pad)) return true + return false +} + +function padIsConvex(pad: Vec2[]): boolean { + try { + validateTerrainBreak({ line: closedCounterclockwise(pad), left: 0, right: 'ground' }) + return true + } catch { + return false + } +} + +const LATTICE_EDGE_NOTE = + 'blendM is 0, so the pad edge is a vertical step; this pad could not be written as an exact soil face, so the step is written on the 0.5 m lattice: the ground between the pad height and the original passes through lattice triangles up to one cell wide, not along the pad line. A convex pad that crosses no other terrain break gets an exact soil face.' + +/** + * A zero-run slope is a vertical earth face: a convex pad with blendM 0 is written as an exact + * closed break at the pad height, ground outside, with a soil face. A pad that cannot be (not + * convex, or its break would cross another) keeps the lattice write and says so. + */ +function soilPadOutcome( + nodes: SceneNodes, + input: z.infer, + site: SiteNode, + pad: Vec2[], + context: Parameters[2], +): { outcome: ReturnType } | { reason: string } { + if (!padIsConvex(pad)) return { reason: 'non_convex_pad' } + try { + return { outcome: sharpPadOutcome(nodes, input, site, pad, context, 'soil') } + } catch (error) { + if (!isAgentRefusal(error)) throw error + // A refusal the lattice write would meet too is its own: it surfaces from there. + return { reason: error.code } + } +} + +export const carveTerrainPad: AgentOperation> = (nodes, raw, context) => { + const input = parseInput(padInput, raw) + const { site } = groundOf(nodes) + const property = propertyOf(site) + const pad = footprintOf(input.pad) + const padArea: { kind: 'polygon'; polygon: Vec2[] } = { kind: 'polygon', polygon: pad } + if (input.scope !== 'context') requireInsideProperty(padArea, property) + if ((input.padHeightM === undefined) === (input.padFromHighestM === undefined)) + refuse('invalid_input', 'Give exactly one of padHeightM or padFromHighestM.') + if (input.padFromHighestM !== undefined && input.padFromHighestM < 0) + refuse('invalid_input', 'padFromHighestM is a depth below the highest ground, 0 or more.') + if (input.edges === 'cliff' || input.edges === 'retaining') + return sharpPadOutcome(nodes, input, site, pad, context, input.edges) + const blendM = input.blendM ?? 0 + let latticeEdge: Record | undefined + if (blendM === 0) { + if (!padHoldsLatticeSample(pad)) + refuse( + 'pad_too_small', + 'No field sample falls inside the pad; at this spacing the pad cannot be levelled.', + ) + const soil = soilPadOutcome(nodes, input, site, pad, context) + if ('outcome' in soil) return soil.outcome + latticeEdge = { + kind: 'lattice_step', + exact: false, + reason: soil.reason, + resolutionM: DEFAULT_TERRAIN_SPACING, + note: LATTICE_EDGE_NOTE, + } + } + const field = editingField(site, nodes, padArea, blendM + 0.5) + const { ring, padSamples } = padRingSamples( + field, + padArea, + blendM, + input.scope === 'context' ? null : property, + ) + const highestM = padSamples.reduce( + (max, sample) => Math.max(max, metresOf(field, field.heights[sample.index] ?? 0)), + -Infinity, + ) + const targetQ = quantize(field, input.padHeightM ?? highestM - (input.padFromHighestM ?? 0)) + const padHeightM = metresOf(field, targetQ) + const carved = carvedHeights(field, padArea, ring, targetQ, blendM, property) + const after = { ...field, heights: carved.heights } + return terrainWriteOutcome(site, nodes, field, carved.heights, { + cutVolumeM3: carved.cutVolumeM3, + fillVolumeM3: carved.fillVolumeM3, + netM3: carved.cutVolumeM3 - carved.fillVolumeM3, + padAreaM2: polygonArea(pad), + padHeightM, + maxSlopeIntoPadDeg: steepestBlendSlopeDeg(after, padArea, ring), + retainingHeightM: retainingHeights(field, pad, padHeightM), + changedSamples: carved.changedSamples, + sampling: samplingOf(field, 'quantized_sample_integral', ring.length), + ...(latticeEdge ? { edge: latticeEdge } : {}), + }) +} + +const GRADE_DEFAULTS = { padBelowSlabM: 0.15, marginM: 1, run: 2, reachM: 15 } as const + +export type GradeInput = z.infer +type ResolvedPad = { + levelId?: string + slabId?: string + slabTopM?: number + outline: Vec2[] + heightM: number + marginM: number +} + +/** One pad: a level's largest slab, or a given footprint with its height. */ +function resolveGradePad( + nodes: SceneNodes, + surfaces: () => SlabSurface[], + want: { + levelId?: string + footprint?: number[][] + padHeightM?: number + padBelowSlabM?: number + marginM?: number + }, + defaults: { padBelowSlabM: number; marginM: number }, +): ResolvedPad { + if (want.levelId !== undefined && want.footprint !== undefined) + refuse('invalid_input', 'Give a levelId or a footprint, not both.') + const marginM = want.marginM ?? defaults.marginM + if (want.footprint !== undefined) { + if (want.padHeightM === undefined) + refuse( + 'invalid_input', + 'A given footprint has no slab to take the pad height from; give padHeightM.', + ) + return { outline: footprintOf(want.footprint), heightM: want.padHeightM, marginM } + } + const all = surfaces() + const levelId = houseLevelId(nodes, all, want.levelId) + const surface = largestSlabOn(all, levelId) + const framed = siteFrameFootprint(nodes, surface) + return { + levelId, + slabId: surface.slab.id, + slabTopM: framed.slabTopM, + outline: framed.footprint, + heightM: want.padHeightM ?? framed.slabTopM - (want.padBelowSlabM ?? defaults.padBelowSlabM), + marginM, + } +} + +/** Two outlines sharing more than this share of the smaller one stand one over the other. */ +const STACKED_PADS_SHARE = 0.1 + +/** + * Pads are the levels of a split-level house, side by side. Storeys one over the other are not: + * a sample follows the nearest outline, so the upper storey's pad would win over the whole plan + * and the ground floor would be buried under a platform at the upper floor's height. + */ +function requirePadsSideBySide(pads: ResolvedPad[]): void { + for (const [index, pad] of pads.entries()) + for (const other of pads.slice(index + 1)) { + const shared = sharedArea(intersection(pad.outline, other.outline)) + const smaller = Math.min(polygonArea(pad.outline), polygonArea(other.outline)) + if (shared > STACKED_PADS_SHARE * smaller) { + const name = (each: ResolvedPad) => each.levelId ?? 'a footprint' + refuse( + 'invalid_input', + `The outlines of ${name(pad)} and ${name(other)} stand one over the other (${shared.toFixed(1)} m2 in common): pads are the levels of a split-level house, side by side. Storeys one over the other share one seat, the level of the building that stands on the ground.`, + ) + } + } +} + +const alongOf = (point: Vec2, normal: Vec2) => point[0] * normal[0] + point[1] * normal[1] + +/** The straight edge a band grades along: its normal (from the house toward it) and where it stands. */ +function resolveGradeEdge( + site: SiteNode, + property: Vec2[], + outline: Vec2[], + edge: NonNullable, +) { + if ([edge.facing, edge.direction, edge.line].filter((given) => given !== undefined).length !== 1) + refuse('invalid_input', 'Give exactly one of facing, direction or line for an edge.') + let normal: Vec2 + let role: string | undefined + let lineOffsetM: number | undefined + if (edge.facing !== undefined) { + const roles = classifyEdges( + property, + resolveFrontEdge(property, site.frontEdge, site.northRotation), + site.streetEdges, + ) + const longest = roles + .map((edgeRole, index) => ({ edgeRole, index })) + .filter(({ edgeRole }) => edgeRole === edge.facing) + .sort((a, b) => edgeLength(property, b.index) - edgeLength(property, a.index))[0] + if (!longest) refuse('invalid_input', `The lot has no ${edge.facing} edge.`) + const [x, z] = outwardNormal(property, longest.index) + normal = [x, z] + role = edge.facing + } else if (edge.direction !== undefined) { + const [dx, dz] = edge.direction as [number, number] + const length = Math.hypot(dx, dz) + if (length < 1e-9) + refuse('invalid_input', 'The edge direction needs two coordinates that are not both zero.') + normal = [dx / length, dz / length] + } else { + const [from, to] = edge.line as [number[], number[]] + const dx = (to[0] as number) - (from[0] as number) + const dz = (to[1] as number) - (from[1] as number) + const length = Math.hypot(dx, dz) + if (length < 1e-9) refuse('invalid_input', 'The edge line needs two different points.') + const perpendicular: Vec2 = [-dz / length, dx / length] + const centroid: Vec2 = [ + outline.reduce((sum, p) => sum + p[0], 0) / outline.length, + outline.reduce((sum, p) => sum + p[1], 0) / outline.length, + ] + const offset = alongOf([from[0] as number, from[1] as number], perpendicular) + normal = + alongOf(centroid, perpendicular) > offset + ? [-perpendicular[0], -perpendicular[1]] + : perpendicular + lineOffsetM = alongOf([from[0] as number, from[1] as number], normal) + } + const frontM = Math.min(...outline.map((point) => alongOf(point, normal))) + const supportM = Math.max(...outline.map((point) => alongOf(point, normal))) + if (lineOffsetM !== undefined && lineOffsetM < supportM - 1e-6) + refuse( + 'invalid_input', + 'The edge line cuts across the house; it must lie on or beyond the outline.', + ) + return { normal, frontM, edgeM: lineOffsetM ?? supportM, role } +} + +const GRADE_WALL_SOURCE = 'grade_around_house' + +/** The ring of a convex outline offset by `marginM`: straight beside each edge, an arc at each corner. */ +function offsetRing(hull: Vec2[], marginM: number): Vec2[] { + if (marginM <= 0) return hull + const count = hull.length + const normalOf = (index: number): Vec2 => { + const from = hull[index] as Vec2 + const to = hull[(index + 1) % count] as Vec2 + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + return [(to[1] - from[1]) / length, -(to[0] - from[0]) / length] + } + const ring: Vec2[] = [] + for (let i = 0; i < count; i++) { + const before = normalOf((i + count - 1) % count) + const after = normalOf(i) + const start = Math.atan2(before[1], before[0]) + let end = Math.atan2(after[1], after[0]) + while (end < start) end += 2 * Math.PI + const steps = Math.max(1, Math.ceil((end - start) / (Math.PI / 12))) + const corner = hull[i] as Vec2 + for (let k = 0; k <= steps; k++) { + const angle = start + ((end - start) * k) / steps + ring.push([corner[0] + marginM * Math.cos(angle), corner[1] + marginM * Math.sin(angle)]) + } + } + return ring +} + +/** The faces a grading of this outline left on the site: the breaks it tagged with the outline. */ +export function gradeWallsOf(nodes: SceneNodes, site: SiteNode, footprint: Vec2[]): string[] { + const source = `${GRADE_WALL_SOURCE}:${gradeWallKey({ outline: footprint, heightM: 0, marginM: 0 })}` + return queryNodes(nodes, { type: 'terrain-break', parentId: site.id }) + .filter((node) => node.metadata?.source === source) + .map((node) => node.id) +} + +function gradeWallKey(pad: ResolvedPad): string { + return ( + pad.levelId ?? + `footprint:${pad.outline.map((p) => `${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(';')}` + ) +} + +/** The part of a convex or concave polygon on one side of a line `along(point) = offset` (Sutherland–Hodgman). */ +function clipPolygonAlong( + polygon: Vec2[], + normal: Vec2, + offset: number, + keep: 'below' | 'above', +): Vec2[] { + const sign = keep === 'below' ? 1 : -1 + const depth = (point: Vec2) => sign * (alongOf(point, normal) - offset) + const out: Vec2[] = [] + polygon.forEach((point, i) => { + const next = polygon[(i + 1) % polygon.length] as Vec2 + const here = depth(point) + const there = depth(next) + if (here <= 0) out.push(point) + if ((here < 0 && there > 0) || (here > 0 && there < 0)) { + const t = here / (here - there) + out.push([point[0] + (next[0] - point[0]) * t, point[1] + (next[1] - point[1]) * t]) + } + }) + return out +} + +/** A ring's corners with repeats and the closing repeat dropped, counter-clockwise in the site frame. */ +function counterClockwise(ring: Vec2[]): Vec2[] { + const corners = ring.filter((point, i) => { + const previous = ring[(i + ring.length - 1) % ring.length] as Vec2 + return Math.hypot(point[0] - previous[0], point[1] - previous[1]) > 1e-9 + }) + const area = corners.reduce((sum, a, i) => { + const b = corners[(i + 1) % corners.length] as Vec2 + return sum + a[0] * b[1] - b[0] * a[1] + }, 0) + return area < 0 ? corners.reverse() : corners +} + +/** + * The wall as a terrain-break. The pad is the numeric side (its whole region is the one plane), the + * batter side is the ground the tiles describe: the face stands between them where the two heights differ. + * Around a house the break is a ring (the convex hull, offset). Along a band it is a closed ring around + * the pad strip, the strip clipped to `clip` (the property, or the written region), so the pad is level + * across the lot between the strip's front and its edge and nowhere else. + */ +function gradeWallBreak( + site: SiteNode, + clip: Vec2[], + pad: GradePad, + key: string, + band: { normal: Vec2; frontM: number; edgeM: number } | undefined, +): TerrainBreakNode { + const metadata = { source: `${GRADE_WALL_SOURCE}:${key}` } + let ring: Vec2[] + if (!band) { + if (pad.outline.length < 3) + refuse( + 'unsupported_geometry', + 'The outline is a line or a point; a wall has no ring to stand on.', + ) + ring = offsetRing(pad.outline, pad.marginM) + } else { + const rear = clipPolygonAlong(clip, band.normal, band.edgeM + pad.marginM, 'below') + const strip = counterClockwise( + clipPolygonAlong(rear, band.normal, band.frontM - pad.marginM, 'above'), + ) + if (strip.length < 3) refuse('invalid_input', 'The pad strip does not cross the property.') + const convex = strip.every((a, i) => { + const b = strip[(i + 1) % strip.length] as Vec2 + return strip.every( + (point) => (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]) >= -1e-9, + ) + }) + if (!convex) + refuse( + 'unsupported_geometry', + 'The pad strip is not convex across this lot, so its wall cannot be one terrain-break ring; grade without exactWall.', + ) + ring = strip + } + return TerrainBreakNode.parse({ + parentId: site.id, + line: [...ring, ring[0]], + kind: 'retaining', + left: pad.heightM, + right: 'ground', + metadata, + }) +} + +function lineLengthM(line: number[][]): number { + return line + .slice(1) + .reduce( + (sum, to, i) => + sum + + Math.hypot( + (to[0] as number) - (line[i]?.[0] as number), + (to[1] as number) - (line[i]?.[1] as number), + ), + 0, + ) +} + +/** + * Grade the ground around a house: a pad at the house's height, a batter to the ground that was there or to + * a lawn, both as functions of the distance to the outline (terrain-grade.ts); one pad per level, a straight + * band across the lot instead of the ring, and a wall as a real terrain-break. The footprint is read the way + * describe_terrain_under_house reads it; the write is the tile write every terrain tool shares. + */ +export const gradeAroundHouse: AgentOperation = (nodes, raw) => + gradeHouse(nodes, parseInput(gradeInput, raw)) + +/** What a caller that seats a house adds to the grading the tool's own input describes. */ +export type GradeExtras = { + /** The pad falls away from the walls by this many metres per metre (terrain-grade `padFallPerM`). */ + padFallPerM?: number + /** The pad and its batter only cut (terrain-grade `cutOnly`). */ + cutOnly?: boolean + /** Further pads graded with the house's, each on its own outline (an apron before a wall). */ + morePads?: GradePad[] + /** A low line round the pad's high side (terrain-grade `lowLine`). */ + lowLine?: GradeLowLine + /** The high side is held by a face, not battered back (terrain-grade `retain`): the face is a terrain break on the outline's hull. */ + retain?: GradeRetain + /** Faces an earlier seating of this outline left are taken away, whether or not this one makes a face. */ + replaceWalls?: boolean +} + +/** grade_around_house's grading, for the tool and for an operation that seats a house first. */ +export function gradeHouse(nodes: SceneNodes, input: GradeInput, extras: GradeExtras = {}) { + const { site } = groundOf(nodes) + const property = propertyOf(site) + const scope = input.scope ?? 'lot' + if (input.pads !== undefined) { + if ( + input.levelId !== undefined || + input.footprint !== undefined || + input.padHeightM !== undefined + ) + refuse( + 'invalid_input', + 'pads gives each pad its own level, footprint and height; leave the top-level levelId, footprint and padHeightM out.', + ) + if (input.pads.some((pad) => pad.levelId === undefined && pad.footprint === undefined)) + refuse('invalid_input', 'Each pad needs a levelId or a footprint.') + const levels = input.pads.flatMap((pad) => (pad.levelId === undefined ? [] : [pad.levelId])) + if (new Set(levels).size !== levels.length) + refuse('invalid_input', 'Two pads name the same level.') + } + if (input.exactWall && !input.wallM) refuse('invalid_input', 'An exact wall needs wallM above 0.') + const wanted = input.pads ?? [ + { levelId: input.levelId, footprint: input.footprint, padHeightM: input.padHeightM }, + ] + if (wanted.length > 1 && (input.edge !== undefined || input.exactWall)) + refuse('invalid_input', 'edge and exactWall take one pad; pads has several.') + const defaults = { + padBelowSlabM: input.padBelowSlabM ?? GRADE_DEFAULTS.padBelowSlabM, + marginM: input.marginM ?? GRADE_DEFAULTS.marginM, + } + let surfaces: SlabSurface[] | undefined + const surfacesOf = () => { + surfaces ??= slabSurfaces(nodes as Record) + return surfaces + } + const pads = wanted.map((want) => resolveGradePad(nodes, surfacesOf, want, defaults)) + requirePadsSideBySide(pads) + if (scope !== 'context') + for (const pad of pads) + requireInsideProperty({ kind: 'polygon', polygon: pad.outline }, property) + const run = input.run ?? GRADE_DEFAULTS.run + const reachM = input.reachM ?? GRADE_DEFAULTS.reachM + const band = input.edge + ? resolveGradeEdge(site, property, (pads[0] as ResolvedPad).outline, input.edge) + : undefined + const lawn = input.upperLevelM !== undefined + const lotWide = band !== undefined || (lawn && scope !== 'context') + const maxMarginM = Math.max( + ...pads.map((pad) => pad.marginM), + ...(extras.morePads ?? []).map((pad) => pad.marginM), + ) + const outlinePoints = [ + ...pads.flatMap((pad) => pad.outline), + ...(extras.morePads ?? []).flatMap((pad) => pad.outline), + ] + const lotBounds = polygonBounds(property) + const reachPad = scope === 'context' ? reachM + maxMarginM : 0 + const bounds = lotWide + ? { + minX: lotBounds.minX - reachPad, + minZ: lotBounds.minZ - reachPad, + maxX: lotBounds.maxX + reachPad, + maxZ: lotBounds.maxZ + reachPad, + } + : polygonBounds(outlinePoints) + const field = editingField( + site, + nodes, + { + kind: 'polygon', + polygon: [ + [bounds.minX, bounds.minZ], + [bounds.maxX, bounds.minZ], + [bounds.maxX, bounds.maxZ], + [bounds.minX, bounds.maxZ], + ], + }, + lotWide ? 0.5 : maxMarginM + reachM + 0.5, + ) + const metresOf = (heightM: number) => quantize(field, heightM) * field.step + let gradePads: GradePad[] = [ + ...pads.map((pad) => ({ + outline: pad.outline, + heightM: metresOf(pad.heightM), + marginM: pad.marginM, + ...(extras.cutOnly ? { cutOnly: true } : {}), + })), + ...(extras.morePads ?? []).map((pad) => ({ ...pad, heightM: metresOf(pad.heightM) })), + ] + const upperLevelM = lawn ? metresOf(input.upperLevelM as number) : undefined + let wall: TerrainBreakNode | undefined + let replaced: string[] = [] + if (input.exactWall || extras.retain || extras.replaceWalls) { + const key = gradeWallKey(pads[0] as ResolvedPad) + replaced = queryNodes(nodes, { type: 'terrain-break', parentId: site.id }) + .filter( + (node) => + node.type === 'terrain-break' && + node.parentId === site.id && + node.metadata?.source === `${GRADE_WALL_SOURCE}:${key}`, + ) + .map((node) => node.id) + } + if (extras.retain) { + // The face stands on the hull of the outline, `atM` beyond it: a break is a convex ring. + const [pad, ...more] = gradePads as [GradePad, ...GradePad[]] + const hull = convexHull(pad.outline) + gradePads = [{ ...pad, outline: hull }, ...more] + wall = gradeWallBreak( + site, + property, + { ...pad, outline: hull, marginM: extras.retain.atM }, + gradeWallKey(pads[0] as ResolvedPad), + undefined, + ) + validateTerrainBreakPlacement( + // biome-ignore lint/plugin: This pass needs the original scene record keys, including malformed records. + Object.fromEntries(Object.entries(nodes).filter(([id]) => !replaced.includes(id))), + site, + wall, + scope, + ) + } else if (input.exactWall) { + const pad = gradePads[0] as GradePad + const key = gradeWallKey(pads[0] as ResolvedPad) + if (!band) gradePads = [{ ...pad, outline: convexHull(pad.outline) }] + const region: Vec2[] = [ + [bounds.minX, bounds.minZ], + [bounds.maxX, bounds.minZ], + [bounds.maxX, bounds.maxZ], + [bounds.minX, bounds.maxZ], + ] + wall = gradeWallBreak( + site, + scope === 'context' ? region : property, + gradePads[0] as GradePad, + key, + band, + ) + validateTerrainBreakPlacement( + // biome-ignore lint/plugin: This pass needs the original scene record keys, including malformed records. + Object.fromEntries(Object.entries(nodes).filter(([id]) => !replaced.includes(id))), + site, + wall, + scope, + ) + } + const outcome = gradeGround( + field, + { + pads: gradePads, + band, + run, + reachM, + riserM: input.terraceRiserM, + wallM: input.wallM, + upperLevelM, + lawnToEdge: lawn && scope !== 'context', + exactWall: wall !== undefined, + region: lotWide ? bounds : undefined, + padFallPerM: extras.padFallPerM, + retain: extras.retain, + lowLine: extras.lowLine, + }, + scope === 'context' ? () => true : (point) => pointInPolygon(point, property), + ) + const cellM2 = field.spacing * field.spacing + const treadM = input.terraceRiserM ? run * input.terraceRiserM : undefined + const bankRun = lawn + ? Math.max( + ...gradePads.map((pad) => + bankRunM( + Math.abs((upperLevelM as number) - pad.heightM) - (input.wallM ?? 0), + run, + input.terraceRiserM, + ), + ), + ) + : 0 + const padFacts = pads.map((pad, index) => ({ + ...(pad.levelId !== undefined + ? { levelId: pad.levelId, slabId: pad.slabId, slabTopM: pad.slabTopM } + : {}), + footprint: pad.outline, + padHeightM: (gradePads[index] as GradePad).heightM, + marginM: pad.marginM, + padAreaM2: outcome.padAreasM2[index] ?? 0, + })) + const single = input.pads === undefined ? padFacts[0] : undefined + return terrainWriteOutcome( + site, + nodes, + field, + outcome.heights, + { + ...(single ?? { pads: padFacts }), + run, + reachM, + batterSlopeDeg: (Math.atan(1 / run) * 180) / Math.PI, + padAreaM2: outcome.padAreaM2, + cutVolumeM3: outcome.cutVolumeM3, + fillVolumeM3: outcome.fillVolumeM3, + netM3: outcome.cutVolumeM3 - outcome.fillVolumeM3, + changedSamples: outcome.changedSamples, + steepestSampledSlopeDeg: outcome.steepestSlopeDeg, + daylight: { + reached: lawn + ? bankRun <= reachM || scope !== 'context' + : outcome.farthestChangeM <= reachM - field.spacing, + farthestChangeM: outcome.farthestChangeM, + outsideLotM2: outcome.outsideLotSamples * cellM2, + ...(extras.morePads || extras.cutOnly || extras.padFallPerM !== undefined + ? { outsideLotMaxM: outcome.outsideLotMaxM } + : {}), + }, + ...(upperLevelM !== undefined + ? { lawn: { levelM: upperLevelM, bankRunM: bankRun, areaM2: outcome.lawnAreaM2 } } + : {}), + ...(band + ? { + edge: { + ...(band.role ? { role: band.role } : {}), + normal: band.normal, + frontM: band.frontM, + edgeM: band.edgeM, + padStripM: { + fromM: band.frontM - (gradePads[0] as GradePad).marginM, + toM: band.edgeM + (gradePads[0] as GradePad).marginM, + }, + }, + } + : {}), + ...(input.terraceRiserM && treadM !== undefined + ? { terraces: { riserM: input.terraceRiserM, treadM, resolutionM: field.spacing } } + : {}), + ...(input.wallM + ? { + wall: wall + ? { + heightM: input.wallM, + exact: true, + kind: 'retaining', + breakId: wall.id, + lengthM: lineLengthM(wall.line), + } + : { + heightM: input.wallM, + exact: false, + resolutionM: field.spacing, + note: 'A vertical step at the pad edge on the side the ground leaves the pad, written on the 0.5 m lattice: a steep earth face of one cell, not a wall object. exactWall true writes a terrain-break.', + }, + } + : {}), + ...(outcome.lowLine ? { lowLine: outcome.lowLine } : {}), + ...(extras.retain && wall + ? { face: { breakId: wall.id, lengthM: lineLengthM(wall.line), outline: wall.line } } + : {}), + sampling: samplingOf(field, 'quantized_sample_integral', outcome.changedSamples), + }, + wall || replaced.length + ? { ...(wall ? { create: [{ node: wall, parentId: site.id }] } : {}), delete: replaced } + : undefined, + ) +} + +/** A Boolean ring may repeat its first corner at the end; drop the repeat. */ +function openRing(ring: Vec2[]): Vec2[] { + const first = ring[0] + const last = ring[ring.length - 1] + return first && last && ring.length > 1 && first[0] === last[0] && first[1] === last[1] + ? ring.slice(0, -1) + : ring +} + +/** The footprint's slab area: every solid piece, holes subtracted. */ +function slabAreaM2(surface: SlabSurface): number { + return surface.solid.reduce( + (total, polygon) => + total + + Math.abs(polygonArea(openRing(polygon.outer))) - + polygon.holes.reduce((sum, hole) => sum + Math.abs(polygonArea(openRing(hole))), 0), + 0, + ) +} + +function houseLevelId( + nodes: SceneNodes, + surfaces: SlabSurface[], + requested: string | undefined, +): string | undefined { + if (requested !== undefined) { + const node = nodes[requested] + if (!node) refuse('level_not_found', `No node ${requested} in the scene.`) + if (node.type !== 'level') refuse('not_a_level', `Node ${requested} is not a level.`) + return requested + } + const elevations = getLevelElevations(nodes as Record) + return surfaces + .map((surface) => surface.levelId) + .sort( + (a, b) => + (elevations.get(a)?.baseY ?? Infinity) - (elevations.get(b)?.baseY ?? Infinity) || + a.localeCompare(b), + )[0] +} + +/** + * The level's largest slab, ranked by the slab's total area — ranking the + * solid pieces instead would let a smaller intact slab outrank a larger slab + * a through-cut happened to split, and the answer would silently describe + * the wrong house. A largest slab in several pieces has no single footprint + * outline to report, so it is refused rather than truncated to one piece. + */ +function largestSlabOn(surfaces: SlabSurface[], levelId: string | undefined): SlabSurface { + const onLevel = surfaces + .filter((surface) => surface.levelId === levelId) + .sort((a, b) => slabAreaM2(b) - slabAreaM2(a)) + const chosen = onLevel[0] + if (!chosen || levelId === undefined) + refuse('footprint_empty', 'No slab footprint on the level to measure the ground under.') + if (chosen.solid.length > 1) + refuse( + 'disconnected_footprint', + `Slab ${chosen.slab.id} is the largest on the level but lies in ${chosen.solid.length} disconnected pieces; there is no single footprint to measure under.`, + ) + return chosen +} + +/** The slab outline in site coordinates, through its building's Y-rotation and offset. */ +function siteFrameFootprint( + nodes: SceneNodes, + surface: SlabSurface, +): { footprint: Vec2[]; slabTopM: number } { + const building = surface.buildingId ? nodes[surface.buildingId] : undefined + if (building?.type !== 'building') + refuse('no_building', 'The slab level belongs to no building; its frame is unknown.') + if (building.rotation[0] || building.rotation[2]) + refuse( + 'building_rotation_unsupported', + 'The building tips out of the site plane; its footprint has no site-frame outline.', + ) + const ring = surface.solid[0] + if (!ring) + refuse('footprint_empty', 'No slab footprint on the level to measure the ground under.') + const angle = building.rotation[1] + const cos = Math.cos(angle) + const sin = Math.sin(angle) + const footprint = footprintOf( + openRing(ring.outer).map(([x, z]): [number, number] => [ + cos * x + sin * z + building.position[0], + -sin * x + cos * z + building.position[2], + ]), + ) + return { footprint, slabTopM: building.position[1] + surface.top } +} + +/** The house a ground tool works around: the largest slab of a level, in the site frame. */ +export function houseOutline(nodes: SceneNodes, levelId?: string) { + const surfaces = slabSurfaces(nodes as Record) + const resolved = houseLevelId(nodes, surfaces, levelId) + const surface = largestSlabOn(surfaces, resolved) + return { + levelId: resolved as string, + slabId: surface.slab.id, + buildingId: surface.buildingId as string, + ...siteFrameFootprint(nodes, surface), + } +} + +/** Per footprint edge, the largest fall from slab top to terrain along it. */ +function edgeDropsOf(field: TerrainField, footprint: Vec2[], slabTopM: number, cellM: number) { + const edgeHeights: number[] = [] + const dropAtEdges = polygonEdges(footprint).map(([from, to]) => { + const points = segmentPoints(from, to, segmentSteps(from, to, cellM)) + const heightsM = points.map((point) => heightAt(field, point[0], point[1])) + edgeHeights.push(...heightsM) + return { from, to, dropM: slabTopM - Math.min(...heightsM) } + }) + return { dropAtEdges, edgeHeights } +} + +export const describeTerrainUnderHouse: AgentOperation> = ( + nodes, + raw, +) => { + const input = parseInput(underHouseInput, raw) + const { site, field: persisted } = groundOf(nodes) + const surfaces = slabSurfaces(nodes as Record) + const levelId = houseLevelId(nodes, surfaces, input.levelId) + const surface = largestSlabOn(surfaces, levelId) + const { footprint, slabTopM } = siteFrameFootprint(nodes, surface) + const field = persisted ?? flatFieldOver(footprint) + const cellM = field.spacing + const interior = interiorSamples(field, footprint, gridFor(footprint, cellM)) + const { dropAtEdges, edgeHeights } = edgeDropsOf(field, footprint, slabTopM, cellM) + const sampled = [...interior.map((sample) => sample.yM), ...edgeHeights] + const highestM = Math.max(...sampled) + const lowestM = Math.min(...sampled) + return { + result: { + levelId, + slabId: surface.slab.id, + footprint, + slabTopM, + highestM, + lowestM, + reliefM: highestM - lowestM, + breaks: terrainBreaksOf(site, nodes).map((terrainBreak) => + terrainBreakFacts(terrainBreak, field), + ), + clearanceUnderSlabM: slabTopM - highestM, + dropAtEdges, + needsGuardAt: dropAtEdges.filter((edge) => edge.dropM > UNGUARDED_DROP_THRESHOLD_M), + ...(persisted ? {} : { note: FLAT_GROUND_NOTE }), + guardAdvisory: { + advisory: true, + thresholdM: UNGUARDED_DROP_THRESHOLD_M, + basis: + 'The same 0.5 m drop threshold verify_scene uses for its unguarded_drop observation. Only the threshold is shared: these edges compare slab top against terrain alone, while verify_scene also accounts for landings, neighbouring surfaces and existing guards, so the two need not flag the same edges.', + typicalRequirement: + 'A guard is typically required above about 0.76 m (IRC R312); an edge flagged here between the threshold and that height may not need one. Advisory only: nothing is built from this fact.', + }, + sampling: { + ...samplingOf(field, 'midpoint_grid_and_boundary', interior.length + edgeHeights.length), + cellM, + }, + }, + } +} diff --git a/packages/core/src/agent-operations/unguarded-drop-observations.ts b/packages/core/src/agent-operations/unguarded-drop-observations.ts new file mode 100644 index 0000000000..43f95ada93 --- /dev/null +++ b/packages/core/src/agent-operations/unguarded-drop-observations.ts @@ -0,0 +1,693 @@ +import { floorConstructionLift, liftedManualSlab } from '../lib/floor-construction-lift' +import { withHostedCutterHoles } from '../lib/object-cuts' +import { getOpeningWallCut, wallSupportForNodes } from '../lib/opening-floor-datum' +import { + containsPoint, + difference, + distanceToBoundary, + type MultiPolygon, + type Ring, +} from '../lib/polygon-boolean' +import { getRenderableSlabPolygon, slabPolygonContextForLevel } from '../lib/slab-polygon' +import { heightAt } from '../lib/terrain-field' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import { levelBaseElevationAt } from '../lib/terrain-support-query' +import { rotateVector } from '../procedural-items/spatial' +import { queryNodes } from '../runtime/node-queries' +import type { AnyNode, SlabNode } from '../schema' +import { getLevelElevations, getWallTopLowest } from '../services/storey' +import { sampleFenceCenterline } from '../systems/fence/fence-centerline' +import { resolveStairWalkingSurfaces } from '../systems/stair/stair-clearance' +import { sampleWallCenterline } from '../systems/wall/wall-curve' +import { getWallThickness } from '../systems/wall/wall-footprint' +import { getWallBodyCenterOffset } from '../systems/wall/wall-frame' +import { scriptItemBoundsInLevel } from './layout-clearance' +import { levelIdOf } from './scene-queries' + +type Point = [number, number] +type Interval = [number, number] +type Surface = { + slab: SlabNode + levelId: string + buildingId: string | null + top: number + solid: MultiPolygon +} +export type SlabSurface = Surface +type Guard = { + id: string + levelId: string + start: Point + end: Point + bottom: number + top: number + lateral: number + evidence: 'geometry' | 'bounds' | 'unknown' +} + +export type UnguardedDropObservation = { + type: 'unguarded_drop' + severity: 'info' + message: string + slabId: string + levelId: string + openingIds: string[] + edgeKind: 'perimeter' | 'opening' + coordinateFrame: 'building' + start: Point + end: Point + walkingElevationMeters: number + dropThresholdMeters: number + minimumDropMeters: number + maximumDropMeters: number + exposedLengthMeters: number + guardedLengthMeters: number + unguardedLengthMeters: number + unguardedSpans: { start: Point; end: Point; lengthMeters: number }[] + guardPresent: boolean + guardIds: string[] + boundsGuardIds: string[] + /** What fences it: a fact about the tool, in the form a coherence item states its moves. */ + moves: { label: string; note: string }[] +} + +/** The tool that fences the unguarded spans of slabs, as a move of an unguarded_drop. */ +export function guardEdgesMove(slabIds: readonly string[]): { label: string; note: string } { + const named = slabIds.length === 1 ? slabIds[0] : `${slabIds.length} slabs` + return { + label: `Fence the unguarded spans of ${named}`, + note: `guard_edges({ "slabIds": ${JSON.stringify(slabIds)} }) builds a guard fence along every span verify_scene reports as an unguarded_drop for ${slabIds.length === 1 ? 'the slab' : 'those slabs'} (their unguardedSpans), in one call; its answer states the guarded length and how many unguarded_drop observations remain.`, + } +} + +/** The fall past which an unguarded slab edge is worth naming, metres. Shared + * with describe_terrain_under_house as a threshold only: that fact compares + * slab top against terrain alone, where this check also weighs landings, + * neighbouring surfaces and existing guards, so the flagged edges can differ. */ +export const UNGUARDED_DROP_THRESHOLD_M = 0.5 +const DROP_THRESHOLD = UNGUARDED_DROP_THRESHOLD_M +const GUARD_HEIGHT = 0.5 +const LATERAL_TOLERANCE = 0.1 +const EPSILON = 1e-6 +const OUTSIDE_PROBE = 0.01 +/** + * How far from a stair's walking surface a fall still lands on it: a person at a rim steps onto the + * flight across the clearance a stair well leaves beside it (a few centimetres), as a tread's + * stringer or a handrail leaves. Surfaces of slabs are not reached across a gap. + */ +const STAIR_REACH = 0.1 +const cross = (a: Point, b: Point) => a[0] * b[1] - a[1] * b[0] +const subtract = (a: Point, b: Point): Point => [a[0] - b[0], a[1] - b[1]] +const mix = (a: Point, b: Point, t: number): Point => [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, +] +const length = (a: Point, b: Point) => Math.hypot(b[0] - a[0], b[1] - a[1]) +const edges = (ring: Ring) => ring.map((a, i): [Point, Point] => [a, ring[(i + 1) % ring.length]!]) + +function breakpoints(start: Point, end: Point, solid: MultiPolygon): number[] { + const direction = subtract(end, start) + const result = [0, 1] + for (const polygon of solid) + for (const ring of [polygon.outer, ...polygon.holes]) + for (const [a, b] of edges(ring)) { + const edge = subtract(b, a), + delta = subtract(a, start), + denominator = cross(direction, edge) + if (Math.abs(denominator) <= EPSILON) continue + const t = cross(delta, edge) / denominator, + u = cross(delta, direction) / denominator + if (t > 0 && t < 1 && u >= -EPSILON && u <= 1 + EPSILON) result.push(t) + } + return result +} + +function merged(intervals: Interval[]): Interval[] { + const result: Interval[] = [] + for (const [a, b] of intervals.sort((a, b) => a[0] - b[0])) { + if (b - a <= EPSILON) continue + const last = result.at(-1) + if (last && a <= last[1] + EPSILON) last[1] = Math.max(last[1], b) + else result.push([a, b]) + } + return result +} + +function guardSpan(start: Point, end: Point, guard: Guard): Interval | undefined { + const size = length(start, end), + direction = subtract(end, start) + const otherSize = length(guard.start, guard.end) + if (size < EPSILON || otherSize < EPSILON) return + // Crossing posts and perpendicular partitions do not cover an edge's length. + if (Math.abs(cross(direction, subtract(guard.end, guard.start))) / (size * otherSize) > 0.02) + return + const a = subtract(guard.start, start), + b = subtract(guard.end, start) + if (Math.max(Math.abs(cross(direction, a)), Math.abs(cross(direction, b))) / size > guard.lateral) + return + const project = (p: Point) => (p[0] * direction[0] + p[1] * direction[1]) / (size * size) + const low = Math.max(0, Math.min(project(a), project(b))), + high = Math.min(1, Math.max(project(a), project(b))) + return high - low > EPSILON ? [low, high] : undefined +} + +export function slabSurfaces(nodes: Record): SlabSurface[] { + const elevations = getLevelElevations(nodes) + return queryNodes(nodes, { type: 'slab' }).flatMap((original) => { + if (original.type !== 'slab' || original.recessed || !original.parentId) return [] + const level = elevations.get(original.parentId), + parent = nodes[original.parentId] + if (!level || parent?.type !== 'level') return [] + try { + const slab = liftedManualSlab(nodes, original) + const outer = getRenderableSlabPolygon( + slab, + slabPolygonContextForLevel(parent, (id) => nodes[id]), + ) + const holes = withHostedCutterHoles(original, nodes).holes + const solid = holes.length + ? difference( + outer, + holes.map((outer) => ({ outer, holes: [] })), + { throwOnError: true }, + ) + : difference(outer, []) + const top = level.baseY + slab.elevation + return Number.isFinite(top) && solid.length + ? [{ slab, levelId: parent.id, buildingId: level.buildingId, top, solid }] + : [] + } catch { + // An unsupported polygon supplies no edge evidence. + return [] + } + }) +} + +function guardsForScene(nodes: Record, surfaces: Surface[]): Guard[] { + const result: Guard[] = [], + elevations = getLevelElevations(nodes) + for (const node of queryNodes(nodes, {})) { + const levelId = levelIdOf(nodes, node.id), + level = levelId ? elevations.get(levelId) : undefined + if (!levelId || !level) continue + if (node.type === 'wall') { + const unknownCuts = queryNodes(nodes, { type: 'item', parentId: node.id }).some( + (child) => + child.parentId === node.id && + child.type === 'item' && + child.source?.manifest.cutters?.length, + ) + const base = wallSupportForNodes(node, nodes).elevation, + top = getWallTopLowest(node, levelId, nodes, base) + const points = sampleWallCenterline(node, node.curveOffset ? 64 : 1) + const offset = getWallBodyCenterOffset(node) + const cuts = unknownCuts + ? [] + : queryNodes(nodes, { type: ['door', 'window'] }).flatMap((child) => + child.parentId === node.id && (child.type === 'door' || child.type === 'window') + ? [ + { + child, + cut: getOpeningWallCut(node, child, nodes), + glazing: + child.type === 'window' && + child.openingKind !== 'opening' && + !(child.operationState > 0), + }, + ] + : [], + ) + let distance = 0 + for (let i = 1; i < points.length; i++) { + const a = points[i - 1]!, + b = points[i]!, + span = Math.hypot(b.x - a.x, b.y - a.y) + if (span <= EPSILON) continue + const normal: Point = [-(b.y - a.y) / span, (b.x - a.x) / span] + const start: Point = [a.x + normal[0] * offset, a.y + normal[1] * offset], + end: Point = [b.x + normal[0] * offset, b.y + normal[1] * offset] + const breaks = [ + 0, + 1, + ...cuts + .flatMap(({ child }) => + [child.position[0] - child.width / 2, child.position[0] + child.width / 2].map( + (x) => (x - distance) / span, + ), + ) + .filter((t) => t > 0 && t < 1), + ].sort((a, b) => a - b) + for (let j = 1; j < breaks.length; j++) { + const from = breaks[j - 1]!, + to = breaks[j]!, + mid = distance + ((from + to) / 2) * span + const cut = cuts.find(({ child }) => Math.abs(mid - child.position[0]) < child.width / 2) + const halfThickness = getWallThickness(node) / 2 + const guardStart = mix(start, end, from === 0 && i === 1 ? -halfThickness / span : from) + const guardEnd = mix( + start, + end, + to === 1 && i === points.length - 1 ? 1 + halfThickness / span : to, + ) + // The remaining sill below a doorway is geometry, not a closed-door guard. + result.push({ + id: cut?.glazing ? cut.child.id : node.id, + levelId, + start: guardStart, + end: guardEnd, + bottom: level.baseY + base, + top: level.baseY + (cut && !cut.glazing ? Math.min(top, cut.cut.bottom) : top), + lateral: halfThickness + LATERAL_TOLERANCE, + evidence: unknownCuts ? 'unknown' : 'geometry', + }) + if (cut && !cut.glazing && cut.cut.top < top) + result.push({ + id: node.id, + levelId, + start: guardStart, + end: guardEnd, + bottom: level.baseY + Math.max(base, cut.cut.top), + top: level.baseY + top, + lateral: halfThickness + LATERAL_TOLERANCE, + evidence: 'geometry', + }) + } + distance += span + } + } else if (node.type === 'fence' && node.style === 'guard' && !node.supportSurfaceNodeId) { + const points = sampleFenceCenterline(node, node.path || node.curveOffset ? 64 : 1) + let distance = 0 + const openings = queryNodes(nodes, { type: ['fence-opening', 'fence-gate'] }).filter( + (n) => + n.parentId === node.id && + (n.type === 'fence-opening' || (n.type === 'fence-gate' && (n.openAngle ?? 0) > 0)), + ) + for (let i = 1; i < points.length; i++) { + const a = points[i - 1]!, + b = points[i]!, + start: Point = [a.x, a.y], + end: Point = [b.x, b.y], + span = length(start, end), + mid = mix(start, end, 0.5) + const followsTerrain = + (node.path?.length ?? 0) >= 2 || Math.abs(node.curveOffset ?? 0) > 1e-4 + const sample = node.surfaceMode === 'level' || !followsTerrain ? node.start : mid + const hosts = surfaces.filter( + (s) => s.levelId === levelId && containsPoint(s.solid, sample), + ) + const host = + node.supportSlabId && node.supportSlabId !== 'ground' + ? surfaces.find((s) => s.slab.id === node.supportSlabId && s.levelId === levelId) + : node.supportSlabId || !followsTerrain + ? undefined + : hosts.sort((a, b) => b.top - a.top)[0] + const base = + (host?.top ?? + level.baseY + + levelBaseElevationAt(nodes, levelId, sample[0], sample[1]) + + floorConstructionLift(nodes, node)) + (node.supportOffset ?? 0) + const breaks = [ + 0, + 1, + ...openings + .flatMap((n) => + 'center' in n && 'width' in n + ? [n.center - n.width / 2, n.center + n.width / 2].map((x) => (x - distance) / span) + : [], + ) + .filter((t) => t > 0 && t < 1), + ].sort((a, b) => a - b) + for (let j = 1; j < breaks.length; j++) { + const from = breaks[j - 1]!, + to = breaks[j]!, + center = distance + ((from + to) / 2) * span + if ( + openings.some( + (n) => 'center' in n && 'width' in n && Math.abs(center - n.center) < n.width / 2, + ) + ) + continue + result.push({ + id: node.id, + levelId, + start: mix(start, end, from), + end: mix(start, end, to), + bottom: base + node.groundClearance, + top: base + node.height, + lateral: node.thickness / 2 + LATERAL_TOLERANCE, + evidence: 'geometry', + }) + } + distance += span + } + } else if (node.type === 'slab' && node.railing?.length) { + const surface = surfaces.find((s) => s.slab.id === node.id) + if (surface) + for (const rail of node.railing) + result.push({ + id: node.id, + levelId, + ...rail, + bottom: surface.top, + top: surface.top + 1.1, + lateral: LATERAL_TOLERANCE, + evidence: 'geometry', + }) + } else if ( + node.type === 'item' && + /\b(railing|balustrade|guardrail|glazing)\b/i.test( + `${node.asset.category} ${node.name ?? node.asset.name}`, + ) + ) { + const resolved = scriptItemBoundsInLevel(node, nodes) + if (!resolved) continue + // Bounds near an edge identify a modeled guard object, not continuous infill or mesh safety. + const manifest = node.source!.manifest + const corrected = (point: [number, number, number]) => { + const asset = rotateVector( + point.map((v, i) => v * (node.asset.scale?.[i] ?? 1)) as [number, number, number], + node.asset.rotation, + ) + return rotateVector( + asset.map((v, i) => (v + node.asset.offset[i]!) * node.scale[i]!) as [ + number, + number, + number, + ], + node.rotation, + ) + } + const first = corrected(manifest.bounds.min) + const origin = resolved.corners[0]!.map((v, i) => v - first[i]!) + const guardParts = new Set( + (manifest.parts ?? []) + .filter((part) => /^(railing|balustrade|guardrail|glazing)$/.test(part.type ?? '')) + .map((part) => part.id), + ) + const rings = (manifest.surfaces ?? []).flatMap((surface) => { + if (!surface.part || !guardParts.has(surface.part)) return [] + const polygon: Ring = surface.polygon.map(([x, z]) => { + const point = corrected([x, surface.y, z]) + return [point[0] + origin[0]!, point[2] + origin[2]!] + }) + return polygon.length >= 3 && polygon.every((p) => p.every(Number.isFinite)) + ? [polygon] + : [] + }) + if (!rings.length) rings.push(planHull(resolved.corners.map(([x, , z]): Point => [x, z]))) + for (const [start, end] of rings.flatMap(edges)) + result.push({ + id: node.id, + levelId, + start, + end, + bottom: level.baseY + resolved.bounds.min[1], + top: level.baseY + resolved.bounds.max[1], + lateral: LATERAL_TOLERANCE, + evidence: 'bounds', + }) + } + } + return result +} + +function planHull(points: Ring): Ring { + const sorted = points.sort((a, b) => a[0] - b[0] || a[1] - b[1]) + const half = (list: Ring) => { + const hull: Ring = [] + for (const p of list) { + while ( + hull.length >= 2 && + cross(subtract(hull.at(-1)!, hull.at(-2)!), subtract(p, hull.at(-1)!)) <= 0 + ) + hull.pop() + hull.push(p) + } + return hull.slice(0, -1) + } + return [...half(sorted), ...half([...sorted].reverse())] +} + +const pointsMeet = (a: Point, b: Point) => length(a, b) < 1e-6 + +/** What a report says of one edge: its unguarded length, the fall along it, and the guard it has. */ +function observationMessage( + observation: Pick< + UnguardedDropObservation, + | 'slabId' + | 'edgeKind' + | 'unguardedLengthMeters' + | 'minimumDropMeters' + | 'maximumDropMeters' + | 'guardedLengthMeters' + | 'boundsGuardIds' + >, +): string { + const { unguardedLengthMeters, minimumDropMeters, maximumDropMeters } = observation + return `Slab ${observation.slabId} ${observation.edgeKind} edge has ${unguardedLengthMeters.toFixed(3)} m without a modeled guard along a drop of ${minimumDropMeters.toFixed(3)}–${maximumDropMeters.toFixed(3)} m (threshold ${DROP_THRESHOLD.toFixed(2)} m); ${observation.guardedLengthMeters.toFixed(3)} m has guard geometry or labeled guard bounds${observation.boundsGuardIds.length ? '; object bounds are not continuous-infill evidence' : ''}` +} + +/** An edge this short is a facet of a rounded corner, not a span anyone guards on its own. */ +const TINY_EDGE_M = 0.1 + +function absorb(host: UnguardedDropObservation, piece: UnguardedDropObservation) { + host.unguardedSpans.push(...piece.unguardedSpans) + host.exposedLengthMeters += piece.exposedLengthMeters + host.guardedLengthMeters += piece.guardedLengthMeters + host.unguardedLengthMeters += piece.unguardedLengthMeters + host.minimumDropMeters = Math.min(host.minimumDropMeters, piece.minimumDropMeters) + host.maximumDropMeters = Math.max(host.maximumDropMeters, piece.maximumDropMeters) + host.guardIds = [...new Set([...host.guardIds, ...piece.guardIds])].sort() + host.boundsGuardIds = [...new Set([...host.boundsGuardIds, ...piece.boundsGuardIds])].sort() + host.openingIds = [...new Set([...host.openingIds, ...piece.openingIds])].sort() + host.guardPresent = host.guardIds.length > 0 + host.message = observationMessage(host) +} + +/** + * The observations of one ring, in ring order, with the facets of its rounded corners folded into + * the straight edge they join (before it, else after it): a corner is part of the edge's guard. + * A piece that joins no straight edge stays as it is. + */ +function foldTinyEdges(pieces: UnguardedDropObservation[]): UnguardedDropObservation[] { + const tiny = (piece: UnguardedDropObservation) => length(piece.start, piece.end) < TINY_EDGE_M + const folded = new Set() + let host: UnguardedDropObservation | undefined + let reach: Point | undefined + for (const piece of pieces) { + if (!tiny(piece)) { + host = piece + reach = piece.end + } else if (host && reach && pointsMeet(reach, piece.start)) { + absorb(host, piece) + folded.add(piece) + reach = piece.end + } else { + host = undefined + } + } + let next: UnguardedDropObservation | undefined + let back: Point | undefined + for (const piece of [...pieces].reverse()) { + if (folded.has(piece)) continue + if (!tiny(piece)) { + next = piece + back = piece.start + } else if (next && back && pointsMeet(back, piece.end)) { + absorb(next, piece) + folded.add(piece) + back = piece.start + } else { + next = undefined + } + } + return pieces.filter((piece) => !folded.has(piece)) +} + +/** Edge-length evidence on solid walking plates; this is not guard adequacy or code certification. */ +export function unguardedDropObservations( + nodes: Record, +): UnguardedDropObservation[] { + const surfaces = slabSurfaces(nodes), + guards = guardsForScene(nodes, surfaces), + elevations = getLevelElevations(nodes) + const stairSurfaces = queryNodes(nodes, { type: 'stair' }).flatMap((node) => { + if (node.type !== 'stair') return [] + const levelId = levelIdOf(nodes, node.id), + buildingId = levelId ? elevations.get(levelId)?.buildingId : null + try { + return resolveStairWalkingSurfaces(node, nodes).map((surface) => ({ + levelId, + buildingId, + top: surface.top, + solid: [surface.region], + reach: STAIR_REACH, + })) + } catch { + // Over-budget or unresolved stair detail is not a measured landing surface. + return [] + } + }) + const observations: UnguardedDropObservation[] = [] + for (const surface of surfaces) { + const peers = [ + ...surfaces.filter((s) => s.slab.id !== surface.slab.id).map((s) => ({ ...s, reach: 0 })), + ...stairSurfaces, + ].filter( + (s) => + s.levelId === surface.levelId || + (surface.buildingId && s.buildingId === surface.buildingId), + ) + const building = surface.buildingId ? nodes[surface.buildingId] : undefined + if (building?.type !== 'building' || building.rotation[0] || building.rotation[2]) continue + const site = building.parentId ? nodes[building.parentId] : undefined + const field = site?.type === 'site' ? persistedTerrainFieldOf(site, nodes) : null + if (site?.type === 'site' && site.terrain && !field) continue + for (const polygon of surface.solid) + for (const [ringIndex, ring] of [polygon.outer, ...polygon.holes].entries()) { + const pieces: UnguardedDropObservation[] = [] + for (const [start, end] of edges(ring)) { + const size = length(start, end) + if (size < EPSILON) continue + // Boolean rings have the solid to their left, including clockwise hole rims. + const outward: Point = [ + ((end[1] - start[1]) / size) * OUTSIDE_PROBE, + (-(end[0] - start[0]) / size) * OUTSIDE_PROBE, + ] + const outsideStart: Point = [start[0] + outward[0], start[1] + outward[1]], + outsideEnd: Point = [end[0] + outward[0], end[1] + outward[1]] + // A flight beside the edge splits it where its treads begin, along a line within reach. + const reachStart: Point = [ + start[0] + (outward[0] / OUTSIDE_PROBE) * STAIR_REACH, + start[1] + (outward[1] / OUTSIDE_PROBE) * STAIR_REACH, + ] + const reachEnd: Point = [ + end[0] + (outward[0] / OUTSIDE_PROBE) * STAIR_REACH, + end[1] + (outward[1] / OUTSIDE_PROBE) * STAIR_REACH, + ] + const breaks = [ + ...new Set( + peers + .flatMap((s) => [ + ...breakpoints(outsideStart, outsideEnd, s.solid), + ...(s.reach > 0 ? breakpoints(reachStart, reachEnd, s.solid) : []), + ]) + .concat([0, 1]), + ), + ].sort((a, b) => a - b) + const exposed: { from: number; to: number; drop: number }[] = [] + for (let i = 1; i < breaks.length; i++) { + const from = breaks[i - 1]!, + to = breaks[i]!, + point = mix(outsideStart, outsideEnd, (from + to) / 2) + const angle = building.rotation[1] + const worldX = + Math.cos(angle) * point[0] + Math.sin(angle) * point[1] + building.position[0] + const worldZ = + -Math.sin(angle) * point[0] + Math.cos(angle) * point[1] + building.position[2] + let landing = (field ? heightAt(field, worldX, worldZ) : 0) - building.position[1] + for (const peer of peers) + if ( + peer.top <= surface.top + DROP_THRESHOLD + EPSILON && + (containsPoint(peer.solid, point) || + (peer.reach > 0 && distanceToBoundary(peer.solid, point) <= peer.reach)) + ) + landing = Math.max(landing, peer.top) + const drop = surface.top - landing + if (drop > DROP_THRESHOLD + EPSILON) exposed.push({ from, to, drop }) + } + if (!exposed.length) continue + const covering = guards.flatMap((guard) => { + if ( + guard.levelId !== surface.levelId || + guard.bottom > surface.top + LATERAL_TOLERANCE || + guard.top < surface.top + GUARD_HEIGHT - EPSILON + ) + return [] + const span = guardSpan(start, end, guard) + return span ? [{ guard, span }] : [] + }) + if ( + covering.some( + ({ guard, span }) => + guard.evidence === 'unknown' && + exposed.some( + ({ from, to }) => Math.min(to, span[1]) > Math.max(from, span[0]) + EPSILON, + ), + ) + ) + continue + const unguarded: Interval[] = [], + guarded: Interval[] = [], + guardIds = new Set(), + boundsIds = new Set() + for (const { from, to } of exposed) { + const coverage = merged( + covering.flatMap(({ guard, span }) => { + const a = Math.max(from, span[0]), + b = Math.min(to, span[1]) + if (b - a <= EPSILON) return [] + guardIds.add(guard.id) + if (guard.evidence === 'bounds') boundsIds.add(guard.id) + return [[a, b] as Interval] + }), + ) + let cursor = from + for (const [a, b] of coverage) { + if (a > cursor + EPSILON) unguarded.push([cursor, a]) + guarded.push([a, b]) + cursor = b + } + if (cursor < to - EPSILON) unguarded.push([cursor, to]) + } + const unguardedLength = unguarded.reduce((sum, [a, b]) => sum + (b - a) * size, 0) + if (unguardedLength <= EPSILON) continue + const openingIds = queryNodes(nodes, { type: 'floor-opening', parentId: surface.levelId }) + .filter( + (n) => + n.type === 'floor-opening' && + n.parentId === surface.levelId && + n.drawnOn === 'floor' && + containsPoint([{ outer: n.polygon, holes: [] }], mix(start, end, 0.5)), + ) + .map((n) => n.id) + .sort() + const minimumDrop = Math.min(...exposed.map((s) => s.drop)), + maximumDrop = Math.max(...exposed.map((s) => s.drop)), + guardedLength = guarded.reduce((sum, [a, b]) => sum + (b - a) * size, 0) + const piece: UnguardedDropObservation = { + type: 'unguarded_drop', + severity: 'info', + message: '', + slabId: surface.slab.id, + levelId: surface.levelId, + openingIds, + edgeKind: ringIndex ? 'opening' : 'perimeter', + coordinateFrame: 'building', + start, + end, + walkingElevationMeters: surface.top, + dropThresholdMeters: DROP_THRESHOLD, + minimumDropMeters: minimumDrop, + maximumDropMeters: maximumDrop, + exposedLengthMeters: exposed.reduce((sum, s) => sum + (s.to - s.from) * size, 0), + guardedLengthMeters: guardedLength, + unguardedLengthMeters: unguardedLength, + unguardedSpans: merged(unguarded).map(([a, b]) => ({ + start: mix(start, end, a), + end: mix(start, end, b), + lengthMeters: (b - a) * size, + })), + guardPresent: guardIds.size > 0, + guardIds: [...guardIds].sort(), + boundsGuardIds: [...boundsIds].sort(), + moves: [guardEdgesMove([surface.slab.id])], + } + piece.message = observationMessage(piece) + pieces.push(piece) + } + observations.push(...foldTinyEdges(pieces)) + } + } + return observations +} diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 1501973d00..f23820168d 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -58,6 +58,10 @@ import { queryNodes, } from './scene-queries' import { reviewSince } from './scene-review' +import { + type TerrainBreakObservation, + terrainBreakObservations, +} from './terrain-break-observations' import type { AgentContext, AgentOperation, AgentOperationSteps, SceneNodes } from './types' import type { RoomUnreachableIssue } from './unreachable-rooms-check' import { @@ -73,6 +77,7 @@ import { type WallObjectObservation, wallObjectObservations } from './wall-objec export type SceneIssue = | CeilingObjectObservation | WallObjectObservation + | TerrainBreakObservation | RoomFinding | { type: string; message: string; severity?: 'info' | 'warning' } | { type: 'schema_invalid'; message: string; nodeId: string; path: string } @@ -483,7 +488,15 @@ export const verifySceneSteps: AgentOperationSteps true, ) const seat = groundSeat(asNodes, buildingOf(level.levelId) ?? '') - if (seat?.levelId === level.levelId && seat.explicit && !seat.seated) + // A house that walks out: the level under its ground level stands on the low ground and in + // the hill at once. The ground level then stands high on purpose, carried by that level. + const walksOut = levels.some( + (other) => + other.floorIndex === level.floorIndex - 1 && + buildingOf(other.levelId) === buildingOf(level.levelId) && + levelGradeStanding(asNodes, other.levelId) === 'partly-below-grade', + ) + if (seat?.levelId === level.levelId && seat.explicit && !seat.seated && !walksOut) report( 'ground_level_unseated', `${levelName} is the ground floor, but its floor datum stands ${seat.offset.toFixed(2)} m ${seat.offset > 0 ? 'over' : 'under'} grade (${seat.gradeElevation.toFixed(2)} m); a seated ground floor stands on it. set_ground_level on it seats the building.`, @@ -808,6 +821,7 @@ export const verifySceneSteps: AgentOperationSteps issues.push(...layoutIssuesFromScene(Object.values(settled))) issues.push(...ceilingObjectObservations(settled)) issues.push(...wallObjectObservations(settled)) + issues.push(...terrainBreakObservations(settled)) const registered = function* (beforeCheckpoint: boolean): Steps { for (const check of checks) { if (check.order < CHECKPOINT_ORDER !== beforeCheckpoint) continue diff --git a/packages/core/src/agent-tools/index.ts b/packages/core/src/agent-tools/index.ts index 2f00b7c297..163abe8055 100644 --- a/packages/core/src/agent-tools/index.ts +++ b/packages/core/src/agent-tools/index.ts @@ -29,11 +29,31 @@ import { deleteNodeTool, getNodeTool } from './nodes' import { paintTool } from './paint' import { placeInRoomTool } from './place-in-room' import { placeItemsTool } from './place-items' +import { addRampTool } from './ramp' import { createRoofTool, moveRoofsToRoofLevelTool } from './roofs' import { ROOM_TOOL_CONTRACTS } from './room-structure' import { searchMaterialsTool } from './search-materials' import { getSiteTool, placeBuildingTool } from './site' import { createStairTool, fitStairTool, measureStairTool } from './stairs' +import { + addStepsToGroundTool, + addTerracesTool, + gradeAlongLineTool, + readTerrainFactsTool, + seatHouseTool, + setTerrainPlaneTool, +} from './terraforming' +import { + addTerrainBreakTool, + carveTerrainPadTool, + describeTerrainUnderHouseTool, + gradeAroundHouseTool, + readSiteTerrainTool, + readTerrainContoursTool, + sampleTerrainLineTool, + setSiteLotTool, + shapeSiteTerrainTool, +} from './terrain' import { UNIT_TOOL_CONTRACTS } from './units' import { verifySceneTool } from './verify-scene' import { viewSceneTool } from './view-scene' @@ -132,6 +152,22 @@ export const AGENT_TOOL_CONTRACTS = [ searchMaterialsTool, getSiteTool, placeBuildingTool, + setSiteLotTool, + addRampTool, + addTerrainBreakTool, + readSiteTerrainTool, + sampleTerrainLineTool, + readTerrainContoursTool, + shapeSiteTerrainTool, + carveTerrainPadTool, + gradeAroundHouseTool, + describeTerrainUnderHouseTool, + readTerrainFactsTool, + seatHouseTool, + setTerrainPlaneTool, + gradeAlongLineTool, + addStepsToGroundTool, + addTerracesTool, ...ROOM_TOOL_CONTRACTS, ...UNIT_TOOL_CONTRACTS, runBatchTool, @@ -143,4 +179,7 @@ export * from './design-brief' export { placeDesignTool, validateDesignTool } from './designs' export { straightenFacadePhotoTool } from './photo-elevation' export { placeInRoomTool } from './place-in-room' +export * from './ramp' export { createRoofTool } from './roofs' +export * from './terraforming' +export * from './terrain' diff --git a/packages/core/src/agent-tools/notation.test.ts b/packages/core/src/agent-tools/notation.test.ts index 0a4f3fa992..08f423e462 100644 --- a/packages/core/src/agent-tools/notation.test.ts +++ b/packages/core/src/agent-tools/notation.test.ts @@ -1,6 +1,10 @@ import { describe, expect, test } from 'bun:test' import { z } from 'zod' -import { NOT_LENGTHS, NOTATION_CASES } from '../agent-operations/__fixtures__/notation-cases' +import { + METRES_ONLY_TOOLS, + NOT_LENGTHS, + NOTATION_CASES, +} from '../agent-operations/__fixtures__/notation-cases' import { HOSTED_SERVICE_TOOL_CONTRACTS } from './hosted-services' import { AGENT_TOOL_CONTRACTS, @@ -35,7 +39,11 @@ describe('one notation (N1): each length, angle and pitch reads in its own unit test('every other number a shared tool takes by name is a coordinate, a fraction or a ratio', () => { const plain = bareNumberPaths(CONTRACTS) - expect(plain.filter((path) => !NOT_LENGTHS.has(path))).toEqual([]) + expect( + plain.filter( + (path) => !(NOT_LENGTHS.has(path) || METRES_ONLY_TOOLS.has(path.split('.')[0] ?? '')), + ), + ).toEqual([]) expect([...NOT_LENGTHS].filter((path) => !plain.includes(path))).toEqual([]) }) diff --git a/packages/core/src/agent-tools/ramp.ts b/packages/core/src/agent-tools/ramp.ts new file mode 100644 index 0000000000..e6bdfbc6c6 --- /dev/null +++ b/packages/core/src/agent-tools/ramp.ts @@ -0,0 +1,67 @@ +import { z } from 'zod' +import { measurement } from './measurement' +import { NodeId } from './node-id' + +const point = z.array(measurement('length', 'm')).length(2) + +export const addRampTool = { + name: 'add_ramp', + title: 'Add ramp', + description: + 'Add a Site-owned vehicle or pedestrian ramp with a continuous centreline of lines and signed circular arcs, absolute Site-local endpoint heights and softer entry/exit grade transitions. Width follows the centreline; thickness extends downward. French residential vehicle ramps commonly use 15–18% maximum grades with softer transitions to avoid grounding vehicles; this is design context, not accessibility or code certification. Returns measured length, rise, maximum grade, transitions, target matches and warnings. A declared door or level target is only reached when its modeled position, footprint and height match the endpoint; naming a target does not create a connection. cut-fill (default) reshapes persisted terrain beneath the corridor; none leaves it unchanged. Refuses invalid/degenerate centreline geometry, arcs whose inner radius does not exceed half the width, and intersecting or stacked corridors rather than overwriting them.', + input: { + siteId: NodeId.optional().describe('Owning Site id; omit when the scene has one Site.'), + name: z.string().min(1).max(120).optional(), + start: point.describe('Centreline start [x, z] in Site-local metres.'), + segments: z + .array( + z.discriminatedUnion('type', [ + z.object({ + type: z.literal('line'), + end: point.describe('Line endpoint [x, z] in Site-local metres.'), + }), + z.object({ + type: z.literal('arc'), + center: point.describe('Circle centre [x, z] in Site-local metres.'), + sweep: measurement('angle', 'rad', { + description: 'Signed arc sweep in radians, from the preceding endpoint.', + }), + }), + ]), + ) + .min(1) + .max(128), + width: measurement('length', 'm', { positive: true }).optional(), + startHeight: measurement('length', 'm', { + description: 'Absolute Site-local Y at the centreline start, default 0 m.', + }).optional(), + endHeight: measurement('length', 'm', { + description: + 'Absolute Site-local Y at the final endpoint; omit to resolve endTargetId from its modeled door or level height. With neither height nor target, refuses ramp_end_required.', + }).optional(), + thickness: measurement('length', 'm', { positive: true }).optional(), + startTransition: measurement('length', 'm', { + min: 0, + description: + 'Entry transition length: grade increases linearly from zero. Default is the smaller of 1.5 m and one quarter of the centreline length; explicit zero removes the transition.', + }).optional(), + endTransition: measurement('length', 'm', { + min: 0, + description: + 'Exit transition length: grade decreases linearly to zero. Default is the smaller of 1.5 m and one quarter of the centreline length; explicit zero removes the transition.', + }).optional(), + maxSlopePercent: z + .number() + .positive() + .optional() + .describe('Stated maximum grade, default 18%.'), + use: z.enum(['vehicle', 'pedestrian']).optional(), + startTargetId: NodeId.optional().describe('Optional modeled door or level at the start.'), + endTargetId: NodeId.optional().describe('Optional modeled door or level at the end.'), + terrainMode: z.enum(['cut-fill', 'none']).optional(), + retainingHeight: measurement('length', 'm', { + min: 0, + description: 'Retaining side height; zero means no retaining walls.', + }).optional(), + }, +} diff --git a/packages/core/src/agent-tools/terraforming.ts b/packages/core/src/agent-tools/terraforming.ts new file mode 100644 index 0000000000..7b237332dc --- /dev/null +++ b/packages/core/src/agent-tools/terraforming.ts @@ -0,0 +1,643 @@ +import { z } from 'zod' +import { measurement } from './measurement' +import { NodeId } from './node-id' + +/** + * Shaping the ground for what stands on it, and reading how the two meet: one set for whoever + * lays out a garden and whoever seats a house. Heights are metres above the scene datum; points + * are [x, z] metres in the site frame unless a field says otherwise. + */ + +// Arrays avoid tuple-form JSON schemas that some clients cannot call. +const point = z.array(z.number()).length(2) +const range = z.object({ min: z.number(), max: z.number() }) +const terrainScope = z + .enum(['lot', 'context']) + .optional() + .describe('Default lot: stay inside the property. Context explicitly allows shaping beyond it.') +const samplingOutput = z.looseObject({ + approximate: z.literal(true), + method: z.string(), + spacingM: z.number(), + heightStepM: z.number(), + sampleCount: z.number().int(), +}) + +const findingOutput = z.object({ + code: z.string(), + id: z.string(), + value: z.number(), + message: z.string(), +}) + +const GROUND_REFUSALS = + 'Refusals: no_site, ambiguous_site (more than one site), no_terrain (a persisted field that cannot be read or is not finite), invalid_input.' + +export const readTerrainFactsTool = { + name: 'read_terrain_facts', + title: 'Read terrain facts', + description: + 'Read how what is built meets the ground, as measured facts: heights are metres above the scene datum, points are [x, z] in the site frame, the ground is the persisted terrain or the flat datum where none is shaped. ' + + 'houses: per building, its ground level, the base of that level and its storey height, the top of its floor, whether the floor rests on the ground and follows it (floorFollowsGround) and what the storey then keeps (clearHeightM: a floor that follows the ground rises with the ground at its walls, the top of the storey does not), the ground under it (lowest, highest, mean), floorOverGroundM (floor top minus ground: negative where the ground stands over the floor), the share of the floor with ground over it and with air under it; per exterior wall, its side of the lot (the street side is front), the ground along its foot, the floor over that ground, fallAwayPercent (how the ground falls going away from the wall over 3 m; negative rises), fallAtWallPercent (the same over the first half metre from the foot of the wall), fallsTowardLengthM (the length where water runs to the wall: the ground climbs from its foot, without first falling, over 1 m or more and by 0.03 m or more; a face the ground steps up at is not a climb), lowLineUnderFootM (how far under the foot of the wall the lowest ground within 2.5 m lies), earthAgainstM (the ground at the outside face over the floor inside: earth the wall holds), earthLengthM (the length with more than 0.3 m of it), buriedShare (that earth against the storey height), faceBefore (a face the ground steps up at before the wall, across an areaway: its distance and height) and each window with its sill against the ground outside (underGroundM); per exterior door, its sill, what is outside it (the ground, or a slab laid there), stepM (sill minus outside: negative is ground over the sill) and the steps or ramp that serve it; roomsAgainstEarth, the rooms along a wall that holds earth: their length along outside walls and along those that hold earth, their openings with the ground under the sill and over it, and whether the room states artificial light and ventilation. Left and right are the sides of the lot as its setbacks name them, read along the street edge in the order its corners are listed; outward gives the direction itself. ' + + 'surfaces: each driveway, walk, patio and lawn slab, flat or draped, its height over the ground and its slope; a draped drive or walk is read the way it is travelled (down its middle, along the nearest side of its outline, over 3 m), with its cross fall apart and the steepest ground under it apart (steepestGroundPercent: its edges on a batter included). steps: each outside flight, its foot against the ground and its top against the sill of the door it reaches. ramps: each ramp, its steepest grade against its stated limit, each end against the ground beyond it, and its sides (the most the ground beside it stands over and under its surface, the height of its retaining sides, and the length of side where a higher face stands unheld). retaining: each terrain break with the height it holds, and each house within 10 m of it: on its high side (top) or its low side (foot), and how far its walls stand from the face. banks: ground steeper than 45 degrees that no face holds. earthwork: cut and fill against the ground before any tile was written (the frozen base field, or the datum; relief that was itself written as tiles counts as earthwork). ' + + 'open lists the facts past a limit, each with its number and a sentence; limits states those limits, which are design context, not a code check. ' + + 'section, when given, adds a section along a straight line: the ground at its breakpoints (stations where the ground departs from a straight line by more than 0.02 m) and each floor the line passes over, with its top and its clearance. ' + + 'Reads persisted terrain only; changes nothing. ' + + GROUND_REFUSALS, + input: { + section: z + .strictObject({ + from: point.describe('Section start [x,z] in site-frame metres.'), + to: point.describe('Section end [x,z] in site-frame metres.'), + }) + .optional() + .describe('A straight line to cut a section along; omit for the facts alone.'), + }, + annotations: { readOnlyHint: true }, +} + +const wallFactsOutput = z.object({ + wallId: z.string(), + side: z.enum(['front', 'rear', 'left', 'right']).optional(), + outward: point, + lengthM: z.number(), + groundM: range, + floorOverGroundM: range, + fallAwayPercent: range, + fallAtWallPercent: range, + fallsTowardLengthM: z.number(), + lowLineUnderFootM: range, + earthAgainstM: z.object({ max: z.number(), mean: z.number() }), + earthLengthM: z.number(), + buriedShare: z.number(), + faceBefore: z.object({ distanceM: z.number(), heightM: z.number() }).optional(), + windows: z.array( + z.object({ + windowId: z.string(), + sillM: z.number(), + outsideM: z.number(), + underGroundM: z.number(), + }), + ), +}) +const doorFactsOutput = z.object({ + doorId: z.string(), + wallId: z.string(), + levelId: z.string(), + at: point, + sillM: z.number(), + outside: z.enum(['ground', 'slab']), + outsideId: z.string().optional(), + outsideM: z.number(), + stepM: z.number(), + servedBy: z.string().optional(), +}) + +export const terrainFactsOutput = { + hasTerrain: z.boolean(), + houses: z.array( + z.object({ + buildingId: z.string(), + levelId: z.string(), + standing: z.string(), + levelBaseM: z.number(), + storeyHeightM: z.number(), + floorM: range, + clearHeightM: z.number(), + floorFollowsGround: z.boolean(), + followingFloorOverBaseM: z.number(), + groundM: z.object({ lowest: z.number(), highest: z.number(), mean: z.number() }), + floorOverGroundM: range, + groundOverFloorShare: z.number(), + floorInAirShare: z.number(), + walls: z.array(wallFactsOutput), + doors: z.array(doorFactsOutput), + roomsAgainstEarth: z.array( + z.object({ + zoneId: z.string(), + name: z.string(), + frontageM: z.number(), + earthFrontageM: z.number(), + openingsClear: z.number().int(), + openingsUnderGround: z.number().int(), + declared: z.boolean(), + }), + ), + }), + ), + surfaces: z.array( + z.object({ + slabId: z.string(), + kind: z.string(), + mode: z.enum(['flat', 'draped']), + areaM2: z.number(), + overGroundM: range, + slopePercent: z.object({ max: z.number(), mean: z.number() }), + crossFallPercent: z.object({ max: z.number(), mean: z.number() }).optional(), + steepestGroundPercent: z.number(), + }), + ), + steps: z.array( + z.object({ + stairId: z.string(), + foot: point, + footM: z.number(), + groundAtFootM: z.number(), + footOverGroundM: z.number(), + topM: z.number(), + doorId: z.string().optional(), + topOverSillM: z.number().optional(), + }), + ), + ramps: z.array( + z.object({ + rampId: z.string(), + lengthM: z.number(), + maximumSlopePercent: z.number(), + statedLimitPercent: z.number(), + ends: z.array( + z.object({ + at: point, + heightM: z.number(), + groundBeyondM: z.number(), + overGroundM: z.number(), + }), + ), + sides: z.object({ + cutMaxM: z.number(), + fillMaxM: z.number(), + retainingHeightM: z.number(), + unheldLengthM: z.number(), + }), + }), + ), + retaining: z.array( + z.object({ + breakId: z.string(), + kind: z.string(), + lengthM: z.number(), + heightM: range, + houses: z.array( + z.object({ + buildingId: z.string(), + standsAt: z.enum(['top', 'foot']), + distanceM: z.number(), + }), + ), + }), + ), + banks: z.object({ steepestDeg: z.number(), areaM2: z.number() }), + earthwork: z + .object({ + cutM3: z.number(), + fillM3: z.number(), + against: z.enum(['base_field', 'datum']), + }) + .optional(), + open: z.array(findingOutput), + limits: z.record(z.string(), z.number()), + section: z + .object({ + from: point, + to: point, + lengthM: z.number(), + ground: z.array(z.object({ sM: z.number(), groundM: z.number() })), + floors: z.array( + z.object({ + slabId: z.string(), + fromM: z.number(), + toM: z.number(), + topM: z.number(), + overGroundM: range, + }), + ), + }) + .optional(), + note: z.string().optional(), +} + +export const SEAT_STRATEGIES = ['balance', 'fill', 'cut', 'keep', 'walk_out', 'hillside'] as const + +export const seatHouseTool = { + name: 'seat_house', + title: 'Seat house', + description: + 'Seat a house on the ground: choose the height the base of its ground level stands at against the ground under it, move the building to that height (its plan stays where it is), and grade the ground to meet it, in one undo step. The house is the largest slab of a level (levelId, default the ground level of the building), which must be the ground level of its building, not a level under or over it. ' + + 'The ground at the walls is brought to the base of the level, as it lies on a flat site. A floor that rests on the ground follows the ground at its walls while the top of its storey stays on the base of the level: with the ground at the base the floor stands where it was drawn and the storey keeps its height. A floor the ground had lifted before a level was put under it is put back on the base of its level, as thick as it was, and a floor stored thinner than a slab can be takes the thickness of a slab (floorsPutBack). ' + + 'strategy says where the base goes. balance (the default): at the height where the cut and the fill of the whole grading are equal; a move of the building under 0.03 m is not made, and on ground that is level under the house the edge of the pad stands on it, as fill does. fill: the edge of the pad at the highest ground under the house, so nothing is cut under it and the low side is filled. cut: the edge of the pad at the lowest ground under the house, so the house is dug in and the high side is cut. keep: the building stays where it is and only the ground moves, to the base it has. walk_out: for a house with a level under its ground level; that lower level stands with its base on the lowest ground along the open side (openToward, [x,z], default downhill), an apron apronM deep (default 3 m) is levelled before that side at the lower base, and around the rest of the house the hill is only cut back where it stands over the base of the ground level and keeps its own slope elsewhere. hillside: the house is backed into the slope; its base stands as for cut (or at groundM, which this strategy alone takes with it), the ground that stands over the base is not battered back but held against the house by a face on the hull of its outline, areawayM from the walls (default 0: the walls themselves hold it; above 0 a level areaway lies between the walls and the face), written as a retaining terrain break; the face holds retainM of ground at most (default the height of the storey) and ground over that is cut back at the batter; where the ground lies under the base the pad and its batter are filled as for cut. An outline that is not convex is excavated to its hull: the part of the hull outside the house stands at the base, as a court. groundM instead states the height of the ground at the walls in metres above datum; give it or strategy, not both (hillside excepted). ' + + 'Where the ground rises beyond the pad, or is held, a low line carries water round the house instead of to its walls: a level bottom 0.75 m wide, at the edge of the pad and 0.15 m under it at its summit (before held ground: 1 m from the face, 0.25 m under the ground, the ground falling 8 % from the face to it), falling 1 % along its length from its summit to each end, and from each end straight down the ground until the ground is lower than it. lowLine in the answer gives its length, its summit and lowest heights, the deepest it is cut and the ends that came out (outlets); an end that finds no lower ground within 8 m, or ground that stands over the base on every side, is said in unmet. A declared wall (wallM) gets no low line. A house seated before is left as it stands by the same strategy (no_change), its low line kept; a face an earlier seating left is taken away when this one makes none. ' + + 'The pad reaches marginM (default 1.0 m) beyond the outline and falls away from the walls by padFallPercent (default 5) over that margin, so water leaves the walls and, under a bank that rises, the edge of the pad is the low line that carries it round. Beyond the pad the ground is a batter, 1 m of height per run metres (default 2), to the ground that was there, looked for within reachM (default 15 m); terraceRiserM cuts it into steps; wallM declares a retaining wall at the pad edge on the side the ground leaves the pad, written as a terrain break (a real wall) when exactWall is true, else as a step on the 0.5 m lattice; inside an exact wall the pad is level, a terrain break holding one height on its side. ' + + 'Writes level-0 tiles at 0.5 m; a numeric terrain-break plane wins over what is written under it. Scope lot (default) writes nothing outside the property: where the batter would pass the property line it stops there, and unmet says so with the step it leaves. ' + + 'Returns strategy, levelId, buildingId, groundAtWallsM, padEdgeM, movedBuildingByM, groundUnderHouseM before (lowest, highest, mean), cutVolumeM3, fillVolumeM3, netM3, batterSlopeDeg, steepestSampledSlopeDeg, daylight, wall, terraces, walkOut (the lower level, its base, the open side, the apron, the fall across the house and the height between the two levels), hillside (retainM, areawayM, faceBreakId), lowLine, floorsPutBack, stepsResolved (outside flights of one straight run that climbed from the ground to a door of the house that opens on the ground are solved again from the new sill and ground, each with its new rise and step count, or removed where the door now meets the ground; a flight of several runs, a door with a slab before it and a ramp are left as they were), unmet (what the grading could not do, in sentences), floorM, and after: floorOverGroundM, clearHeightM, each exterior door with its stepM, and the open terrain facts about this house once seated (the terrain facts read gives every one). ' + + 'Refusals: no_site, ambiguous_site, no_terrain, invalid_input (a strategy other than hillside with groundM; a level that is not the ground level of its building; walk_out with no level under it, or with exactWall; hillside with wallM or exactWall; retainM or areawayM without hillside), level_not_found, not_a_level, no_building, building_rotation_unsupported, footprint_empty, disconnected_footprint, invalid_polygon, outside_property, crossing_breaks, conflicting_breaks, unsupported_geometry, no_change (the house already stands so and less than 0.25 m3 would move), sampling_limit (the edit over 400,000 terrain samples, or the corners of the outline times its samples over 2,000,000). An outline of more than 256 corners gets no low line, and unmet says so.', + input: { + scope: terrainScope, + levelId: z + .string() + .optional() + .describe( + 'Level whose largest slab is the house outline; default the ground level of the building.', + ), + strategy: z + .enum(SEAT_STRATEGIES) + .optional() + .describe( + 'Where the base of the level goes against the ground; default balance. Not with groundM.', + ), + groundM: measurement('length', 'm', { + min: -1000, + max: 1000, + description: + 'Height of the ground at the walls (the base of the level) in metres above datum, instead of a strategy.', + }).optional(), + openToward: point + .optional() + .describe( + 'walk_out: the open side looks this way, [x,z] in the site frame (need not be unit); default downhill.', + ), + apronM: measurement('length', 'm', { + positive: true, + max: 20, + description: 'walk_out: depth of the level apron before the open side; default 3 m.', + }).optional(), + marginM: measurement('length', 'm', { + min: 0, + max: 10, + description: 'How far the pad reaches beyond the outline; default 1.0 m.', + }).optional(), + padFallPercent: z + .number() + .min(0) + .max(15) + .optional() + .describe('Fall of the pad away from the walls, percent over the margin; 0–15, default 5.'), + run: z + .number() + .min(0.25) + .max(20) + .optional() + .describe( + 'Batter run: horizontal metres per metre of height (2 is 1:2); 0.25–20, default 2.', + ), + reachM: measurement('length', 'm', { + positive: true, + max: 60, + description: 'How far beyond the pad edge the batter is looked for; default 15 m.', + }).optional(), + terraceRiserM: measurement('length', 'm', { + min: 0.2, + max: 1.5, + description: 'Terrace riser: the batter in steps of this height. Omit for a plain batter.', + }).optional(), + retainM: measurement('length', 'm', { + positive: true, + max: 12, + description: + 'hillside: the most ground the face holds over the base; default the height of the storey. Ground over it is cut back at the batter.', + }).optional(), + areawayM: measurement('length', 'm', { + min: 0, + max: 10, + description: + 'hillside: distance from the walls to the face that holds the ground; default 0, the walls themselves hold it.', + }).optional(), + wallM: measurement('length', 'm', { + min: 0, + max: 6, + description: + 'Declared retaining wall at the pad edge, on the side the ground leaves the pad; omit for none.', + }).optional(), + exactWall: z + .boolean() + .optional() + .describe('Write the wall as a terrain break instead of a lattice step. Needs wallM.'), + }, +} + +export const seatHouseOutput = { + strategy: z.enum([...SEAT_STRATEGIES, 'ground']), + levelId: z.string(), + buildingId: z.string(), + groundAtWallsM: z.number(), + padEdgeM: z.number(), + movedBuildingByM: z.number(), + floorM: z.number(), + groundUnderHouseM: z.object({ lowest: z.number(), highest: z.number(), mean: z.number() }), + cutVolumeM3: z.number(), + fillVolumeM3: z.number(), + netM3: z.number(), + batterSlopeDeg: z.number().optional(), + steepestSampledSlopeDeg: z.number().optional(), + daylight: z + .object({ reached: z.boolean(), farthestChangeM: z.number(), outsideLotM2: z.number() }) + .optional(), + wall: z.looseObject({ heightM: z.number(), exact: z.boolean() }).optional(), + terraces: z + .object({ riserM: z.number(), treadM: z.number(), resolutionM: z.number() }) + .optional(), + walkOut: z + .object({ + lowerLevelId: z.string(), + lowerBaseM: z.number(), + openSide: point, + fallAcrossHouseM: z.number(), + storeyBelowM: z.number(), + apron: z.array(point).optional(), + }) + .optional(), + lowLine: z + .object({ + lengthM: z.number(), + summitM: z.number(), + lowestM: z.number(), + deepestCutM: z.number(), + outlets: z.number().int(), + }) + .optional(), + hillside: z + .object({ retainM: z.number(), areawayM: z.number(), faceBreakId: z.string().optional() }) + .optional(), + floorsPutBack: z.array(z.string()).optional(), + stepsResolved: z + .array( + z.object({ + stairId: z.string(), + doorId: z.string(), + stepCount: z.number().int().optional(), + riseM: z.number().optional(), + removed: z.literal(true).optional(), + }), + ) + .optional(), + unmet: z.array(z.string()), + changedSamples: z.number().int(), + after: z.object({ + floorOverGroundM: range, + clearHeightM: z.number(), + doors: z.array( + z.object({ + doorId: z.string(), + levelId: z.string(), + stepM: z.number(), + outside: z.string(), + }), + ), + open: z.array(findingOutput), + }), + sampling: samplingOutput.optional(), +} + +const polygonArea = z + .array(point) + .max(512) + .describe('Polygon corners in order, [x,z] metres in the site frame. At most 512 corners.') +const circleArea = z.strictObject({ + center: point.describe('Centre [x,z] in site-frame metres.'), + radiusM: measurement('length', 'm', { + positive: true, + max: 1000, + description: 'Circle radius in metres.', + }), +}) + +export const setTerrainPlaneTool = { + name: 'set_terrain_plane', + title: 'Set terrain plane', + description: + 'Set the ground over an area (a polygon of [x,z] corners or a circle {center, radiusM}) to one sloping plane: a lot that falls to the street, a lawn with a cross fall, a level bench. through gives the plane by points with heights, metres above datum: three points not in a line fix it; two points give a plane that rises from one to the other and is level across that direction; one point gives a level plane at its height. Outside the area the ground blends back to what was there over blendM (default 0, a hard edge), in proportion to the distance from the area. ' + + 'Writes level-0 tiles at 0.5 m, never the frozen legacy site.terrain; heights are quantised to 0.01 m; a numeric terrain-break plane wins over what is written under it. Scope lot (default) keeps the area and the write inside the property. ' + + 'Returns slopePercent and fallDirection (unit [x,z] pointing downhill; [0,0] for a level plane), minM and maxM over the area after, cutVolumeM3, fillVolumeM3, netM3, changedSamples and sampling; volumes are estimates over the quantised field. One undo step. ' + + 'Refusals: no_site, ambiguous_site, no_terrain, invalid_input (points that coincide or lie in a line, a point that is not finite or lies more than 500 m from the property), footprint_empty, invalid_polygon, outside_property, no_change, sampling_limit (the area with its blend holds more than 400,000 terrain samples: about 300 m square).', + input: { + scope: terrainScope, + area: z + .union([polygonArea, circleArea]) + .describe('A polygon of [x,z] corners, or a circle {center, radiusM}.'), + through: z + .array( + z.strictObject({ + at: point.describe('A point [x,z] in site-frame metres.'), + heightM: measurement('length', 'm', { + min: -1000, + max: 1000, + description: 'Height of the plane at that point, metres above datum.', + }), + }), + ) + .min(1) + .max(3) + .describe('One, two or three points the plane passes through, each with its height.'), + blendM: measurement('length', 'm', { + min: 0, + max: 30, + description: 'Distance outside the area over which the ground blends back; default 0.', + }).optional(), + }, +} + +export const terrainPlaneOutput = { + slopePercent: z.number(), + fallDirection: point, + minM: z.number(), + maxM: z.number(), + cutVolumeM3: z.number(), + fillVolumeM3: z.number(), + netM3: z.number(), + changedSamples: z.number().int(), + sampling: samplingOutput, +} + +export const gradeAlongLineTool = { + name: 'grade_along_line', + title: 'Grade along line', + description: + 'Grade a strip of ground along a line: the bed of a drive or a path that follows the ground within a slope limit, a swale (the strip lowered), a berm (the strip raised). line is the centreline, [x,z] points in order in the site frame; the strip is widthM wide (default 1.2 m) and level across. Along the line the strip stands offsetM over the ground that is there (default 0; negative for a swale, positive for a berm); with maxSlopePercent the profile is eased so no stretch is steeper, cutting the rises and filling the dips it must, and it keeps the ground height (plus offsetM) at both ends unless startHeightM or endHeightM state them. Beside the strip the ground is a batter, 1 m of height per run metres (default 2), to the ground that was there. ' + + 'Writes level-0 tiles at 0.5 m; heights are quantised to 0.01 m; a numeric terrain-break plane wins over what is written under it. Scope lot (default) writes nothing outside the property. It lays no surface: outline is the strip as a polygon, for a surface laid on it. ' + + 'Returns lengthM, startM and endM (strip heights at the ends), steepestPercent (of the strip) and groundSteepestPercent (of the ground along the line before), profile (the strip height and the ground before at its breakpoints, sM metres along), outline, cutVolumeM3, fillVolumeM3, netM3, deepestCutM, highestFillM, changedSamples and sampling, and for a strip lowered into the ground (offsetM under 0) drains: where its bottom is lowest (start, end or between), that height, and standingWaterM, the depth of the closed hollow the strip leaves (0 where it comes out on lower ground: a swale that leads somewhere). One undo step. ' + + 'Limits, checked before anything is sampled: the line is at most 2,000 m long and 64 points, every point within 500 m of the property, the strip and its batters at most 40 m to a side, the edit at most 400,000 terrain samples. ' + + 'Refusals: no_site, ambiguous_site, no_terrain, invalid_input (a point that is not finite or lies more than 500 m from the property, an end height with no slope limit, a strip so far off the ground that its batters would pass 40 m), outside_property, slope_limit_unreachable (the ends differ by more than the limit allows over this length; the message states the length that would hold it), no_change, sampling_limit (a line over 2,000 m, or an edit over 400,000 samples).', + input: { + scope: terrainScope, + line: z + .array(point) + .min(2) + .max(64) + .describe('Centreline points in order, [x,z] metres in the site frame.'), + widthM: measurement('length', 'm', { + positive: true, + max: 20, + description: 'Width of the level strip; default 1.2 m.', + }).optional(), + offsetM: measurement('length', 'm', { + min: -3, + max: 3, + description: + 'Height of the strip over the ground that is there; default 0. Negative lowers it (a swale), positive raises it (a berm).', + }).optional(), + maxSlopePercent: z + .number() + .positive() + .max(100) + .optional() + .describe('Steepest grade along the strip, percent; omit to follow the ground as it is.'), + startHeightM: measurement('length', 'm', { + min: -1000, + max: 1000, + description: 'Height of the strip at the first point; default the ground there plus offsetM.', + }).optional(), + endHeightM: measurement('length', 'm', { + min: -1000, + max: 1000, + description: 'Height of the strip at the last point; default the ground there plus offsetM.', + }).optional(), + run: z + .number() + .min(0.25) + .max(20) + .optional() + .describe('Side batter run: horizontal metres per metre of height; 0.25–20, default 2.'), + }, +} + +export const gradeAlongLineOutput = { + lengthM: z.number(), + startM: z.number(), + endM: z.number(), + steepestPercent: z.number(), + groundSteepestPercent: z.number(), + profile: z.array(z.object({ sM: z.number(), heightM: z.number(), groundM: z.number() })), + outline: z.array(point), + cutVolumeM3: z.number(), + fillVolumeM3: z.number(), + netM3: z.number(), + drains: z + .object({ + lowestAt: z.enum(['start', 'end', 'between']), + lowestM: z.number(), + standingWaterM: z.number(), + }) + .optional(), + deepestCutM: z.number(), + highestFillM: z.number(), + changedSamples: z.number().int(), + sampling: samplingOutput, +} + +export const addStepsToGroundTool = { + name: 'add_steps_to_ground', + title: 'Add steps to ground', + description: + 'Add the outside flight an exterior door needs to reach the ground: its top at the sill, against the wall, its foot on the ground in front of the door, the rise and the run solved from the two (no riser over 0.19 m, two risers and a going of 0.63 m). The door is one with a floor on one side only; the ground is the persisted terrain or the flat datum. width defaults to the door width plus 0.4 m. ' + + 'Returns stairId, doorId, stepCount, riseM, runM, sillM, the foot [x,z] in the site frame and groundAtFootM. One undo step. ' + + 'Refusals: node_not_found, not_a_door, not_exterior (a floor on both sides of the door, or on neither), steps_not_needed (the sill is within 0.05 m of the ground outside), door_below_ground (the ground stands over the sill: grade it first), steps_too_tall (2 m or more, or a storey: that is a flight between storeys, not steps to the ground), building_rotation_unsupported, no_site, ambiguous_site, no_terrain.', + input: { + doorId: NodeId.describe('The exterior door the steps climb to.'), + width: measurement('length', 'm', { + positive: true, + max: 6, + description: 'Width of the flight; default the door width plus 0.4 m.', + }).optional(), + }, +} + +export const stepsToGroundOutput = { + stairId: z.string(), + doorId: z.string(), + stepCount: z.number().int(), + riseM: z.number(), + runM: z.number(), + sillM: z.number(), + foot: point, + groundAtFootM: z.number(), +} + +export const addTerracesTool = { + name: 'add_terraces', + title: 'Add terraces', + description: + 'Cut a slope into level terraces that touch, one below the other, each held by a wall or a bank, with the steps between them. line is the way down: two [x,z] points in the site frame, from the upper edge of the first terrace to the lower edge of the last; the terraces are count equal rectangles along it (2 to 12, each 1.5 m deep or more), widthM wide across it, centred on it. ' + + 'Their heights, metres above datum: with neither topM nor bottomM each terrace stands at the mean of the ground under it, so its cut and its fill are alike; topM alone or bottomM alone states that terrace and the others keep their steps from it; both give equal risers between them. ' + + 'Every second terrace, from the first, is written as a closed retaining terrain break at its exact height (a wall on its four sides wherever the ground beside it stands higher or lower), and the terraces between as level ground on the 0.5 m lattice: two neighbours meet at one vertical face with no ground between them. Beyond the sides of a terrace that is not a break, and beyond the lower edge of the last one when count is even, the ground is a bank, 1 m of height per run metres (default 2), to the ground that was there. A numeric terrain-break plane wins over what is written under it. Scope lot (default) writes nothing outside the property. ' + + 'stepsAt, 0 to 1 across the width (0.5 is the middle), puts a flight from each terrace up to the one above it there: its foot on the lower terrace, its top at the face, rise and run solved from the two heights (no riser over 0.19 m). A flight belongs to a level of a building: with none in the scene no flight is made and the answer says so. ' + + 'Returns terraces (index, levelM, outline, heldAs break or lattice, breakId, the ground under it before as lowest and highest), edges (top, each pair of neighbours and bottom: the height between and what holds it, wall or bank), steps (stairId, from and to terrace, riseM, stepCount) or stepsNote, cutVolumeM3, fillVolumeM3, netM3, changedSamples and sampling. One undo step. ' + + 'Limits, checked before anything is sampled: both points finite and within 500 m of the property, the line 3 to 200 m long, widthM at most 100 m, the edit at most 400,000 terrain samples. ' + + 'Refusals: no_site, ambiguous_site, no_terrain, invalid_input (a line under 3 m or over 200 m, terraces under 1.5 m deep, a point that is not finite or lies more than 500 m from the property), outside_property, crossing_breaks, conflicting_breaks, unsupported_geometry, no_change, sampling_limit.', + input: { + scope: terrainScope, + line: z + .array(point) + .length(2) + .describe( + 'The way down: [x,z] of the upper edge of the first terrace, then of the lower edge of the last, site frame.', + ), + widthM: measurement('length', 'm', { + positive: true, + max: 100, + description: 'Width of the terraces across the line, centred on it.', + }), + count: z.number().int().min(2).max(12).describe('How many terraces, 2 to 12.'), + topM: measurement('length', 'm', { + min: -1000, + max: 1000, + description: + 'Height of the first (upper) terrace, metres above datum; default the mean ground under it.', + }).optional(), + bottomM: measurement('length', 'm', { + min: -1000, + max: 1000, + description: + 'Height of the last (lower) terrace, metres above datum; default the mean ground under it.', + }).optional(), + run: z + .number() + .min(0.25) + .max(20) + .optional() + .describe('Bank run: horizontal metres per metre of height; 0.25–20, default 2.'), + stepsAt: z + .number() + .min(0) + .max(1) + .optional() + .describe( + 'Where across the width the flights between terraces stand, 0 to 1; omit for no flights.', + ), + }, +} + +export const addTerracesOutput = { + terraces: z.array( + z.object({ + index: z.number().int(), + levelM: z.number(), + outline: z.array(point), + heldAs: z.enum(['break', 'lattice']), + breakId: z.string().optional(), + groundBeforeM: z.object({ lowest: z.number(), highest: z.number() }), + }), + ), + edges: z.array( + z.object({ + at: z.string(), + heightM: z.number(), + heldBy: z.enum(['wall', 'bank', 'none']), + }), + ), + steps: z + .array( + z.object({ + stairId: z.string(), + fromTerrace: z.number().int(), + toTerrace: z.number().int(), + riseM: z.number(), + stepCount: z.number().int(), + }), + ) + .optional(), + stepsNote: z.string().optional(), + cutVolumeM3: z.number(), + fillVolumeM3: z.number(), + netM3: z.number(), + changedSamples: z.number().int(), + sampling: samplingOutput, +} diff --git a/packages/core/src/agent-tools/terrain.ts b/packages/core/src/agent-tools/terrain.ts new file mode 100644 index 0000000000..e232498111 --- /dev/null +++ b/packages/core/src/agent-tools/terrain.ts @@ -0,0 +1,526 @@ +import { z } from 'zod' +import { measurement } from './measurement' + +// Arrays avoid tuple-form JSON schemas that some MCP clients cannot call. +const point = z.array(z.number()).length(2) +const resolution = z.number().positive().optional() +const samplingOutput = z.looseObject({ + approximate: z.literal(true), + method: z.string(), + spacingM: z.number(), + heightStepM: z.number(), + sampleCount: z.number().int(), +}) + +const breakRange = z.object({ minM: z.number(), maxM: z.number() }) +export const terrainBreakOutput = { + breakId: z.string(), + line: z.array(point), + kind: z.enum(['cliff', 'retaining', 'soil']), + lengthM: z.number(), + left: breakRange, + right: breakRange, + dropMinM: z.number(), + dropMaxM: z.number(), + faceAreaM2: z.number(), + sampling: z + .looseObject({ + approximate: z.literal(true), + method: z.string(), + spacingM: z.number(), + sampleCount: z.number().int(), + }) + .optional(), +} +const breaksOutput = z.array(z.object(terrainBreakOutput)).optional() + +const terrainRefusals = + 'Returns breaks with directed side height ranges, nonnegative absolute side-to-side drop range and vertical face area; ground-side facts are labelled numerical samples. Slopes and normals do not average across breaks. Contour cells straddling breaks are omitted rather than interpolated into a false slope; break lines are reported separately. Refusals: no_site, ambiguous_site (more than one site), no_terrain (a persisted field that cannot be read or is not finite; a site with no shaped ground is not refused, it is the flat datum plane and answers with hasTerrain false and level facts), invalid_input, sampling_limit (sampling budget exceeded), unsupported_geometry (unsupported persisted break or insufficient same-side ground samples), crossing_breaks, conflicting_breaks (closed numeric exterior combined with other features). Reads persisted terrain only, never an unfinished sculpt stroke; changes nothing.' + +const writeRefusals = + 'Numeric terrain-break planes override later base sculpt and tile writes: edit the feature heights to change those effective surfaces. Reported sample changes and sample height ranges describe the tile edit, not an effective height change beneath a numeric break. ' + + 'Refusals: no_site, ambiguous_site (more than one site), no_terrain (a persisted field that cannot be read or is not finite), invalid_input, footprint_empty, invalid_polygon, outside_property (the area reaches past the site polygon without scope context), no_change (no sample would move), sampling_limit (the edit exceeds the bounded sample budget). Writes level-0 terrain tiles at 0.5 metre spacing, never rewrites the frozen legacy site.terrain. The write is one undo step, ends any unfinished sculpt stroke first, and works from persisted ground, never that stroke. New tiles sample the existing ground or its slope continuation before editing, including legacy grids with any spacing or origin. Untouched points inside seeded tiles may differ through height quantization and triangle resampling; planar ground differs by at most half the tile height step, while old creases can differ more. Heights are quantised to the tile step, so reported heights are the achieved sample heights.' + +const terrainScope = z + .enum(['lot', 'context']) + .optional() + .describe('Default lot: stay inside the property. Context explicitly allows shaping beyond it.') + +const polygonArea = z + .array(point) + .max(512) + .describe('Polygon corners in order, [x,z] metres in the site frame. At most 512 corners.') +const circleArea = z.strictObject({ + x: z.number().describe('Centre x in site-frame metres.'), + z: z.number().describe('Centre z in site-frame metres.'), + radiusM: measurement('length', 'm', { + positive: true, + description: 'Circle radius in metres.', + }), +}) + +export const addTerrainBreakTool = { + name: 'add_terrain_break', + title: 'Add terrain break', + description: + 'Numeric feature heights keep precedence over later brushes and base-tile writes; edit the feature heights to move those planes. ' + + 'Create one vertical cliff, retaining or soil boundary under the site (cliff is bare rock, retaining a built wall, soil an earth face), without changing terrain samples or frozen legacy data. line is directed site-frame [x,z] metres; positive XZ cross product is left and points exactly on the line choose left. Numeric sides are exact elevations; ground preserves the effective surrounding terrain, using only same-region base samples where no other feature sets a height. Give at least one numeric side. Open lines must be straight, ordered and collinear, covering the whole lot intersection; their supporting line separates half-planes through context too. Closed lines repeat the first point and must be simple convex CCW (left inside). No batter. Breaks cannot cross or touch. At most one open feature; closed rings apply outer-to-inner, so a pad overrides a surrounding cliff independently of ids. A closed numeric exterior cannot be combined with another feature. Keep-ground preserves wholly same-region source triangles and extends the nearest such triangle where the original straddles a break, bounded to 32 source-grid cells; too-narrow sampled regions are refused, not blended across the break. scope defaults lot; context permits authored line outside the property. Returns breakId, line, kind, lengthM, left/right height ranges, nonnegative absolute dropMinM/dropMaxM and vertical faceAreaM2; ground traces carry a numerical sampling label. Refusals: no_site, ambiguous_site, invalid_input, unsupported_geometry, crossing_breaks, conflicting_breaks, outside_property, no_terrain, sampling_limit. One undo step.', + input: { + line: z.array(point).min(2).max(513), + kind: z.enum(['cliff', 'retaining', 'soil']), + left: z.union([z.number(), z.literal('ground')]), + right: z.union([z.number(), z.literal('ground')]), + scope: terrainScope, + name: z.string().optional(), + }, +} + +export const readSiteTerrainTool = { + name: 'read_site_terrain', + title: 'Read site terrain', + description: + 'Read ground facts over footprint, default the site polygon: hasTerrain (false where no relief is shaped: the ground is then the flat datum plane at y = 0, answered with level facts and a note), flat, reliefM (maxM minus minM), minM, maxM, datumM:0, slopeMeanDeg (area-weighted interior samples), slopeMaxDeg, slopeAtCorners with unit normals, edgeDrops with signed dropM = height(from) minus height(to) and sampled maxSlopeDeg, areaAboveGradeM2 and areaBelowGradeM2. Areas are plan-area estimates above/below scene datum y=0, not earthwork volumes. Relief, flatness, aggregate slopes and areas are sampled estimates, labelled with sampling method, cellM, field spacing/height quantization and sampleCount; peaks between samples can be missed. Interior cell midpoints are weighted by their rectangular cell area, boundary cells are included only when their midpoint is inside the footprint; corners and edge samples contribute extrema, not the mean or area. cellM defaults to field spacing. Coordinates are site-frame [x,z] metres, slopes in degrees from horizontal. Slopes and normals use core central differences at field spacing, sampling the same continuation beyond authored borders. Additional refusals: footprint_empty, invalid_polygon, sampling_insufficient (no interior midpoint; use a finer cellM). ' + + terrainRefusals, + input: { + footprint: z + .array(point) + .max(512) + .optional() + .describe( + 'Footprint corners in order, [x,z] metres; default the site polygon. At most 512 corners to bound validation work.', + ), + cellM: resolution.describe( + 'Maximum interior cell size and edge sample spacing in metres; default field spacing. At most 20,000 samples including corners and edges.', + ), + }, + annotations: { readOnlyHint: true }, +} + +export const sampleTerrainLineTool = { + name: 'sample_terrain_line', + title: 'Sample terrain line', + description: + 'Read one straight segment from `from` to `to` in site-frame [x,z] metres. Returns points [{x,z,yM,slopeDeg}] including both endpoints (one point for a zero-length segment), with heights above scene datum y=0 and slope degrees from horizontal. Slopes use core central differences at field spacing, sampling the same continuation beyond authored borders. stepM is the maximum gap, default field spacing; samples divide the segment evenly. A polyline is the concatenation of segment calls. sampling labels the profile as discrete samples, with stepM, actualStepM, field spacing/height quantization and sampleCount; terrain between samples is not measured by this profile. ' + + terrainRefusals, + input: { + from: point.describe('Segment start [x,z] in site-frame metres.'), + to: point.describe('Segment end [x,z] in site-frame metres.'), + stepM: resolution.describe( + 'Maximum gap between samples in metres; default field spacing. At most 20,000 points.', + ), + }, + annotations: { readOnlyHint: true }, +} + +export const readTerrainContoursTool = { + name: 'read_terrain_contours', + title: 'Read terrain contours', + description: + 'Read contours of the persisted heightfield at intervalM (default 1 metre), levels at multiples of the interval from scene datum y=0. Returns {datum:0, lines:[{levelM,points:[[x,z],...]}], sampling}. This is a marching-squares approximation at field spacing, with centimetre endpoint chaining and a site-polygon midpoint mask: whole segments are retained by midpoint, so endpoints can extend up to a cell outside the lot. It is not an exact triangle-plane contour or a surveyed/geographic elevation. Flat fields legitimately return no lines. sampling labels method, intervalM, field spacing/height quantization and sampleCount (returned contour vertices). Additional refusals: footprint_empty, invalid_polygon, contour_limit (more than 400 level intervals, more than 2,000,000 cell-level visits or more than 20,000 returned vertices). ' + + terrainRefusals, + input: { + intervalM: resolution.describe( + 'Vertical interval in metres; default 1. Too many levels are refused, never silently reported as no contours.', + ), + }, + annotations: { readOnlyHint: true }, +} + +export const shapeSiteTerrainTool = { + name: 'shape_site_terrain', + title: 'Shape site terrain', + description: + 'Shape the persisted ground over an area (a polygon of [x,z] corners or a circle {x,z,radiusM}), inside the site polygon by default, or beyond it with scope context. Verbs: flatten sets samples to heightM (required for flatten); raise/lower move samples by heightM metres (default 1, the sculpt stroke metre); smooth lerps samples toward an 8-pass diffusion of the field, as the sculpt smooth brush does. strength (0..1, default 1) scales the effect; softness fades it linearly over that many metres inside the area edge (default 0, a hard edge). Returns {changedSamples, beforeMinMaxM, afterMinMaxM, touchedM2, sampling}: the min/max heights over the touched samples before and after, and their plan area at field spacing (an estimate, labelled in sampling). ' + + writeRefusals, + input: { + scope: terrainScope, + verb: z.enum(['flatten', 'raise', 'lower', 'smooth']).describe('How to move the ground.'), + area: z + .union([polygonArea, circleArea]) + .describe( + 'A polygon of [x,z] corners, or a circle {x, z, radiusM}; inside the property unless scope is context.', + ), + heightM: measurement('length', 'm', { + description: + 'Flatten target height in metres above datum (required for flatten), or the metres raise/lower move the ground.', + }).optional(), + strength: z + .number() + .min(0) + .max(1) + .optional() + .describe('Fraction of the full effect to apply, 0..1; default 1.'), + softness: measurement('length', 'm', { + min: 0, + description: 'Edge falloff distance in metres inside the area; default 0.', + }).optional(), + }, +} + +export const carveTerrainPadTool = { + name: 'carve_terrain_pad', + title: 'Carve terrain pad', + description: + 'Level a pad of ground at one height and blend it back to the existing ground. The pad polygon (site-frame [x,z] metres, inside the property unless scope context) is set exactly to padHeightM, or to padFromHighestM metres below the highest sample under the pad; give exactly one. Outside the pad, samples within blendM (default 0) move toward the pad height in proportion to their distance from the pad edge, never past it and never upward: the blend ring only cuts. With default scope lot it also stays inside the property. Returns {cutVolumeM3, fillVolumeM3, netM3 (cut minus fill), padAreaM2, padHeightM, maxSlopeIntoPadDeg, retainingHeightM, changedSamples, sampling}. Cut is earth removed above the pad surface, fill earth added below it; volumes are integrals over the quantised field at its spacing — estimates with their resolution in sampling, not survey numbers. retainingHeightM gives, per pad edge, the highest original ground above the pad along that edge (0 where the ground falls away). Additional refusal: pad_too_small (no field sample falls inside the pad). ' + + 'edges defaults slope. With edges slope and blendM 0 (the default), a convex pad is written as an exact closed terrain break of kind soil at the pad height, ground outside, without tile writes: a slope with no run is a vertical earth face. Then changedSamples is 0; breaks[0] carries the face (kind soil, faceAreaM2, dropMinM and dropMaxM); cutVolumeM3, fillVolumeM3 and netM3 are plan-area integrals over the pad, not sample sums; retainingHeightM is, per pad edge, the greatest height of the face along it, whether the ground stands above or below the pad; maxSlopeIntoPadDeg is 90 where a face has height and 0 otherwise. A pad that already stands on the ground writes nothing (no_change). A pad that cannot be a break, because it is not convex or its break would cross or touch another terrain break, keeps the lattice write, and edge says so: {kind lattice_step, exact false, reason, resolutionM, note}; its step then passes through lattice triangles up to one cell wide rather than along the pad line. With blendM above 0 the blend ring is written as above and the pad stays on the lattice. ' + + 'With edges cliff or retaining, creates a convex CCW closed terrain break (cliff bare rock, retaining a built wall) at the exact pad height, ground outside, without tile writes; blendM must be zero. ' + + writeRefusals, + input: { + scope: terrainScope, + edges: z.enum(['cliff', 'retaining', 'slope']).optional(), + pad: polygonArea.describe( + 'Pad polygon corners in order, [x,z] metres; inside the property unless scope is context.', + ), + padHeightM: measurement('length', 'm', { + description: 'Absolute pad height in metres above datum. Give this or padFromHighestM.', + }).optional(), + padFromHighestM: measurement('length', 'm', { + min: 0, + description: + 'Cut this many metres below the highest ground under the pad. Give this or padHeightM.', + }).optional(), + blendM: measurement('length', 'm', { + min: 0, + description: 'Distance outside the pad over which ground blends back to existing; default 0.', + }).optional(), + }, +} + +const gradePadInput = z.strictObject({ + levelId: z + .string() + .optional() + .describe("Level whose largest slab is this pad's house outline. Not with footprint."), + footprint: polygonArea + .optional() + .describe( + "This pad's outline, [x,z] metres in the site frame; needs padHeightM. Not with levelId.", + ), + padHeightM: measurement('length', 'm', { + description: + 'Absolute height of this pad in metres above datum; default its slab top minus padBelowSlabM.', + }).optional(), + padBelowSlabM: measurement('length', 'm', { + min: 0, + max: 2, + description: 'How far under its slab top this pad stands when padHeightM is not given.', + }).optional(), + marginM: measurement('length', 'm', { + min: 0, + max: 10, + description: 'How far this pad reaches beyond its outline; default the top-level marginM.', + }).optional(), +}) + +export const gradeAroundHouseTool = { + name: 'grade_around_house', + title: 'Grade around house', + description: + 'Grade the ground around a house as a function of the distance to its outline. The outline is the largest slab of a level (levelId, default the lowest level with a slab) or a footprint given ([x,z] corners; then padHeightM is required). Out to marginM from the outline (default 1.0 m) the ground is a pad at padHeightM, by default padBelowSlabM (0.15 m) under the slab top. Beyond it the ground is a batter, 1 m of height per run metres (run 2 is 1:2; default 2), falling where the ground was lower and rising where it was higher until it meets the ground that was there (the daylight line); ground beyond reachM (default 15 m) from the pad edge is not touched. Distance is Euclidean to the outline, so the contours are the outline offset, rounded at convex corners: a curved house gets a curved slope. terraceRiserM (0.2–1.5 m) cuts the batter into steps, each tread run times the riser, on the 0.5 m lattice (a tread under 1 m is not drawn). ' + + 'wallM (0–6 m) declares a retaining wall at the pad edge on whichever side the ground leaves the pad: the ground beyond starts wallM above the pad where it rises and wallM below it where it falls. By default it is a vertical step on the 0.5 m lattice (exact false). exactWall true writes a retaining terrain-break instead (exact true, with its breakId): it needs wallM above 0 and one pad, rings the convex hull of the outline (a notch is filled into the pad) or, with edge, the pad strip, replaces the wall an earlier call made for the same house, and refuses crossing_breaks, unsupported_geometry (a strip that is not convex across the lot) and outside_property. ' + + 'upperLevelM is a flat lawn after the bank: the ground beyond the bank is raised or cut to that height, out to the property edge (scope context: to reachM). ' + + "edge grades across the lot along one straight edge instead of around the outline: the outline is extended along the edge, so pad, wall, bank and lawn run the lot's whole width. Give exactly one of facing (front, rear, left or right of the lot, the street edge being the front), direction [x,z] (the side of the outline facing that way) or line [[x,z],[x,z]] (on or beyond the outline). The pad is the strip from the front of the outline to the edge plus marginM; its front batters as a ring does; upperLevelM applies beyond the edge only. With exactWall the wall is a closed break around the pad strip (padStripM, along the edge's normal), clipped to the property: the ground is level inside it and meets the ground outside it in a face, so the lot in front of the strip keeps its own fall. " + + 'pads gives one pad per level of a split-level house, each its own levelId (or footprint with padHeightM), padHeightM, padBelowSlabM and marginM (the top-level values are the defaults); a sample follows the nearest outline, so abutting pads at different heights meet in a step. pads excludes the top-level levelId, footprint and padHeightM; edge and exactWall take one pad. ' + + 'Writes level-0 tiles at 0.5 m, never the frozen legacy site.terrain; heights are quantised to 0.01 m. A numeric terrain-break plane wins over what is written under it; otherwise the later of this tool, carve_terrain_pad and shape_site_terrain wins, and an earlier pad is ground the batter meets (without upperLevelM it never raises ground above its pad on a cut side nor lowers it below on a fill side). Scope lot (default) writes nothing outside the property. ' + + "Returns padHeightM and marginM (or pads), batterSlopeDeg (the stated batter), cutVolumeM3, fillVolumeM3, steepestSampledSlopeDeg (an exact wall's face is not in the tiles), daylight {reached, farthestChangeM, outsideLotM2}, lawn, edge, wall, terraces; volumes are estimates over the quantised field. One undo step. " + + 'Refusals: no_site, ambiguous_site, no_terrain, invalid_input, invalid_polygon, footprint_empty, level_not_found, not_a_level, no_building, building_rotation_unsupported, disconnected_footprint, outside_property, crossing_breaks, conflicting_breaks, unsupported_geometry, no_change (no sample would move), sampling_limit.', + input: { + scope: terrainScope, + levelId: z + .string() + .optional() + .describe( + 'Level whose largest slab is the house outline; default the lowest level with a slab. Not with footprint or pads.', + ), + footprint: polygonArea + .optional() + .describe( + 'A house outline to grade around, [x,z] metres in the site frame; needs padHeightM. Not with levelId or pads.', + ), + padHeightM: measurement('length', 'm', { + description: + 'Absolute pad height in metres above datum; default the slab top minus padBelowSlabM.', + }).optional(), + padBelowSlabM: measurement('length', 'm', { + min: 0, + max: 2, + description: + 'How far under the slab top the pad stands when padHeightM is not given; default 0.15 m.', + }).optional(), + marginM: measurement('length', 'm', { + min: 0, + max: 10, + description: 'How far the pad reaches beyond the outline; default 1.0 m.', + }).optional(), + run: z + .number() + .min(0.25) + .max(20) + .optional() + .describe( + 'Batter run: horizontal metres per metre of height (2 is 1:2); 0.25–20, default 2.', + ), + reachM: measurement('length', 'm', { + positive: true, + max: 60, + description: + 'How far beyond the pad edge the batter is looked for; default 15 m, at most 60 m. A lawn (upperLevelM) holds past it to the property edge.', + }).optional(), + terraceRiserM: measurement('length', 'm', { + min: 0.2, + max: 1.5, + description: + 'Terrace riser in metres: the batter in steps of this height. Omit for a plain batter.', + }).optional(), + wallM: measurement('length', 'm', { + min: 0, + max: 6, + description: + 'Declared retaining wall at the pad edge, in metres, on the side the ground leaves the pad; omit for none.', + }).optional(), + exactWall: z + .boolean() + .optional() + .describe( + 'Write the wall as a terrain-break (a real wall, exact true) instead of a lattice step. Needs wallM and one pad.', + ), + upperLevelM: measurement('length', 'm', { + description: + 'Absolute height in metres above datum of a flat lawn after the bank: raised or cut to it. Omit for ground that meets the natural slope.', + }).optional(), + edge: z + .strictObject({ + facing: z + .enum(['front', 'rear', 'left', 'right']) + .optional() + .describe( + 'The side of the lot the edge faces: the lot edge with that role (front is the street).', + ), + direction: point + .optional() + .describe('The edge faces this way, [x,z] in the site frame (need not be unit).'), + line: z + .array(point) + .length(2) + .optional() + .describe( + 'The edge stands on the line through these two [x,z] points, on or beyond the outline.', + ), + }) + .optional() + .describe( + 'Grade across the lot along one straight edge instead of around the outline. Give exactly one of facing, direction, line.', + ), + pads: z + .array(gradePadInput) + .min(1) + .max(6) + .optional() + .describe( + 'One pad per level, each with its own height and margin. Not with levelId or footprint.', + ), + }, +} + +const gradePadOutput = z.object({ + levelId: z.string().optional(), + slabId: z.string().optional(), + slabTopM: z.number().optional(), + footprint: z.array(point), + padHeightM: z.number(), + marginM: z.number(), + padAreaM2: z.number(), +}) + +export const gradeAroundHouseOutput = { + breaks: breaksOutput, + levelId: z.string().optional(), + slabId: z.string().optional(), + footprint: z.array(point).optional(), + slabTopM: z.number().optional(), + padHeightM: z.number().optional(), + marginM: z.number().optional(), + pads: z.array(gradePadOutput).optional(), + run: z.number(), + reachM: z.number(), + batterSlopeDeg: z.number(), + padAreaM2: z.number(), + cutVolumeM3: z.number(), + fillVolumeM3: z.number(), + netM3: z.number(), + changedSamples: z.number().int(), + steepestSampledSlopeDeg: z.number(), + daylight: z.object({ + reached: z.boolean(), + farthestChangeM: z.number(), + outsideLotM2: z.number(), + }), + lawn: z.object({ levelM: z.number(), bankRunM: z.number(), areaM2: z.number() }).optional(), + edge: z + .object({ + role: z.string().optional(), + normal: point, + frontM: z.number(), + edgeM: z.number(), + padStripM: z.object({ fromM: z.number(), toM: z.number() }), + }) + .optional(), + terraces: z + .object({ riserM: z.number(), treadM: z.number(), resolutionM: z.number() }) + .optional(), + wall: z + .object({ + heightM: z.number(), + exact: z.boolean(), + resolutionM: z.number().optional(), + note: z.string().optional(), + breakId: z.string().optional(), + kind: z.literal('retaining').optional(), + lengthM: z.number().optional(), + }) + .optional(), + sampling: samplingOutput, +} + +export const setSiteLotTool = { + name: 'set_site_lot', + title: 'Set site lot', + description: + 'With an open terrain break, the new lot crossing must remain covered by its authored endpoints; otherwise refuses unsupported_geometry. Extend the break endpoints before enlarging the lot. ' + + 'Set the property polygon without rewriting existing ground, setbacks or street-edge indices. Give polygon, or both widthM and depthM for an axis-aligned rectangle centred at anchor (default the current lot bounds centre). Coordinates are site-frame [x,z] metres. New land reads the same continuous ground: authored tiles, then the frozen legacy field, then its border slope decaying over 64 metres to a horizontal context plane. That plane is the lower of datum zero and the frozen legacy minimum, or zero without a legacy field; it is an inferred continuation, not surveyed ground. Painted ground is not rewritten either: ground laid over the whole lot (Environment lay_ground with site) carries over onto new land, as grass of the same tint and height or the same surface; ground laid over part of the lot, or before that was kept, does not, and new land there stays unpainted until it is laid. Tiled ground has no fixed lot-size ceiling; facts use a bounded sampling resolution for large lots. Returns siteId, polygon, areaM2 and the sampled minM/maxM height range with resolution. Refusals: no_site, ambiguous_site, invalid_input, invalid_polygon, footprint_empty, no_terrain (unreadable persisted ground). One undo step.', + input: { + polygon: polygonArea.optional(), + widthM: measurement('length', 'm', { + positive: true, + description: 'Rectangle width in metres; give with depthM instead of polygon.', + }).optional(), + depthM: measurement('length', 'm', { + positive: true, + description: 'Rectangle depth in metres; give with widthM instead of polygon.', + }).optional(), + anchor: point.optional().describe('Rectangle centre [x,z]; default current lot bounds centre.'), + }, +} + +export const siteLotOutput = { + siteId: z.string(), + polygon: z.array(point), + areaM2: z.number(), + minM: z.number(), + maxM: z.number(), + sampling: samplingOutput, +} + +export const describeTerrainUnderHouseTool = { + name: 'describe_terrain_under_house', + title: 'Describe terrain under house', + description: + 'Advisory ground facts under a house: the footprint of the largest slab on a level (levelId, default the lowest level with a slab), in site-frame [x,z] metres, with slabTopM, highestM and lowestM ground under it, reliefM (highest minus lowest), clearanceUnderSlabM (slab top minus the highest ground: the least headroom under the slab), and dropAtEdges — per footprint edge, the largest fall from slab top to ground sampled along that edge. needsGuardAt lists the edges whose drop exceeds guardAdvisory.thresholdM. The guard link is advisory only, never a write: guardAdvisory states the threshold (the same 0.5 m verify_scene uses for its unguarded_drop observation — only the threshold is shared, since these drops compare slab top against terrain alone while verify_scene also accounts for landings, neighbouring surfaces and existing guards) and the typical requirement (a guard is typically required above about 0.76 m, IRC R312). Heights are sampled estimates at field spacing, labelled in sampling. Refusals: no_site, ambiguous_site, no_terrain, invalid_input, level_not_found, not_a_level, no_building, building_rotation_unsupported (the building tips out of the site plane), footprint_empty (no slab footprint on the level), disconnected_footprint (the largest slab is in several disconnected pieces), invalid_polygon, sampling_limit, sampling_insufficient. Where no relief is shaped the ground under the house is the datum plane, with a note. Reads persisted terrain only; changes nothing.', + input: { + levelId: z + .string() + .optional() + .describe( + 'Level whose largest slab is the house footprint; default the lowest level with a slab.', + ), + }, + annotations: { readOnlyHint: true }, +} + +export const siteTerrainOutput = { + breaks: breaksOutput, + hasTerrain: z.boolean(), + flat: z.boolean(), + reliefM: z.number(), + minM: z.number(), + maxM: z.number(), + datumM: z.literal(0), + slopeMeanDeg: z.number(), + slopeMaxDeg: z.number(), + slopeAtCorners: z.array( + z.object({ + x: z.number(), + z: z.number(), + slopeDeg: z.number(), + normal: z.array(z.number()).length(3), + }), + ), + edgeDrops: z.array( + z.object({ from: point, to: point, dropM: z.number(), maxSlopeDeg: z.number() }), + ), + areaAboveGradeM2: z.number(), + areaBelowGradeM2: z.number(), + note: z.string().optional(), + sampling: samplingOutput.extend({ cellM: z.number() }), +} + +export const terrainLineOutput = { + breaks: breaksOutput, + points: z.array(z.object({ x: z.number(), z: z.number(), yM: z.number(), slopeDeg: z.number() })), + note: z.string().optional(), + sampling: samplingOutput.extend({ stepM: z.number(), actualStepM: z.number() }), +} + +export const terrainContoursOutput = { + breaks: breaksOutput, + datum: z.literal(0), + lines: z.array(z.object({ levelM: z.number(), points: z.array(point) })), + note: z.string().optional(), + sampling: samplingOutput.extend({ intervalM: z.number() }), +} + +const minMaxOutput = z.object({ minM: z.number(), maxM: z.number() }) +const edgeOutput = z.object({ from: point, to: point }) + +export const shapeTerrainOutput = { + changedSamples: z.number().int(), + beforeMinMaxM: minMaxOutput, + afterMinMaxM: minMaxOutput, + touchedM2: z.number(), + sampling: samplingOutput, +} + +export const terrainPadOutput = { + breaks: breaksOutput, + cutVolumeM3: z.number(), + fillVolumeM3: z.number(), + netM3: z.number(), + padAreaM2: z.number(), + padHeightM: z.number(), + maxSlopeIntoPadDeg: z.number(), + retainingHeightM: z.array(edgeOutput.extend({ heightM: z.number() })), + changedSamples: z.number().int(), + sampling: samplingOutput, + /** Present when a pad with blendM 0 could not be written as an exact face. */ + edge: z + .object({ + kind: z.literal('lattice_step'), + exact: z.literal(false), + reason: z.string(), + resolutionM: z.number(), + note: z.string(), + }) + .optional(), +} + +export const terrainUnderHouseOutput = { + breaks: breaksOutput, + levelId: z.string(), + slabId: z.string(), + footprint: z.array(point), + slabTopM: z.number(), + highestM: z.number(), + lowestM: z.number(), + reliefM: z.number(), + clearanceUnderSlabM: z.number(), + dropAtEdges: z.array(edgeOutput.extend({ dropM: z.number() })), + needsGuardAt: z.array(edgeOutput.extend({ dropM: z.number() })), + guardAdvisory: z.object({ + advisory: z.literal(true), + thresholdM: z.number(), + basis: z.string(), + typicalRequirement: z.string(), + }), + note: z.string().optional(), + sampling: samplingOutput.extend({ cellM: z.number() }), +} diff --git a/packages/core/src/building/zone-wall-stretches.ts b/packages/core/src/building/zone-wall-stretches.ts new file mode 100644 index 0000000000..000af9e158 --- /dev/null +++ b/packages/core/src/building/zone-wall-stretches.ts @@ -0,0 +1,26 @@ +import type { WallNode, ZoneNode } from '../schema' + +type Vec2 = [number, number] + +/** How far beyond a wall's half thickness a room's edge still lies along it (m). */ +const EDGE_REACH = 0.15 + +/** The stretches of a room's edges lying along a wall line, as distances along that line. */ +function stretchesAlong(zone: ZoneNode, [sx, sz]: Vec2, [ex, ez]: Vec2, reach: number) { + const length = Math.hypot(ex - sx, ez - sz) + if (!length) return [] + const [ux, uz] = [(ex - sx) / length, (ez - sz) / length] + const off = ([x, z]: Vec2) => Math.abs((x - sx) * uz - (z - sz) * ux) + const at = ([x, z]: Vec2) => (x - sx) * ux + (z - sz) * uz + return zone.polygon.flatMap((p, i) => { + const q = zone.polygon[(i + 1) % zone.polygon.length] ?? p + if (off(p) > reach || off(q) > reach) return [] + const from = Math.max(0, Math.min(at(p), at(q))) + const to = Math.min(length, Math.max(at(p), at(q))) + return to - from > 0.05 ? [[from, to] as const] : [] + }) +} + +/** The stretches of a room's edges lying along a wall, within its half thickness and a margin. */ +export const stretchesAlongWall = (zone: ZoneNode, wall: WallNode) => + stretchesAlong(zone, wall.start, wall.end, (wall.thickness ?? 0.2) / 2 + EDGE_REACH) From 51b441bfc115d81743c7a7597ee28b4091bf146b Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 16 Nov 2026 21:07:03 +0100 Subject: [PATCH 03/11] viewer, editor: the underground view and the orbit on slopes The eye under the ground is measured against the ground the site actually draws: the sculpted lot to its property line, and past the line the horizon disc under the block's base (groundPastLot, set by the site renderer). groundHeightAt takes the scene's nodes, so the underground ambiance reads tiles and breaks, not only site.terrain. The orbit rests on the floor of a seated house, not on the datum (level-orbit-floor), and on Solid the sculpted ground holds the eye inside the property line only; the walkthrough stands on a walk-out's floor where the ground is drawn open over it. undergroundLook gains ground: 'drawn' | 'implied'. 'drawn' (the default) is what main does today; 'implied' draws no ground under the ground on any lot, so the inside of a hill looks like the underside of a flat lot. Off by default. Past the property line the eye is measured against the disc, not the field. This moves where the dark mode starts on every sculpted lot: a look decision for the team. The first-person collider reaches past the lot as well as the field: its test's expectation moves from +-1008 m to +-1015 m (the default 30 x 30 m lot reaches past the 16 m field), as the lab changed it. Co-Authored-By: Claude Opus 5.5 --- .../core/src/lib/site-ground-height.test.ts | 16 ++-- packages/core/src/lib/site-ground-height.ts | 11 ++- .../editor/custom-camera-controls.tsx | 18 ++--- .../floor-aware-camera-controls.test.ts | 26 +++++++ .../editor/floor-aware-camera-controls.ts | 10 ++- .../components/editor/floor-surface.test.ts | 67 +++++++++++++++++ .../src/components/editor/floor-surface.ts | 75 +++++++++++++++++-- .../editor/src/lib/level-orbit-floor.test.ts | 58 ++++++++++++++ packages/editor/src/lib/level-orbit-floor.ts | 23 ++++++ .../first-person/build-collider-world.test.ts | 11 ++- .../viewer/underground-ambiance.tsx | 23 +++++- packages/viewer/src/index.ts | 2 + .../src/lib/underground-ambiance.test.ts | 38 ++++++++++ .../viewer/src/lib/underground-ambiance.ts | 28 ++++++- packages/viewer/src/store/use-viewer.ts | 29 ++++++- .../systems/wall/wall-terrain-bottom.test.ts | 55 +++++++++++++- 16 files changed, 448 insertions(+), 42 deletions(-) create mode 100644 packages/editor/src/lib/level-orbit-floor.test.ts create mode 100644 packages/editor/src/lib/level-orbit-floor.ts diff --git a/packages/core/src/lib/site-ground-height.test.ts b/packages/core/src/lib/site-ground-height.test.ts index de2a7fa41d..c9256beb68 100644 --- a/packages/core/src/lib/site-ground-height.test.ts +++ b/packages/core/src/lib/site-ground-height.test.ts @@ -12,24 +12,28 @@ const site = Object.values(nodes).find((node) => node.type === 'site') as AnyNod describe('the height of the site’s ground at a point', () => { test('a flat site answers the plane its fill is drawn on, anywhere', () => { const flat = SiteNode.parse({ id: 'site_flat', children: [] }) - expect(groundHeightAt(flat, 0, 0)).toBe(FLAT_GROUND_Y) - expect(groundHeightAt(flat, -400, 900)).toBe(FLAT_GROUND_Y) + const scene = { [flat.id]: flat } as Record + expect(groundHeightAt(flat, scene, 0, 0)).toBe(FLAT_GROUND_Y) + expect(groundHeightAt(flat, scene, -400, 900)).toBe(FLAT_GROUND_Y) }) test('no site is a flat site too', () => { - expect(groundHeightAt(null, 3, 4)).toBe(FLAT_GROUND_Y) + expect(groundHeightAt(null, {} as Record, 3, 4)).toBe(FLAT_GROUND_Y) }) test('a sculpted site answers the terrain as it reads there', () => { - const field = terrainFieldOf(site as never) + const field = terrainFieldOf(site as never, nodes) if (!field) throw new Error('the owner hillside has terrain') const probes: Array<[number, number]> = [ [0, 0], [0, -14], [3, 9], ] - for (const [x, z] of probes) expect(groundHeightAt(site, x, z)).toBe(heightAt(field, x, z)) + for (const [x, z] of probes) + expect(groundHeightAt(site, nodes, x, z)).toBe(heightAt(field, x, z)) // The street side stands well over the pad the house sits on. - expect(groundHeightAt(site, 0, -14)).toBeGreaterThan(groundHeightAt(site, 0, 0) + 2) + expect(groundHeightAt(site, nodes, 0, -14)).toBeGreaterThan( + groundHeightAt(site, nodes, 0, 0) + 2, + ) }) }) diff --git a/packages/core/src/lib/site-ground-height.ts b/packages/core/src/lib/site-ground-height.ts index af52dd3510..ee5e317aab 100644 --- a/packages/core/src/lib/site-ground-height.ts +++ b/packages/core/src/lib/site-ground-height.ts @@ -1,4 +1,4 @@ -import type { AnyNode } from '../schema' +import type { AnyNode, AnyNodeId } from '../schema' import { heightAt } from './terrain-field' import { terrainFieldOf } from './terrain-source' @@ -13,7 +13,12 @@ export const FLAT_GROUND_Y = -0.05 * where the site has one, the flat plane everywhere else. `site` is the site node (the caller * knows it; looking it up here would walk every node for every call). */ -export function groundHeightAt(site: AnyNode | null | undefined, x: number, z: number): number { - const field = site?.type === 'site' ? terrainFieldOf(site) : null +export function groundHeightAt( + site: AnyNode | null | undefined, + nodes: Record, + x: number, + z: number, +): number { + const field = site?.type === 'site' ? terrainFieldOf(site, nodes) : null return field ? heightAt(field, x, z) : FLAT_GROUND_Y } diff --git a/packages/editor/src/components/editor/custom-camera-controls.tsx b/packages/editor/src/components/editor/custom-camera-controls.tsx index a84a20bd72..552dddf48c 100644 --- a/packages/editor/src/components/editor/custom-camera-controls.tsx +++ b/packages/editor/src/components/editor/custom-camera-controls.tsx @@ -14,13 +14,7 @@ import { sceneRegistry, useScene, } from '@pascal-app/core' -import { - GRID_LAYER, - getLevelPresentationY, - useSceneGroundReplacement, - useViewer, - ZONE_LAYER, -} from '@pascal-app/viewer' +import { GRID_LAYER, useSceneGroundReplacement, useViewer, ZONE_LAYER } from '@pascal-app/viewer' import { type CameraPoseApplicationPlan, frameViewerCamera, @@ -61,6 +55,7 @@ import { setKeyboardPanKey, syncKeyboardPanMotion, } from '../../lib/keyboard-pan' +import { levelOrbitFloorY } from '../../lib/level-orbit-floor' import { diveFloorY, MAX_ORBIT_POLAR_ANGLE, @@ -170,8 +165,7 @@ function orbitGroundY( levelId: string | null | undefined, levelMode: LevelMode = useViewer.getState().levelMode, ) { - const floorY = levelId ? getLevelPresentationY(levelId, useScene.getState().nodes, levelMode) : 0 - return floorY + ORBIT_TARGET_HEIGHT + return levelOrbitFloorY(levelId, useScene.getState().nodes, levelMode) + ORBIT_TARGET_HEIGHT } /** @@ -182,7 +176,7 @@ function orbitGroundY( function keepEyeOverGround(x: number, eyeY: number, z: number, previousEyeY = eyeY): number { const { nodes } = useScene.getState() const siteId = sceneRegistry.byType.site?.values().next().value as AnyNodeId | undefined - const groundY = groundHeightAt(siteId ? nodes[siteId] : null, x, z) + const groundY = groundHeightAt(siteId ? nodes[siteId] : null, nodes, x, z) return overviewEyeY(eyeY, previousEyeY, groundY, useViewer.getState().eyeUnderGround) } @@ -509,9 +503,7 @@ export const CustomCameraControls = ({ // Survives first-person (orbit unmounted) so scene-ready fit still applies // once CameraControls remount. const pendingFitSceneRef = useRef(null) - const floorY = useScene((state) => - currentLevelId ? getLevelPresentationY(currentLevelId, state.nodes, levelMode) : 0, - ) + const floorY = useScene((state) => levelOrbitFloorY(currentLevelId, state.nodes, levelMode)) const allowUnderground = !isPreviewMode && allowUndergroundCamera // With the ground on Auto the eye may dive under any building, down to the dive's floor; Solid // keeps the eye over the ground. diff --git a/packages/editor/src/components/editor/floor-aware-camera-controls.test.ts b/packages/editor/src/components/editor/floor-aware-camera-controls.test.ts index 835cdb5d80..fa72646914 100644 --- a/packages/editor/src/components/editor/floor-aware-camera-controls.test.ts +++ b/packages/editor/src/components/editor/floor-aware-camera-controls.test.ts @@ -393,6 +393,32 @@ test('a camera that drops from high above straight under a raised floor is held expect(controls.camera.position.y).toBeCloseTo(1 + GROUND_MIN_Y, 4) }) +test('a hill standing far over the level floor holds the eye, as a platform near it does', () => { + const hillside = (reachY?: number) => ({ + revision: 0, + reachY, + // The pad the house stands on, and a hill 6 m high past x = -8. + topAt: (x: number) => (x < -8 ? 6 : 0), + }) + const sweep = (surface: ReturnType) => { + const controls = groundFloorControls() + controls.floorSurface = surface + // A level orbit 5 m up, 16 m out, starting over the pad on the +x side. + controls.setLookAt(ROOM_CENTRE.x + 16, 5, ROOM_CENTRE.z, ROOM_CENTRE.x, 5, ROOM_CENTRE.z, false) + settleLong(controls) + expect(controls.camera.position.y).toBeCloseTo(5, 6) + // Half a turn takes the eye over the hill, a metre under its top. + controls.rotate(Math.PI, 0, false) + settleLong(controls, 240) + expect(controls.camera.position.x).toBeLessThan(-8) + return controls.camera.position.y + } + // The surface says how high it stands: the eye rides over the hill. + expect(sweep(hillside(6))).toBeCloseTo(6 + ORBIT_FLOOR_CLEARANCE, 4) + // A surface that says nothing is looked up near the level's floor only, as before. + expect(sweep(hillside())).toBeCloseTo(5, 6) +}) + test('over a hole in the floor the camera keeps the floor it came from, not the level below', () => { // A stair void over z < 3; a 0.5 m floor elsewhere. const controls = groundFloorControls() diff --git a/packages/editor/src/components/editor/floor-aware-camera-controls.ts b/packages/editor/src/components/editor/floor-aware-camera-controls.ts index c03b9af1e6..f1713dbecc 100644 --- a/packages/editor/src/components/editor/floor-aware-camera-controls.ts +++ b/packages/editor/src/components/editor/floor-aware-camera-controls.ts @@ -12,8 +12,9 @@ const virtualPosition = new Vector3() const groundedPosition = new Vector3() const drawnTarget = new Vector3() const shiftDelta = new Vector3() -// Below this height over the level's floor limit the surface under the camera -// is looked up; higher up it cannot matter. +// Below this height over the level's floor limit (or over the highest the +// surface stands, a hill) the surface under the camera is looked up; higher +// up it cannot matter. const SURFACE_BAND = 3 // While the limit glides up over a platform's edge, the camera still never // sits closer than this to the floor it is over. @@ -23,6 +24,8 @@ const SURFACE_MIN_GAP = 0.05 export type CameraFloorSurface = { /** Changes whenever an earlier answer may no longer hold. */ readonly revision: number + /** The highest the surface stands anywhere (a hill over the level's floor), when it knows. */ + readonly reachY?: number | null topAt(x: number, z: number, levelY: number): number | null } @@ -297,7 +300,8 @@ export class FloorAwareCameraControls extends CameraControlsImpl { */ private resolveFloorLimit(position: Vector3, levelY: number) { const surface = this.floorSurface - if (!surface || position.y > levelY + ORBIT_FLOOR_CLEARANCE + SURFACE_BAND) { + const reachY = Math.max(levelY, surface?.reachY ?? levelY) + if (!surface || position.y > reachY + ORBIT_FLOOR_CLEARANCE + SURFACE_BAND) { this.forgetFloorSurface() return levelY + ORBIT_FLOOR_CLEARANCE } diff --git a/packages/editor/src/components/editor/floor-surface.test.ts b/packages/editor/src/components/editor/floor-surface.test.ts index 48e2e8b404..838a5d83d3 100644 --- a/packages/editor/src/components/editor/floor-surface.test.ts +++ b/packages/editor/src/components/editor/floor-surface.test.ts @@ -101,6 +101,73 @@ test('on the ground level the site ground counts; on other levels it does not', expect(topAt(surface, 3, 3, 2.71)).toBeNull() }) +test("sculpted ground in tiles is the site's ground too, and the surface says how high it stands", () => { + scene([ + node(GROUND, 'level', null, { level: 0 }), + node(UPPER, 'level', null, { level: 1 }), + node('site_a', 'site', null), + node('tile_a', 'terrain-tile', 'site_a'), + node('building_a', 'building', 'site_a'), + ]) + const site = new THREE.Group() + // A tile is a node of its own under the site, as a building is: its mesh is the ground. + const tile = new THREE.Group() + tile.add(slabMesh(3, 0.01)) + const building = new THREE.Group() + building.add(slabMesh(8, 0.3)) + site.add(tile, building) + register('tile_a', 'terrain-tile', tile) + register('building_a', 'building', building) + register('site_a', 'site', site) + + const surface = new FloorSurface() + surface.levelId = GROUND + // The hill, 3 m over the level's floor, and not the building standing on the site. + expect(topAt(surface, 3, 3)).toBeCloseTo(3, 6) + expect(surface.reachY).toBeCloseTo(3, 6) + // Sculpted in place, it stands higher at once. + tile.children[0]!.position.y += 2.5 + tile.updateMatrixWorld(true) + expect(surface.reachY).toBeCloseTo(5.5, 6) + // Another level's floor is not the ground. + surface.levelId = UPPER + expect(topAt(surface, 3, 3, 2.71)).toBeNull() + expect(surface.reachY).toBeNull() +}) + +test('past the property line the sculpted tiles are not the ground: nothing of them is drawn there', () => { + scene([ + node(GROUND, 'level', null, { level: 0 }), + // A lot of 4 x 4 m on tiles that reach 5 m each way, as tiles do past any lot. + node('site_a', 'site', null, { + polygon: { + type: 'polygon', + points: [ + [-2, -2], + [2, -2], + [2, 2], + [-2, 2], + ], + }, + }), + node('tile_a', 'terrain-tile', 'site_a'), + ]) + const site = new THREE.Group() + const tile = new THREE.Group() + tile.add(slabMesh(3, 0.01)) + site.add(tile) + register('tile_a', 'terrain-tile', tile) + register('site_a', 'site', site) + + const surface = new FloorSurface() + surface.levelId = GROUND + expect(topAt(surface, 1, 1)).toBeCloseTo(3, 6) + // Over the tile's own geometry still, but past the line: the hill is not drawn here, and an + // eye out there is not held over it. + expect(topAt(surface, 4, 1)).toBeNull() + expect(topAt(surface, -1, -4.5)).toBeNull() +}) + test('rebuilding a slab in place moves the revision so a cached answer is refreshed', () => { scene([node(GROUND, 'level', null, { level: 0 }), node('slab_base', 'slab', GROUND)]) const slab = slabMesh(0.05) diff --git a/packages/editor/src/components/editor/floor-surface.ts b/packages/editor/src/components/editor/floor-surface.ts index 4c6843780c..3f02be5fc3 100644 --- a/packages/editor/src/components/editor/floor-surface.ts +++ b/packages/editor/src/components/editor/floor-surface.ts @@ -1,6 +1,6 @@ import { type AnyNode, type AnyNodeId, sceneRegistry, useScene } from '@pascal-app/core' import { BATCHED_LAYER, SCENE_LAYER } from '@pascal-app/viewer' -import { type Intersection, type Mesh, type Object3D, Raycaster, Vector3 } from 'three' +import { Box3, type Intersection, type Mesh, type Object3D, Raycaster, Vector3 } from 'three' // Drawn by the scene pass or by a merged batch that stands in for the mesh. const DRAWN_LAYERS_MASK = (1 << SCENE_LAYER) | (1 << BATCHED_LAYER) @@ -8,6 +8,10 @@ const DRAWN_LAYERS_MASK = (1 << SCENE_LAYER) | (1 << BATCHED_LAYER) const CAST_HEIGHT = 50 const down = new Vector3(0, -1, 0) const origin = new Vector3() +const reachBox = new Box3() +const lotPoint = new Vector3() + +type Lot = { site: Object3D; points: ReadonlyArray } function isMesh(object: Object3D): object is Mesh { return (object as Mesh).isMesh === true @@ -21,6 +25,20 @@ function isDrawn(mesh: Mesh) { return true } +/** Whether world (x, z) lies inside the property line, which is laid out in the site's own plan. */ +function insideLot({ site, points }: Lot, x: number, z: number): boolean { + site.worldToLocal(lotPoint.set(x, 0, z)) + let inside = false + for (let a = 0, b = points.length - 1; a < points.length; b = a, a += 1) { + const [ax, az] = points[a]! + const [bx, bz] = points[b]! + if (az > lotPoint.z !== bz > lotPoint.z) { + if (lotPoint.x < ((bx - ax) * (lotPoint.z - az)) / (bz - az) + ax) inside = !inside + } + } + return inside +} + function levelOf(nodes: Record, id: string): AnyNode | null { let node: AnyNode | undefined = nodes[id as AnyNodeId] while (node) { @@ -33,10 +51,12 @@ function levelOf(nodes: Record, id: string): AnyNode | null /** * The walkable surface of the active level: its floor slabs and plates * (raised platforms and sunken floors included) and, on the ground level, the - * site's ground and terrain. Walls, items, ceilings, roofs and other levels - * are not in it. The mesh list is rebuilt only when the scene, the registry - * or the level changes; `revision` moves with it and with any geometry or - * transform change, so callers can cache answers between moves. + * site's ground and terrain, the sculpted tiles among it, inside the property + * line: sculpted ground is drawn to the line only, though its tiles reach past + * it. Walls, items, ceilings, roofs and other levels are not in it. The mesh + * list is rebuilt only when the scene, the registry or the level changes; + * `revision` moves with it and with any geometry or transform change, so + * callers can cache answers between moves. */ export class FloorSurface { /** The level whose floors count. */ @@ -44,6 +64,9 @@ export class FloorSurface { private readonly raycaster = new Raycaster() private readonly hits: Intersection[] = [] private meshes: Mesh[] = [] + // The site's own ground among them, and the property line it is drawn within. + private siteGround = new Set() + private lot: Lot | null = null private objects: { object: Object3D; children: Object3D[] }[] = [] private builtFor: { registry: number; nodes: unknown; levelId: string | null } | null = null private meshStates: { @@ -56,20 +79,44 @@ export class FloorSurface { drawn: boolean }[] = [] private version = 0 + private reach: { version: number; y: number | null } | null = null get revision() { this.refresh() return this.version } + /** + * The highest the surface stands anywhere, world Y, or null with nothing drawn: a hill may + * stand many metres over the level's floor, and a caller that only looks for a floor near the + * level's own would fly into it. + */ + get reachY(): number | null { + this.refresh() + if (this.reach?.version !== this.version) { + let y: number | null = null + for (const mesh of this.meshes) { + const position = mesh.geometry.getAttribute('position') + if (!position || !isDrawn(mesh)) continue + // Read from the vertices, not the geometry's own box: sculpted ground moves in place. + reachBox.setFromBufferAttribute(position as never).applyMatrix4(mesh.matrixWorld) + if (!reachBox.isEmpty() && (y === null || reachBox.max.y > y)) y = reachBox.max.y + } + this.reach = { version: this.version, y } + } + return this.reach.y + } + /** Height of the highest floor surface at `x`/`z`, or null over nothing. */ topAt(x: number, z: number, levelY: number): number | null { origin.set(x, levelY + CAST_HEIGHT, z) this.raycaster.set(origin, down) this.raycaster.far = Number.POSITIVE_INFINITY let top: number | null = null + const pastLot = this.lot !== null && !insideLot(this.lot, x, z) for (const mesh of this.meshes) { if (!isDrawn(mesh)) continue + if (pastLot && this.siteGround.has(mesh)) continue this.hits.length = 0 mesh.raycast(this.raycaster, this.hits) for (const hit of this.hits) if (top === null || hit.point.y > top) top = hit.point.y @@ -154,13 +201,21 @@ export class FloorSurface { private collect(nodes: Record) { const meshes: Mesh[] = [] this.objects = [] + this.siteGround = new Set() + this.lot = null const level = this.levelId ? nodes[this.levelId as AnyNodeId] : undefined if (level?.type !== 'level') return meshes const nodeObjects = new Set(sceneRegistry.nodes.values()) + // Sculpted ground is drawn tile by tile, each a node under the site: the site's ground still. + const groundTiles = new Set() + for (const id of sceneRegistry.byType['terrain-tile'] ?? []) { + const tile = sceneRegistry.nodes.get(id) + if (tile) groundTiles.add(tile) + } const collect = (object: Object3D, root: Object3D) => { // A slab's hosted items and a site's buildings are not its surface. - if (object !== root && nodeObjects.has(object)) return + if (object !== root && nodeObjects.has(object) && !groundTiles.has(object)) return this.objects.push({ object, children: object.children.slice() }) if (isMesh(object)) meshes.push(object) for (const child of object.children) collect(child, root) @@ -174,7 +229,13 @@ export class FloorSurface { if (level.level === 0) { for (const id of sceneRegistry.byType.site ?? []) { const object = sceneRegistry.nodes.get(id) - if (object) collect(object, object) + if (!object) continue + const first = meshes.length + collect(object, object) + for (const mesh of meshes.slice(first)) this.siteGround.add(mesh) + const site = nodes[id as AnyNodeId] + const points = site?.type === 'site' ? site.polygon?.points : undefined + if (points && points.length >= 3) this.lot = { site: object, points } } } return meshes diff --git a/packages/editor/src/lib/level-orbit-floor.test.ts b/packages/editor/src/lib/level-orbit-floor.test.ts new file mode 100644 index 0000000000..33c6693fe3 --- /dev/null +++ b/packages/editor/src/lib/level-orbit-floor.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from 'bun:test' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + EXPLODED_GAP, + LevelNode, +} from '@pascal-app/core' +import { levelOrbitFloorY } from './level-orbit-floor' +import { ORBIT_TARGET_HEIGHT } from './orbit-floor-clearance' + +/** A house of a lower floor, a ground floor and an upper floor, standing `seatY` over the datum. */ +function house(seatY: number) { + const list: AnyNode[] = [ + BuildingNode.parse({ + id: 'building_a', + position: [4, seatY, -2], + children: ['level_lower', 'level_ground', 'level_upper'], + }), + LevelNode.parse({ + id: 'level_lower', + parentId: 'building_a', + level: -1, + height: 2.7, + baseElevation: -2.7, + }), + LevelNode.parse({ id: 'level_ground', parentId: 'building_a', level: 0, height: 2.5 }), + LevelNode.parse({ id: 'level_upper', parentId: 'building_a', level: 1, height: 2.5 }), + ] + return Object.fromEntries(list.map((node) => [node.id, node])) as Record +} + +test('the orbit rests on the floor of a house seated on a slope, not on the datum under it', () => { + // A walk-out seated 1.52 m up its slope: the ground floor is there, the lower floor 2.7 m under. + const seated = house(1.52) + expect(levelOrbitFloorY('level_ground', seated, 'stacked')).toBeCloseTo(1.52, 9) + expect(levelOrbitFloorY('level_lower', seated, 'stacked')).toBeCloseTo(1.52 - 2.7, 9) + expect(levelOrbitFloorY('level_upper', seated, 'stacked')).toBeCloseTo(1.52 + 2.5, 9) + // The pivot is then at standing height in the lower floor's rooms (its plane is at -1.18), not + // 0.42 m under its slab, where the datum's count (-2.7 + 1.1) put it. + const pivot = levelOrbitFloorY('level_lower', seated, 'stacked') + ORBIT_TARGET_HEIGHT + expect(pivot).toBeCloseTo(-0.08, 9) + // A house cut into the ground stands under the datum, and its floors with it. + expect(levelOrbitFloorY('level_ground', house(-2), 'stacked')).toBeCloseTo(-2, 9) +}) + +test('a house at the datum, the exploded view and no level read as before', () => { + const flat = house(0) + expect(levelOrbitFloorY('level_ground', flat, 'stacked')).toBe(0) + expect(levelOrbitFloorY('level_lower', flat, 'stacked')).toBeCloseTo(-2.7, 9) + // Exploded, each level is lifted by its index; the seat is added once. + expect(levelOrbitFloorY('level_upper', house(1.52), 'exploded')).toBeCloseTo( + 1.52 + 2.5 + EXPLODED_GAP, + 9, + ) + expect(levelOrbitFloorY(null, flat, 'stacked')).toBe(0) + expect(levelOrbitFloorY('level_gone', flat, 'stacked')).toBe(0) +}) diff --git a/packages/editor/src/lib/level-orbit-floor.ts b/packages/editor/src/lib/level-orbit-floor.ts new file mode 100644 index 0000000000..52e0a1c7f7 --- /dev/null +++ b/packages/editor/src/lib/level-orbit-floor.ts @@ -0,0 +1,23 @@ +import { type AnyNode, type AnyNodeId, getLevelElevations } from '@pascal-app/core' +import { getLevelPresentationY } from '@pascal-app/viewer' + +type LevelMode = Parameters[2] + +/** + * The world height of a level's floor plane as the editor presents it: where the level sits in + * its building (`getLevelPresentationY`: stacked, or lifted apart when exploded) plus the height + * the building itself stands at on the site. A house seated on a slope does not stand at the + * datum, and the orbit rests on its floor, not on the datum under or over it. Analytic, as + * `getLevelPresentationY` is. 0 for no level. + */ +export function levelOrbitFloorY( + levelId: string | null | undefined, + nodes: Record, + levelMode: LevelMode, +): number { + if (!levelId) return 0 + const buildingId = getLevelElevations(nodes).get(levelId)?.buildingId + const building = buildingId ? nodes[buildingId as AnyNodeId] : undefined + const seatY = building?.type === 'building' ? building.position[1] : 0 + return seatY + getLevelPresentationY(levelId, nodes, levelMode) +} diff --git a/packages/viewer/src/components/viewer/first-person/build-collider-world.test.ts b/packages/viewer/src/components/viewer/first-person/build-collider-world.test.ts index 01c9ba3c34..3e075ce70e 100644 --- a/packages/viewer/src/components/viewer/first-person/build-collider-world.test.ts +++ b/packages/viewer/src/components/viewer/first-person/build-collider-world.test.ts @@ -313,9 +313,14 @@ describe('buildFirstPersonColliderWorldFromRegistry', () => { // The hill is in the collider: a flat slab would top out at 0. expect(world.bounds?.max.y).toBeCloseTo(2.5) - // And it still reaches past the site so stepping out does not drop the player. - expect(world.bounds?.min.x).toBeCloseTo(-1008) - expect(world.bounds?.max.x).toBeCloseTo(1008) + // And it still reaches past the site so stepping out does not drop the player. The ground + // the player stands on is the scene's authority (tiles, the frozen legacy field, a + // continuation), which spans the lot as well as the sculpted field: this site's default + // 30 × 30 m lot reaches ±15 m, past the field's ±8 m, and the skirt starts from there. + expect(world.bounds?.min.x).toBeCloseTo(-1015) + expect(world.bounds?.max.x).toBeCloseTo(1015) + expect(world.bounds?.min.z).toBeCloseTo(-1015) + expect(world.bounds?.max.z).toBeCloseTo(1015) // What the player actually stands on, on the plateau and off it. const raycaster = new Raycaster() diff --git a/packages/viewer/src/components/viewer/underground-ambiance.tsx b/packages/viewer/src/components/viewer/underground-ambiance.tsx index 3a111e3830..b8bc7d159c 100644 --- a/packages/viewer/src/components/viewer/underground-ambiance.tsx +++ b/packages/viewer/src/components/viewer/underground-ambiance.tsx @@ -23,6 +23,7 @@ import { easeAmbiance, eyeUnderTheGround, FADE_SECONDS, + groundUnderEye, restoreSkyLights, setAmbianceFactor, setAmbianceFocus, @@ -48,6 +49,7 @@ export function UndergroundAmbiance() { const eye = useRef(new Vector3()) const lastEye = useRef(new Vector3(Number.NaN, Number.NaN, Number.NaN)) const lastNodes = useRef | null>(null) + const lastPastLot = useRef(null) const groundY = useRef(0) // The box the fog keeps clear: the host's ground window box when it keeps one, else the level // shown (or the building) worked out here, so a host without the window still gets it. @@ -62,12 +64,25 @@ export function UndergroundAmbiance() { state.camera.getWorldPosition(eye.current) const { nodes } = useScene.getState() - if (!eye.current.equals(lastEye.current) || nodes !== lastNodes.current) { + const pastLot = viewer.groundPastLot + if ( + !eye.current.equals(lastEye.current) || + nodes !== lastNodes.current || + pastLot !== lastPastLot.current + ) { lastEye.current.copy(eye.current) lastNodes.current = nodes - const siteId = sceneRegistry.byType.site?.values().next().value as AnyNodeId | undefined - const site = siteId ? nodes[siteId] : null - groundY.current = groundHeightAt(site, eye.current.x, eye.current.z) + lastPastLot.current = pastLot + const { x, z } = eye.current + groundY.current = groundUnderEye( + x, + z, + () => { + const siteId = sceneRegistry.byType.site?.values().next().value as AnyNodeId | undefined + return groundHeightAt(siteId ? nodes[siteId] : null, nodes, x, z) + }, + pastLot, + ) } const under = eyeUnderTheGround(viewer.eyeUnderGround, eye.current.y, groundY.current) if (under !== viewer.eyeUnderGround) useViewer.setState({ eyeUnderGround: under }) diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index ff35c9f087..bf45739e68 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -367,12 +367,14 @@ export { DEFAULT_UNDERGROUND_LOOK, default as useViewer, type GroundMode, + type GroundPastLot, groundVeiled, type MetricNotation, type RenderQuality, type RenderQualityChoice, siteGroundShown, type UndergroundEdge, + type UndergroundGround, type UndergroundLook, type UndergroundTransition, type WalkthroughMovement, diff --git a/packages/viewer/src/lib/underground-ambiance.test.ts b/packages/viewer/src/lib/underground-ambiance.test.ts index bd68d6d37b..3c55adf1bb 100644 --- a/packages/viewer/src/lib/underground-ambiance.test.ts +++ b/packages/viewer/src/lib/underground-ambiance.test.ts @@ -14,6 +14,7 @@ import { eyeUnderTheGround, groundHoleOpenNode, groundHoleOpenNow, + groundUnderEye, registerSkyLights, restoreSkyLights, SKY_LIGHT_SCALE, @@ -51,6 +52,43 @@ test('the dark mode is wanted only while the eye is under the ground, never on S expect(ambianceTarget({ ...under, walkthroughMode: false })).toBe(1) }) +test('past the property line of a sculpted lot the eye is measured against the ground drawn there', () => { + // A hillside lot of 30 x 30 m: its hill stands 3 m high along the west line and the height + // field carries it on past the line, where nothing of it is drawn: the lot is a block of earth + // on the horizon disc, here 4.09 m under the datum. + const lot = [ + [-15, -15], + [15, -15], + [15, 15], + [-15, 15], + ] as const + const hill = (x: number) => () => (x < -8 ? 3 : 0.05) + const pastLot = { y: -4.09, lot } + // Inside the line the site's own ground is the ground, under the hill as on the pad. + expect(groundUnderEye(-14, 0, hill(-14), pastLot)).toBe(3) + expect(groundUnderEye(0, 12, hill(0), pastLot)).toBe(0.05) + // Past it, in the open beside the block: the disc, on the hill's side as on any other. A low + // orbit round the lot, 1.6 m up, is over the ground the whole way round, not under it for the + // third of the turn it spends west of the lot. + expect(groundUnderEye(-24, 0, hill(-24), pastLot)).toBe(-4.09) + expect(groundUnderEye(0, 24, hill(0), pastLot)).toBe(-4.09) + expect(eyeUnderTheGround(false, 1.6, groundUnderEye(-24, 0, hill(-24), pastLot))).toBe(false) + expect(eyeUnderTheGround(false, 1.6, groundUnderEye(-14, 0, hill(-14), pastLot))).toBe(true) + // The site's ground is not asked out there. + expect( + groundUnderEye( + 40, + 40, + () => { + throw new Error('asked') + }, + pastLot, + ), + ).toBe(-4.09) + // A flat site, or a site that draws no ground of its own, has one ground everywhere. + expect(groundUnderEye(-24, 0, hill(-24), null)).toBe(3) +}) + test('the eye goes under the ground past a small band and comes back past it, no chatter', () => { const ground = -0.05 expect(eyeUnderTheGround(false, ground - EYE_BAND / 2, ground)).toBe(false) diff --git a/packages/viewer/src/lib/underground-ambiance.ts b/packages/viewer/src/lib/underground-ambiance.ts index 052a3ade69..babd0dbd8b 100644 --- a/packages/viewer/src/lib/underground-ambiance.ts +++ b/packages/viewer/src/lib/underground-ambiance.ts @@ -16,7 +16,7 @@ import { vec3, vec4, } from 'three/tsl' -import type { GroundMode } from '../store/use-viewer' +import type { GroundMode, GroundPastLot } from '../store/use-viewer' import { backdropGradient } from './backdrop' import { UNDERGROUND_PALETTE } from './scene-themes' @@ -114,6 +114,32 @@ export function eyeUnderTheGround(previous: boolean, eyeY: number, groundY: numb return previous ? eyeY < groundY + EYE_BAND : eyeY < groundY - EYE_BAND } +/** + * The height of the ground the eye is measured against at a world XZ: the ground that is drawn + * there. Inside the property line that is the site's own (`siteGround`, asked only then); past + * the line of a sculpted site (`pastLot`) no sculpted ground is drawn, whatever the height field + * says of the hill beyond, and the ground is the horizon disc under the lot's block. + */ +export function groundUnderEye( + x: number, + z: number, + siteGround: () => number, + pastLot: GroundPastLot | null, +): number { + if (pastLot && !insideLot(pastLot.lot, x, z)) return pastLot.y + return siteGround() +} + +function insideLot(lot: GroundPastLot['lot'], x: number, z: number): boolean { + let inside = false + for (let a = 0, b = lot.length - 1; a < lot.length; b = a, a += 1) { + const [ax, az] = lot[a]! + const [bx, bz] = lot[b]! + if (az > z !== bz > z && x < ((bx - ax) * (z - az)) / (bz - az) + ax) inside = !inside + } + return inside +} + /** * One step of the crossing: `progress` moves toward `target` (0 or 1) in a straight line over * `seconds`, and is exactly the target once it has arrived. `seconds <= 0` is instant. diff --git a/packages/viewer/src/store/use-viewer.ts b/packages/viewer/src/store/use-viewer.ts index d750dc0f51..90e6d7d7b7 100644 --- a/packages/viewer/src/store/use-viewer.ts +++ b/packages/viewer/src/store/use-viewer.ts @@ -202,6 +202,14 @@ type ViewerState = { * viewer's underground ambiance from the camera; never persisted. */ eyeUnderGround: boolean + /** + * Where the ground is drawn past the property line. A sculpted site draws its ground to the + * line only, as a block of earth, and past it the horizon disc under the block's base, however + * the height field continues out there: an eye past the line is under the ground only under + * that disc. Set by the site renderer; `null` where the ground is one surface (a flat site) or + * the site draws none. Never persisted. + */ + groundPastLot: GroundPastLot | null /** * The world is turned, or turning, to earth (the underground ambiance's factor is above 0). * Its factor itself eases every frame and lives with the shaders, not here; this flips only at @@ -582,6 +590,7 @@ function persistedSolid(state: Record): boolean { export const DEFAULT_UNDERGROUND_LOOK: UndergroundLook = { edge: 'section-earth', transition: 'fade', + ground: 'drawn', } function resolveLook(state: ViewerState, patch: Partial): Partial { @@ -764,6 +773,7 @@ const useViewer = create()( hasLevelBelowGrade: false, diveAvailable: false, eyeUnderGround: false, + groundPastLot: null, ambianceActive: false, undergroundLook: DEFAULT_UNDERGROUND_LOOK, setUndergroundLook: (look) => @@ -1017,7 +1027,24 @@ export type UndergroundEdge = 'noise' | 'quiet' | 'section' | 'section-earth' /** The dive under the ground: `noise` closes a noise mask over the screen, `fade` fades the whole frame at once. */ export type UndergroundTransition = 'noise' | 'fade' -export type UndergroundLook = { edge: UndergroundEdge; transition: UndergroundTransition } +/** + * What an eye under the ground sees of the ground itself. `drawn`: whatever the site draws. A flat + * lot's ground is seen from above only, so nothing; a sculpted lot is a block of earth (its + * surface, the skirt along the property line, the horizon disc under its base), and an eye inside + * it sees the disc as a sunlit floor, the ground it is level with, and the veil. `implied`: under + * the ground no ground is drawn on any lot, so the inside of a hill looks as the underside of a + * flat lot does. Above the ground the two are the same. + */ +export type UndergroundGround = 'drawn' | 'implied' + +export type UndergroundLook = { + edge: UndergroundEdge + transition: UndergroundTransition + ground: UndergroundGround +} + +/** The ground past a sculpted lot's property line: its height, world Y, and the line, in plan. */ +export type GroundPastLot = { y: number; lot: ReadonlyArray } /** * Whether the site's ground is drawn as a veil wholesale: a level below grade is shown, the diff --git a/packages/viewer/src/systems/wall/wall-terrain-bottom.test.ts b/packages/viewer/src/systems/wall/wall-terrain-bottom.test.ts index ee510e52df..e8c1c1cc24 100644 --- a/packages/viewer/src/systems/wall/wall-terrain-bottom.test.ts +++ b/packages/viewer/src/systems/wall/wall-terrain-bottom.test.ts @@ -1,10 +1,63 @@ // @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not // depend on @types/bun so the import type is unresolved at compile time. import { describe, expect, test } from 'bun:test' -import { calculateLevelMiters, WallNode } from '@pascal-app/core' +import { + calculateLevelMiters, + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + SiteNode, + TerrainTileNode, + WallNode, +} from '@pascal-app/core' import { generateExtrudedWall } from './wall-system' describe('wall terrain bottom', () => { + test('a wall spanning a tile edge uses the overlay instead of the frozen legacy base', () => { + const base = createTerrainField({ cols: 129, rows: 65, spacing: 0.5 }) + base.heights.fill(-100) + const site = SiteNode.parse({ id: 'site_wall', terrain: encodeTerrainField(base) }) + const tiles = [0, 1].map((ix) => { + const field = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + field.heights.fill(50) + return TerrainTileNode.parse({ + id: `terrain-tile_wall_${ix}`, + parentId: site.id, + level: 0, + ix, + iz: 0, + step: 0.01, + heights: encodeTerrainField(field).heights, + }) + }) + const nodes = { [site.id]: site, ...Object.fromEntries(tiles.map((tile) => [tile.id, tile])) } + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error('Missing tiled ground') + const wall = WallNode.parse({ + start: [30, 16], + end: [34, 16], + height: 2.5, + thickness: 1, + supportSlabId: 'ground', + fillToTerrain: true, + }) + const geometry = generateExtrudedWall( + wall, + [], + calculateLevelMiters([wall]), + 1.5, + 1.5, + undefined, + 4, + (x, z) => heightAt(field, x, z), + ) + geometry.computeBoundingBox() + expect(geometry.boundingBox?.min.y).toBeCloseTo(-1, 6) + expect(geometry.boundingBox?.max.y).toBeCloseTo(2.5, 6) + geometry.dispose() + }) + test('samples both faces independently without changing the authored body height', () => { const wall = WallNode.parse({ start: [0, 0], From 3b95a39f8eb23683162cd9ffc5e873979d615c1a Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 16 Nov 2026 21:07:03 +0100 Subject: [PATCH 04/11] nodes: draw the tiled ground, terrain breaks and ramps, with the smooth break ground behind a switch The site renderer draws one composite ground when a site has tiles, breaks or a live stroke: patches cut to the lot, a skirt along the property line, the horizon disc past it, holes for ramps and recessed slabs, and the faces of each terrain break (cliff in stone, retaining wall, soil). A tile wholly outside the property line is kept and not drawn. A stroke reads and uploads only the skirt points and meshes it can reach. Renderers and definitions for the three kinds: terrain-tile (no tool of its own), terrain-break (draw tool, 2D tool, panel), ramp (draw tool, 2D tool, panel, site-plan outline). A draped slab is built on the ground under it. Switch: the ground beside a terrain break is faceted by default (as in the lab); setTerrainBreakGround('smooth') or NEXT_PUBLIC_PASCAL_TERRAIN_BREAK_GROUND=smooth shades it smooth. A switch for the implied earth under the ground follows the viewer's undergroundLook.ground, off by default. Differs from the lab: the 2D tools of ramp and terrain break draw in the floor-plan frame only (the lab reads a drawingType main's FloorplanToolContext does not have). Co-Authored-By: Claude Opus 5.5 --- packages/nodes/src/builtin-definitions.ts | 6 + .../nodes/src/builtin-edit-contributions.ts | 6 + packages/nodes/src/index.test.ts | 4 +- packages/nodes/src/index.ts | 26 + packages/nodes/src/ramp/centreline.ts | 71 ++ packages/nodes/src/ramp/definition.edit.ts | 32 + packages/nodes/src/ramp/definition.render.ts | 54 ++ packages/nodes/src/ramp/definition.ts | 5 + packages/nodes/src/ramp/draft.tsx | 279 ++++++++ packages/nodes/src/ramp/edit.ts | 74 ++ packages/nodes/src/ramp/floorplan-tool.tsx | 134 ++++ packages/nodes/src/ramp/floorplan.ts | 96 +++ packages/nodes/src/ramp/geometry.ts | 241 +++++++ packages/nodes/src/ramp/index.ts | 11 + packages/nodes/src/ramp/number-field.tsx | 62 ++ packages/nodes/src/ramp/panel.tsx | 413 +++++++++++ packages/nodes/src/ramp/ramp-geometry.test.ts | 231 ++++++ packages/nodes/src/ramp/ramp-plan.test.ts | 190 +++++ packages/nodes/src/ramp/snapping.ts | 40 ++ packages/nodes/src/ramp/tool.tsx | 114 +++ packages/nodes/src/rock/material.ts | 67 ++ .../terrain-break-ground-golden.json | 192 +++++ .../terrain-break-ground-scenes.ts | 151 ++++ .../__fixtures__/terrain-lag-mesh-golden.json | 1 + packages/nodes/src/site/ground-hole.test.tsx | 32 +- packages/nodes/src/site/ground-hole.tsx | 23 + packages/nodes/src/site/ground-pit.test.tsx | 69 ++ packages/nodes/src/site/ground-pit.tsx | 17 +- packages/nodes/src/site/ground-veil.test.tsx | 72 ++ packages/nodes/src/site/ground-veil.tsx | 27 +- packages/nodes/src/site/lot-mask.test.ts | 41 ++ packages/nodes/src/site/lot-mask.ts | 4 + packages/nodes/src/site/ramp-cut-faces.ts | 168 +++++ packages/nodes/src/site/ramp-ground-holes.ts | 84 +++ packages/nodes/src/site/renderer.tsx | 258 +++++-- .../src/site/terrain-break-ground.test.ts | 425 ++++++++++++ .../nodes/src/site/terrain-break-split.ts | 656 ++++++++++++++++++ .../nodes/src/site/terrain-breaks.test.ts | 304 ++++++++ .../nodes/src/site/terrain-geometry.test.ts | 56 ++ packages/nodes/src/site/terrain-geometry.ts | 69 +- .../src/site/terrain-ground-renderer.tsx | 116 ++++ .../nodes/src/site/terrain-ground-surface.tsx | 156 +++++ packages/nodes/src/site/terrain-ground.ts | 224 ++++++ packages/nodes/src/site/terrain-holes.ts | 75 +- .../nodes/src/site/terrain-lag-mesh.test.ts | 57 ++ packages/nodes/src/site/terrain-renderer.tsx | 88 +-- .../nodes/src/site/terrain-reveal.test.ts | 100 +++ packages/nodes/src/site/terrain-tiles.test.ts | 162 +++++ .../src/slab/__tests__/terrain-draped.test.ts | 120 ++++ packages/nodes/src/slab/definition.edit.ts | 2 +- packages/nodes/src/slab/definition.render.ts | 9 +- packages/nodes/src/slab/dependency-tracker.ts | 32 +- .../nodes/src/slab/draped-foundation.test.ts | 112 +++ packages/nodes/src/slab/geometry.ts | 34 + packages/nodes/src/slab/terrain-draped.ts | 130 ++++ .../terrain-lag-break-golden.json | 1 + .../src/terrain-break/definition.edit.ts | 18 + .../src/terrain-break/definition.render.ts | 58 ++ .../nodes/src/terrain-break/definition.ts | 8 + packages/nodes/src/terrain-break/draft.tsx | 147 ++++ packages/nodes/src/terrain-break/edit.test.ts | 170 +++++ packages/nodes/src/terrain-break/edit.ts | 67 ++ .../src/terrain-break/floorplan-tool.tsx | 71 ++ packages/nodes/src/terrain-break/floorplan.ts | 17 + packages/nodes/src/terrain-break/geometry.ts | 393 +++++++++++ packages/nodes/src/terrain-break/material.ts | 16 + packages/nodes/src/terrain-break/options.tsx | 57 ++ packages/nodes/src/terrain-break/panel.tsx | 87 +++ packages/nodes/src/terrain-break/renderer.tsx | 138 ++++ .../terrain-lag-break-mesh.test.ts | 72 ++ packages/nodes/src/terrain-break/tool.tsx | 65 ++ .../nodes/src/terrain-tile/definition.edit.ts | 4 + .../src/terrain-tile/definition.render.ts | 42 ++ packages/nodes/src/terrain-tile/definition.ts | 8 + packages/nodes/src/terrain-tile/geometry.ts | 15 + packages/nodes/src/terrain-tile/index.ts | 2 + .../src/terrain-tile/mesh-inputs.test.ts | 159 +++++ .../nodes/src/terrain-tile/mesh-inputs.ts | 73 ++ packages/nodes/src/terrain-tile/renderer.tsx | 42 ++ 79 files changed, 7795 insertions(+), 157 deletions(-) create mode 100644 packages/nodes/src/ramp/centreline.ts create mode 100644 packages/nodes/src/ramp/definition.edit.ts create mode 100644 packages/nodes/src/ramp/definition.render.ts create mode 100644 packages/nodes/src/ramp/definition.ts create mode 100644 packages/nodes/src/ramp/draft.tsx create mode 100644 packages/nodes/src/ramp/edit.ts create mode 100644 packages/nodes/src/ramp/floorplan-tool.tsx create mode 100644 packages/nodes/src/ramp/floorplan.ts create mode 100644 packages/nodes/src/ramp/geometry.ts create mode 100644 packages/nodes/src/ramp/index.ts create mode 100644 packages/nodes/src/ramp/number-field.tsx create mode 100644 packages/nodes/src/ramp/panel.tsx create mode 100644 packages/nodes/src/ramp/ramp-geometry.test.ts create mode 100644 packages/nodes/src/ramp/ramp-plan.test.ts create mode 100644 packages/nodes/src/ramp/snapping.ts create mode 100644 packages/nodes/src/ramp/tool.tsx create mode 100644 packages/nodes/src/rock/material.ts create mode 100644 packages/nodes/src/site/__fixtures__/terrain-break-ground-golden.json create mode 100644 packages/nodes/src/site/__fixtures__/terrain-break-ground-scenes.ts create mode 100644 packages/nodes/src/site/__fixtures__/terrain-lag-mesh-golden.json create mode 100644 packages/nodes/src/site/ground-pit.test.tsx create mode 100644 packages/nodes/src/site/lot-mask.test.ts create mode 100644 packages/nodes/src/site/ramp-cut-faces.ts create mode 100644 packages/nodes/src/site/ramp-ground-holes.ts create mode 100644 packages/nodes/src/site/terrain-break-ground.test.ts create mode 100644 packages/nodes/src/site/terrain-break-split.ts create mode 100644 packages/nodes/src/site/terrain-breaks.test.ts create mode 100644 packages/nodes/src/site/terrain-ground-renderer.tsx create mode 100644 packages/nodes/src/site/terrain-ground-surface.tsx create mode 100644 packages/nodes/src/site/terrain-ground.ts create mode 100644 packages/nodes/src/site/terrain-lag-mesh.test.ts create mode 100644 packages/nodes/src/site/terrain-reveal.test.ts create mode 100644 packages/nodes/src/site/terrain-tiles.test.ts create mode 100644 packages/nodes/src/slab/__tests__/terrain-draped.test.ts create mode 100644 packages/nodes/src/slab/draped-foundation.test.ts create mode 100644 packages/nodes/src/slab/terrain-draped.ts create mode 100644 packages/nodes/src/terrain-break/__fixtures__/terrain-lag-break-golden.json create mode 100644 packages/nodes/src/terrain-break/definition.edit.ts create mode 100644 packages/nodes/src/terrain-break/definition.render.ts create mode 100644 packages/nodes/src/terrain-break/definition.ts create mode 100644 packages/nodes/src/terrain-break/draft.tsx create mode 100644 packages/nodes/src/terrain-break/edit.test.ts create mode 100644 packages/nodes/src/terrain-break/edit.ts create mode 100644 packages/nodes/src/terrain-break/floorplan-tool.tsx create mode 100644 packages/nodes/src/terrain-break/floorplan.ts create mode 100644 packages/nodes/src/terrain-break/geometry.ts create mode 100644 packages/nodes/src/terrain-break/material.ts create mode 100644 packages/nodes/src/terrain-break/options.tsx create mode 100644 packages/nodes/src/terrain-break/panel.tsx create mode 100644 packages/nodes/src/terrain-break/renderer.tsx create mode 100644 packages/nodes/src/terrain-break/terrain-lag-break-mesh.test.ts create mode 100644 packages/nodes/src/terrain-break/tool.tsx create mode 100644 packages/nodes/src/terrain-tile/definition.edit.ts create mode 100644 packages/nodes/src/terrain-tile/definition.render.ts create mode 100644 packages/nodes/src/terrain-tile/definition.ts create mode 100644 packages/nodes/src/terrain-tile/geometry.ts create mode 100644 packages/nodes/src/terrain-tile/index.ts create mode 100644 packages/nodes/src/terrain-tile/mesh-inputs.test.ts create mode 100644 packages/nodes/src/terrain-tile/mesh-inputs.ts create mode 100644 packages/nodes/src/terrain-tile/renderer.tsx diff --git a/packages/nodes/src/builtin-definitions.ts b/packages/nodes/src/builtin-definitions.ts index d2a2ad60b9..b6cad1761d 100644 --- a/packages/nodes/src/builtin-definitions.ts +++ b/packages/nodes/src/builtin-definitions.ts @@ -38,6 +38,7 @@ import { pipeFittingRenderDefinition } from './pipe-fitting/definition.render' import { pipeSegmentRenderDefinition } from './pipe-segment/definition.render' import { pipeTrapRenderDefinition } from './pipe-trap/definition.render' import { proceduralItemRenderDefinition } from './procedural-item/definition.render' +import { rampRenderDefinition } from './ramp/definition.render' import { ridgeVentRenderDefinition } from './ridge-vent/definition.render' import { roofRenderDefinition } from './roof/definition.render' import { roofSegmentRenderDefinition } from './roof-segment/definition.render' @@ -52,6 +53,8 @@ import { spawnRenderDefinition } from './spawn/definition.render' import { stairRenderDefinition } from './stair/definition.render' import { stairSegmentRenderDefinition } from './stair-segment/definition.render' import { structuralGridRenderDefinition } from './structural-grid/definition.render' +import { terrainBreakRenderDefinition } from './terrain-break/definition.render' +import { terrainTileRenderDefinition } from './terrain-tile/definition.render' import { turbineVentRenderDefinition } from './turbine-vent/definition.render' import { unitRenderDefinition } from './unit/definition.render' import { wallRenderDefinition } from './wall/definition.render' @@ -115,6 +118,9 @@ export const builtinRenderDefinitions = [ pipeSegmentRenderDefinition, pipeFittingRenderDefinition, pipeTrapRenderDefinition, + rampRenderDefinition, + terrainTileRenderDefinition, + terrainBreakRenderDefinition, ] as const export type BuiltinKind = (typeof builtinRenderDefinitions)[number]['kind'] diff --git a/packages/nodes/src/builtin-edit-contributions.ts b/packages/nodes/src/builtin-edit-contributions.ts index 8a25e72d35..e5e329ed98 100644 --- a/packages/nodes/src/builtin-edit-contributions.ts +++ b/packages/nodes/src/builtin-edit-contributions.ts @@ -37,6 +37,7 @@ import { pipeFittingEditContribution } from './pipe-fitting/definition.edit' import { pipeSegmentEditContribution } from './pipe-segment/definition.edit' import { pipeTrapEditContribution } from './pipe-trap/definition.edit' import { proceduralItemEditContribution } from './procedural-item/definition.edit' +import { rampEditContribution } from './ramp/definition.edit' import { ridgeVentEditContribution } from './ridge-vent/definition.edit' import { roofEditContribution } from './roof/definition.edit' import { roofSegmentEditContribution } from './roof-segment/definition.edit' @@ -51,6 +52,8 @@ import { spawnEditContribution } from './spawn/definition.edit' import { stairEditContribution } from './stair/definition.edit' import { stairSegmentEditContribution } from './stair-segment/definition.edit' import { structuralGridEditContribution } from './structural-grid/definition.edit' +import { terrainBreakEditContribution } from './terrain-break/definition.edit' +import { terrainTileEditContribution } from './terrain-tile/definition.edit' import { turbineVentEditContribution } from './turbine-vent/definition.edit' import { unitEditContribution } from './unit/definition.edit' import { wallEditContribution } from './wall/definition.edit' @@ -114,4 +117,7 @@ export const builtinEditContributions = { 'pipe-segment': pipeSegmentEditContribution, 'pipe-fitting': pipeFittingEditContribution, 'pipe-trap': pipeTrapEditContribution, + ramp: rampEditContribution, + 'terrain-tile': terrainTileEditContribution, + 'terrain-break': terrainBreakEditContribution, } satisfies BuiltinEditContributions diff --git a/packages/nodes/src/index.test.ts b/packages/nodes/src/index.test.ts index 698759b4d7..e497fabcce 100644 --- a/packages/nodes/src/index.test.ts +++ b/packages/nodes/src/index.test.ts @@ -66,8 +66,8 @@ describe('builtinPlugin', () => { expect(plugin.apiVersion).toBe(1) await loadPlugin(plugin) const kinds = plugin.nodes!.map((definition) => definition.kind) - expect(kinds).toHaveLength(56) - expect(new Set(kinds).size).toBe(56) + expect(kinds).toHaveLength(59) + expect(new Set(kinds).size).toBe(59) expect([...nodeRegistry.entries()].map(([kind]) => kind).sort()).toEqual( AnyNode.options.map(nodeKindOf).sort(), ) diff --git a/packages/nodes/src/index.ts b/packages/nodes/src/index.ts index 0e497cdcf6..5a755517a0 100644 --- a/packages/nodes/src/index.ts +++ b/packages/nodes/src/index.ts @@ -97,6 +97,21 @@ export { measurementDefinition } from './measurement' export { pipeFittingDefinition } from './pipe-fitting' export { pipeSegmentDefinition } from './pipe-segment' export { pipeTrapDefinition } from './pipe-trap' +export { + buildRampFloorplan, + buildRampGeometry, + buildRampRibbonGeometry, + commitRampCreation, + commitRampEdit, + moveRampPoint, + rampDefinition, + rampFloorplanFrame, + rampPlanToSite, + rampSegmentEnd, + rampSegmentFrames, + rampSegmentThrough, + rampSiteToPlan, +} from './ramp' export { ridgeVentDefinition } from './ridge-vent' export { type RoofFootprintSourceChoice, roofDefinition, useRoofFootprintSource } from './roof' export { glazedRoofGeometryAdapter } from './roof/glazed-geometry' @@ -109,6 +124,12 @@ export { separatorDefinition } from './separator/definition' export { default as PipeCollarInspector } from './shared/pipe-collar-inspector' export { shelfDefinition } from './shelf' export { siteDefinition } from './site' +export { + getTerrainBreakGround, + setTerrainBreakGround, + type TerrainBreakGround, +} from './site/terrain-break-split' +export { buildTerrainGroundMesh, terrainGroundPatches } from './site/terrain-ground' export { skylightDefinition } from './skylight' export { slabDefinition } from './slab' export { solarPanelDefinition } from './solar-panel' @@ -124,6 +145,11 @@ export { buildFloorplanStairEntry } from './stair/plan-entry' export { buildPostAndRailGuard } from './stair/post-and-rail-guard' export { stairSegmentDefinition } from './stair-segment' export { structuralGridDefinition } from './structural-grid' +export { terrainBreakDefinition } from './terrain-break/definition' +export { commitTerrainBreakCreation, commitTerrainBreakEdit } from './terrain-break/edit' +export { buildTerrainBreakFloorplan } from './terrain-break/floorplan' +export { buildTerrainBreakGeometry, buildTerrainBreakMesh } from './terrain-break/geometry' +export { buildTerrainTileMesh, terrainTileDefinition } from './terrain-tile' export { turbineVentDefinition } from './turbine-vent' export { unitDefinition } from './unit' export { wallDefinition } from './wall' diff --git a/packages/nodes/src/ramp/centreline.ts b/packages/nodes/src/ramp/centreline.ts new file mode 100644 index 0000000000..5b5e3e61af --- /dev/null +++ b/packages/nodes/src/ramp/centreline.ts @@ -0,0 +1,71 @@ +import type { RampNode, RampSegment } from '@pascal-app/core' + +export type PlanPoint = [number, number] + +export function rampSegmentEnd(start: PlanPoint, segment: RampSegment): PlanPoint { + if (segment.type === 'line') return [...segment.end] + const angle = + Math.atan2(start[1] - segment.center[1], start[0] - segment.center[0]) + segment.sweep + const radius = Math.hypot(start[0] - segment.center[0], start[1] - segment.center[1]) + return [ + segment.center[0] + Math.cos(angle) * radius, + segment.center[1] + Math.sin(angle) * radius, + ] +} + +export function rampSegmentFrames(node: Pick) { + let start = node.start + return node.segments.map((segment) => { + const end = rampSegmentEnd(start, segment) + const midpoint: PlanPoint = + segment.type === 'line' + ? [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2] + : rampSegmentEnd(start, { ...segment, sweep: segment.sweep / 2 }) + const frame = { start, end, midpoint, segment } + start = end + return frame + }) +} + +/** The circle through an endpoint pair and a picked bend. Near-straight bends become lines. */ +export function rampSegmentThrough(start: PlanPoint, end: PlanPoint, bend: PlanPoint): RampSegment { + const dx = end[0] - start[0] + const dz = end[1] - start[1] + const length = Math.hypot(dx, dz) + if (length < 1e-6) throw new Error('Choose distinct ramp endpoints.') + const sagitta = ((bend[0] - start[0]) * -dz + (bend[1] - start[1]) * dx) / length + if (Math.abs(sagitta) < 0.001) return { type: 'line', end } + // Project the bend onto the perpendicular bisector so dragging feels like a curvature grip. + const offset = sagitta / 2 - (length * length) / (8 * sagitta) + const center: PlanPoint = [ + (start[0] + end[0]) / 2 - (dz / length) * offset, + (start[1] + end[1]) / 2 + (dx / length) * offset, + ] + const sweep = -Math.sign(sagitta) * 4 * Math.atan2(2 * Math.abs(sagitta), length) + return { type: 'arc', center, sweep } +} + +/** Preserve all other endpoints while dragging a joint, including an adjacent arc's bend. */ +export function moveRampPoint(node: RampNode, index: number, point: PlanPoint): Partial { + const frames = rampSegmentFrames(node) + const segments = [...node.segments] + if (!Number.isInteger(index) || index < 0 || index > segments.length) + throw new Error('Choose a ramp endpoint.') + if (index > 0) { + const before = frames[index - 1] + if (!before) throw new Error('The ramp segment no longer exists.') + segments[index - 1] = + before.segment.type === 'line' + ? { type: 'line', end: point } + : rampSegmentThrough(before.start, point, before.midpoint) + } + if (index < segments.length) { + const after = frames[index] + if (!after) throw new Error('The ramp segment no longer exists.') + segments[index] = + after.segment.type === 'line' + ? { type: 'line', end: after.end } + : rampSegmentThrough(point, after.end, after.midpoint) + } + return { ...(index === 0 ? { start: point } : {}), segments } +} diff --git a/packages/nodes/src/ramp/definition.edit.ts b/packages/nodes/src/ramp/definition.edit.ts new file mode 100644 index 0000000000..48c39b94e7 --- /dev/null +++ b/packages/nodes/src/ramp/definition.edit.ts @@ -0,0 +1,32 @@ +import type { RampNode } from '@pascal-app/core' +import type { FloorplanNodeExtension } from '@pascal-app/editor' +import type { NodeEditContribution } from '../definition-contributions' +import { + createSlotPaintCapability, + previewGeometrySlot, + resolveSlotByReRaycast, +} from '../shared/slot-paint' + +export const rampEditContribution: NodeEditContribution = { + snapProfile: 'structural', + capabilities: { + paint: createSlotPaintCapability({ + resolveRole: resolveSlotByReRaycast, + applyPreview: previewGeometrySlot, + }), + }, + tool: () => import('./tool'), + extensions: { + 'pascal:editor/floorplan': { + tool: () => import('./floorplan-tool'), + } satisfies FloorplanNodeExtension, + }, + parametrics: { groups: [], customPanel: () => import('./panel') }, + toolHints: [ + { key: 'Left click', label: 'Add centreline point' }, + { key: 'Enter', label: 'Create ramp' }, + { key: 'Backspace', label: 'Remove last segment' }, + { key: 'Alt', label: 'Free placement' }, + { key: 'Esc', label: 'Cancel' }, + ], +} diff --git a/packages/nodes/src/ramp/definition.render.ts b/packages/nodes/src/ramp/definition.render.ts new file mode 100644 index 0000000000..d22f4c0126 --- /dev/null +++ b/packages/nodes/src/ramp/definition.render.ts @@ -0,0 +1,54 @@ +import { RampNode } from '@pascal-app/core' +import type { NodeRenderDefinition } from '../definition-contributions' +import { buildRampFloorplan } from './floorplan' +import { buildRampGeometry } from './geometry' + +export const rampRenderDefinition: NodeRenderDefinition & { kind: 'ramp' } = { + kind: 'ramp', + schemaVersion: 1, + schema: RampNode, + category: 'site', + surfaceRole: 'floor', + defaults: () => { + const { + id: _id, + type: _type, + ...defaults + } = RampNode.parse({ + id: 'ramp_default', + start: [0, 0], + segments: [{ type: 'line', end: [10, 0] }], + endHeight: -1.5, + }) + return defaults + }, + capabilities: { + drawTool: true, + selectable: { hitVolume: 'mesh' }, + deletable: true, // Copies would share an excavated corridor. Author another centreline instead. + duplicable: false, + presettable: false, + hostable: { parents: ['site'] }, + surfaces: { hosting: false }, + slots: () => [ + { slotId: 'surface', label: 'Surface', default: '#aaa69c' }, + { slotId: 'edge', label: 'Solid edges', default: '#88857e' }, + { slotId: 'retaining', label: 'Retaining sides', default: '#88857e' }, + ], + }, + geometry: buildRampGeometry, + geometryChildTypes: [], + floorplan: buildRampFloorplan, + floorplanScope: 'site', + presentation: { + label: 'Ramp', + description: 'A line-and-arc ramp with explicit endpoint heights and terrain cut and fill.', + icon: { kind: 'iconify', name: 'lucide:waypoints' }, + paletteSection: 'structure', + paletteOrder: 76, + }, + mcp: { + description: + 'Site-owned centreline ramp with an exact endpoint-height profile, transitions and optional retaining sides.', + }, +} diff --git a/packages/nodes/src/ramp/definition.ts b/packages/nodes/src/ramp/definition.ts new file mode 100644 index 0000000000..4dd57b3a16 --- /dev/null +++ b/packages/nodes/src/ramp/definition.ts @@ -0,0 +1,5 @@ +import { composeNodeDefinition } from '../definition-contributions' +import { rampEditContribution } from './definition.edit' +import { rampRenderDefinition } from './definition.render' + +export const rampDefinition = composeNodeDefinition(rampRenderDefinition, rampEditContribution) diff --git a/packages/nodes/src/ramp/draft.tsx b/packages/nodes/src/ramp/draft.tsx new file mode 100644 index 0000000000..edf02b9d0a --- /dev/null +++ b/packages/nodes/src/ramp/draft.tsx @@ -0,0 +1,279 @@ +'use client' + +import { + type AnyNodeId, + RampNode, + rampDefaultTransitionLength, + rampStations, + type SceneApi, +} from '@pascal-app/core' +import { + isTypingTarget, + markToolCancelConsumed, + useEditor, + useInteractionScope, + visibleScene, +} from '@pascal-app/editor' +import { Html } from '@react-three/drei' +import { useCallback, useEffect } from 'react' +import { createPortal } from 'react-dom' +import { create } from 'zustand' +import { type PlanPoint, rampSegmentFrames, rampSegmentThrough } from './centreline' +import { commitRampCreation, rampSiteFrame } from './edit' +import { RampNumberField } from './number-field' + +type Options = Pick +type Draft = { + start: PlanPoint | null + segments: RampNode['segments'] + pendingEnd: PlanPoint | null + hover: PlanPoint | null + mode: 'line' | 'arc' + options: Options + error: string | null +} +export const useRampDraft = create(() => ({ + start: null, + segments: [], + pendingEnd: null, + hover: null, + mode: 'line', + error: null, + options: { width: 3, startHeight: 0, endHeight: -1.5, terrainMode: 'cut-fill', use: 'vehicle' }, +})) +let owners = 0 +function resetDraft() { + useRampDraft.setState({ start: null, segments: [], pendingEnd: null, hover: null, error: null }) +} + +export function rampDraftLastPoint(draft: Draft): PlanPoint | null { + if (!draft.start) return null + return ( + rampSegmentFrames({ start: draft.start, segments: draft.segments }).at(-1)?.end ?? draft.start + ) +} + +export function rampDraftNode(draft: Draft, siteId: string, includeHover = false): RampNode | null { + if (!draft.start) return null + const segments = [...draft.segments] + const last = rampDraftLastPoint(draft) + if (!last) return null + const end = draft.pendingEnd ?? (includeHover ? draft.hover : null) + if (end && Math.hypot(end[0] - last[0], end[1] - last[1]) > 0.01) { + segments.push( + draft.pendingEnd && draft.hover + ? rampSegmentThrough(last, draft.pendingEnd, draft.hover) + : { type: 'line', end }, + ) + } + if (!segments.length) return null + const node = RampNode.parse({ + ...draft.options, + id: 'ramp_preview', + name: 'Ramp', + parentId: siteId, + start: draft.start, + segments, + }) + const transition = rampDefaultTransitionLength(node) + return { ...node, startTransition: transition, endTransition: transition } +} + +export function useRampDraftController({ + sceneApi, + activeLevelId, + selectNode, + finishTool, + view, +}: { + sceneApi: SceneApi + activeLevelId: AnyNodeId | null + selectNode: (id: AnyNodeId) => void + finishTool: () => void + view: '2d' | '3d' +}) { + const draft = useRampDraft() + const frame = rampSiteFrame(sceneApi, activeLevelId) + const addPoint = useCallback((point: PlanPoint) => { + const current = useRampDraft.getState() + if (!current.start) { + useRampDraft.setState({ start: point, hover: point, error: null }) + return + } + const last = rampDraftLastPoint(current) + if (!last) return + if (current.pendingEnd) { + try { + const segment = rampSegmentThrough(last, current.pendingEnd, point) + useRampDraft.setState({ + segments: [...current.segments, segment], + pendingEnd: null, + hover: point, + error: null, + }) + } catch (error) { + useRampDraft.setState({ error: error instanceof Error ? error.message : String(error) }) + } + } else if (Math.hypot(point[0] - last[0], point[1] - last[1]) > 0.01) { + if (current.mode === 'arc') + useRampDraft.setState({ pendingEnd: point, hover: point, error: null }) + else + useRampDraft.setState({ + segments: [...current.segments, { type: 'line', end: point }], + hover: point, + error: null, + }) + } + }, []) + const finish = useCallback(() => { + try { + const current = useRampDraft.getState() + if (current.pendingEnd) throw new Error('Click a bend point to finish the arc first.') + const resolved = rampSiteFrame(sceneApi, activeLevelId) + if (!resolved) throw new Error('Choose a Site before drawing a ramp.') + const preview = rampDraftNode(current, resolved.site.id) + if (!preview) throw new Error('Draw at least one centreline segment.') + const node = RampNode.parse({ ...preview, id: undefined }) + commitRampCreation(sceneApi, node) + resetDraft() + selectNode(node.id) + finishTool() + } catch (error) { + useRampDraft.setState({ error: error instanceof Error ? error.message : String(error) }) + } + }, [activeLevelId, finishTool, sceneApi, selectNode]) + useEffect(() => { + if (owners++ === 0) useInteractionScope.getState().begin({ kind: 'drafting', tool: 'ramp' }) + return () => { + if (--owners === 0) { + resetDraft() + useInteractionScope + .getState() + .endIf((scope) => scope.kind === 'drafting' && scope.tool === 'ramp') + } + } + }, []) + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if (isTypingTarget(event.target)) return + const primary = visibleScene(useEditor.getState()) === '2d' ? '2d' : '3d' + if (view !== primary) return + if (event.key === 'Enter') { + event.preventDefault() + finish() + } + if (event.key === 'Backspace') { + event.preventDefault() + const current = useRampDraft.getState() + if (current.pendingEnd) useRampDraft.setState({ pendingEnd: null }) + else if (current.segments.length) + useRampDraft.setState({ segments: current.segments.slice(0, -1), error: null }) + else resetDraft() + } + if (event.key === 'Escape') { + event.preventDefault() + event.stopImmediatePropagation() + markToolCancelConsumed() + resetDraft() + finishTool() + } + } + window.addEventListener('keydown', onKey, true) + return () => window.removeEventListener('keydown', onKey, true) + }, [finish, finishTool, view]) + let preview: RampNode | null = null + let previewError: string | null = null + if (frame) { + try { + preview = rampDraftNode(draft, frame.site.id, true) + if (preview) rampStations(preview) + } catch (error) { + preview = null + previewError = error instanceof Error ? error.message : String(error) + } + } + return { draft, frame, addPoint, finish, preview, previewError } +} + +export function RampDraftControls({ + view, + finish, + previewError, +}: { + view: '2d' | '3d' + finish: () => void + previewError: string | null +}) { + const primary = useEditor((state) => (visibleScene(state) === '2d' ? '2d' : '3d')) + const draft = useRampDraft() + if (primary !== view || typeof document === 'undefined') return null + const setOptions = (patch: Partial) => + useRampDraft.setState((state) => ({ options: { ...state.options, ...patch } })) + const controls = ( +
+

Draw ramp centreline

+

+ {draft.pendingEnd + ? 'Click sideways to set the arc bend.' + : 'Click points, then press Enter. Arc: click an endpoint, then its bend.'} +

+
+ {(['line', 'arc'] as const).map((mode) => ( + + ))} +
+ setOptions({ width })} + value={draft.options.width} + /> + setOptions({ startHeight })} + value={draft.options.startHeight} + /> + setOptions({ endHeight })} + value={draft.options.endHeight} + /> +

+ Absolute Site heights in metres. Transitions and slope are editable after creation. +

+ {(draft.error || previewError) && ( +

+ {draft.error ?? previewError} +

+ )} + +
+ ) + return view === '3d' ? ( + [size.width / 2, size.height / 2]} + fullscreen + style={{ pointerEvents: 'none' }} + zIndexRange={[80, 0]} + > + {controls} + + ) : ( + createPortal(controls, document.body) + ) +} diff --git a/packages/nodes/src/ramp/edit.ts b/packages/nodes/src/ramp/edit.ts new file mode 100644 index 0000000000..6767554b51 --- /dev/null +++ b/packages/nodes/src/ramp/edit.ts @@ -0,0 +1,74 @@ +import { + type AnyNodeId, + type BuildingNode, + levelLocalToWorldXZ, + planRampCreation, + planRampEdit, + RampNode, + type SceneApi, +} from '@pascal-app/core' + +export function rampSiteFrame(sceneApi: SceneApi, activeLevelId: AnyNodeId | null) { + const nodes = sceneApi.nodes() + const level = activeLevelId ? nodes[activeLevelId] : undefined + const parent = level?.parentId ? nodes[level.parentId as AnyNodeId] : undefined + const building = parent?.type === 'building' ? parent : null + const site = building?.parentId ? nodes[building.parentId as AnyNodeId] : undefined + if (site?.type === 'site') return { site, building } + const sites = Object.values(nodes).filter((node) => node.type === 'site') + const onlySite = sites[0] + return sites.length === 1 && onlySite ? { site: onlySite, building } : null +} + +export function rampPlanToSite( + building: BuildingNode | null, + point: [number, number], +): [number, number] { + return levelLocalToWorldXZ(building, point[0], point[1]) +} + +export function rampSiteToPlan( + building: BuildingNode | null, + point: [number, number], +): [number, number] { + if (!building) return point + const x = point[0] - building.position[0] + const z = point[1] - building.position[2] + const angle = building.rotation[1] + return [Math.cos(angle) * x - Math.sin(angle) * z, Math.sin(angle) * x + Math.cos(angle) * z] +} + +/** A site-plan SVG is already in Site metres; an ordinary plan is building-local. */ +export function rampFloorplanFrame( + building: BuildingNode | null, + activeLevelId: AnyNodeId | null, + drawingType: 'floor-plan' | 'site-plan', +) { + return drawingType === 'site-plan' + ? { building: null, activeLevelId: null } + : { building, activeLevelId } +} + +function applyRampPlan(sceneApi: SceneApi, changes: ReturnType) { + if (!sceneApi.applyChanges) throw new Error('Ramp editing requires atomic scene changes.') + sceneApi.applyChanges({ + create: changes.create?.map(({ node, parentId }) => ({ + node, + parentId: parentId as AnyNodeId | undefined, + })), + update: changes.update?.map(({ id, data }) => ({ id: id as AnyNodeId, data })), + }) +} + +/** Plan first; a refusal leaves both the ramp and the terrain untouched. One write, one undo. */ +export function commitRampEdit(sceneApi: SceneApi, id: RampNode['id'], patch: Partial) { + const current = sceneApi.get(id) + if (current?.type !== 'ramp') throw new Error('The ramp no longer exists.') + const next = RampNode.parse({ ...current, ...patch }) + applyRampPlan(sceneApi, planRampEdit(next, sceneApi.nodes())) +} + +export function commitRampCreation(sceneApi: SceneApi, node: RampNode) { + if (!node.parentId) throw new Error('Choose a Site for the ramp.') + applyRampPlan(sceneApi, planRampCreation(node, sceneApi.nodes())) +} diff --git a/packages/nodes/src/ramp/floorplan-tool.tsx b/packages/nodes/src/ramp/floorplan-tool.tsx new file mode 100644 index 0000000000..6c06b83a64 --- /dev/null +++ b/packages/nodes/src/ramp/floorplan-tool.tsx @@ -0,0 +1,134 @@ +'use client' + +import { rampStations } from '@pascal-app/core' +import { clearSurfacePlanSnapFeedback, type FloorplanToolContext } from '@pascal-app/editor' +import { useEffect, useRef } from 'react' +import { + RampDraftControls, + rampDraftLastPoint, + useRampDraft, + useRampDraftController, +} from './draft' +import { rampFloorplanFrame, rampSiteToPlan } from './edit' +import { snapRampPlanPoint } from './snapping' + +export default function FloorplanRampTool(context: FloorplanToolContext) { + const groupRef = useRef(null) + const { frame, addPoint, finish, draft, preview, previewError } = useRampDraftController({ + ...context, + view: '2d', + }) + const drawingFrame = rampFloorplanFrame( + frame?.building ?? null, + context.activeLevelId, + 'floor-plan', + ) + const siteId = frame?.site.id + const { building, activeLevelId } = drawingFrame + useEffect(() => { + const group = groupRef.current + const svg = group?.ownerSVGElement + if (!(siteId && group && svg)) return + const consume = (event: Event) => { + event.preventDefault() + event.stopPropagation() + event.stopImmediatePropagation() + } + const resolve = (event: MouseEvent | PointerEvent) => { + const matrix = group.getScreenCTM() + if (!matrix) return null + const raw = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix.inverse()) + return snapRampPlanPoint( + [raw.x, raw.y], + rampDraftLastPoint(useRampDraft.getState()), + building, + activeLevelId, + context.gridSnapStep, + event.altKey, + ) + } + const down = (event: PointerEvent) => { + if (event.button === 0) consume(event) + } + const move = (event: PointerEvent) => { + if (event.buttons & 0b110) return + consume(event) + useRampDraft.setState({ hover: resolve(event) }) + } + const click = (event: MouseEvent) => { + if (event.button !== 0) return + consume(event) + const point = resolve(event) + if (point) addPoint(point) + } + const doubleClick = (event: MouseEvent) => { + consume(event) + finish() + } + const leave = () => { + useRampDraft.setState({ hover: null }) + clearSurfacePlanSnapFeedback() + } + svg.addEventListener('pointerdown', down, true) + svg.addEventListener('pointermove', move, true) + svg.addEventListener('click', click, true) + svg.addEventListener('dblclick', doubleClick, true) + svg.addEventListener('pointerleave', leave, true) + return () => { + clearSurfacePlanSnapFeedback() + svg.removeEventListener('pointerdown', down, true) + svg.removeEventListener('pointermove', move, true) + svg.removeEventListener('click', click, true) + svg.removeEventListener('dblclick', doubleClick, true) + svg.removeEventListener('pointerleave', leave, true) + } + }, [addPoint, activeLevelId, context.gridSnapStep, finish, siteId, building]) + const points = + preview && frame + ? rampStations(preview).map((station) => rampSiteToPlan(building, station.point)) + : [] + const hover = draft.hover && frame ? rampSiteToPlan(building, draft.hover) : null + const start = draft.start && frame ? rampSiteToPlan(building, draft.start) : null + return ( + + + {points.length > 1 && ( + <> + point.join(',')).join(' ')} + stroke="#38bdf8" + strokeLinejoin="round" + strokeWidth={draft.options.width} + /> + point.join(',')).join(' ')} + stroke="#0284c7" + strokeWidth={1.5} + vectorEffect="non-scaling-stroke" + /> + + )} + {start && } + {hover && ( + + )} + + + + ) +} diff --git a/packages/nodes/src/ramp/floorplan.ts b/packages/nodes/src/ramp/floorplan.ts new file mode 100644 index 0000000000..71ce9deb72 --- /dev/null +++ b/packages/nodes/src/ramp/floorplan.ts @@ -0,0 +1,96 @@ +import { + type FloorplanGeometry, + type GeometryContext, + type RampNode, + rampStations, +} from '@pascal-app/core' + +export function buildRampFloorplan(node: RampNode, ctx: GeometryContext): FloorplanGeometry | null { + const stations = rampStations(node) + if (stations.length < 2) return null + const left = stations.map( + ({ point, tangent }) => + [point[0] - (tangent[1] * node.width) / 2, point[1] + (tangent[0] * node.width) / 2] as [ + number, + number, + ], + ) + const right = stations.map( + ({ point, tangent }) => + [point[0] + (tangent[1] * node.width) / 2, point[1] - (tangent[0] * node.width) / 2] as [ + number, + number, + ], + ) + const selected = ctx.viewState?.selected || ctx.viewState?.highlighted + const stroke = selected ? (ctx.viewState?.palette.selectedStroke ?? '#0ea5e9') : '#73716c' + const middle = stations[Math.floor(stations.length / 2)] + const first = stations[0] + const last = stations.at(-1) + if (!middle || !first || !last) return null + const arrowSign = node.endHeight >= node.startHeight ? 1 : -1 + const [tx, tz] = middle.tangent + const [x, z] = middle.point + const tip: [number, number] = [x + tx * arrowSign * 0.6, z + tz * arrowSign * 0.6] + return { + kind: 'group', + children: [ + { + kind: 'polygon', + points: [...left, ...right.slice().reverse()], + fill: selected ? (ctx.viewState?.palette.selectedFill ?? '#dbeafe') : '#d6d3cd', + fillOpacity: 0.55, + stroke, + strokeWidth: 1.2, + vectorEffect: 'non-scaling-stroke', + }, + { + kind: 'polyline', + points: stations.map((station) => station.point), + fill: 'none', + stroke, + strokeWidth: 1, + strokeDasharray: '5 4', + vectorEffect: 'non-scaling-stroke', + pointerEvents: 'none', + }, + { + kind: 'line', + x1: x - tx * arrowSign * 0.6, + y1: z - tz * arrowSign * 0.6, + x2: tip[0], + y2: tip[1], + stroke, + strokeWidth: 1.5, + vectorEffect: 'non-scaling-stroke', + pointerEvents: 'none', + }, + { + kind: 'polyline', + points: [ + [tip[0] - tx * arrowSign * 0.25 - tz * 0.18, tip[1] - tz * arrowSign * 0.25 + tx * 0.18], + tip, + [tip[0] - tx * arrowSign * 0.25 + tz * 0.18, tip[1] - tz * arrowSign * 0.25 - tx * 0.18], + ], + fill: 'none', + stroke, + strokeWidth: 1.5, + vectorEffect: 'non-scaling-stroke', + pointerEvents: 'none', + }, + ...[first, last].map( + (station): FloorplanGeometry => ({ + kind: 'text', + x: station.point[0], + y: station.point[1], + text: `${station.height.toFixed(2)} m`, + fontSize: 0.18, + fill: stroke, + textAnchor: 'middle', + dominantBaseline: 'hanging', + upright: true, + }), + ), + ], + } +} diff --git a/packages/nodes/src/ramp/geometry.ts b/packages/nodes/src/ramp/geometry.ts new file mode 100644 index 0000000000..eccfc0f8fc --- /dev/null +++ b/packages/nodes/src/ramp/geometry.ts @@ -0,0 +1,241 @@ +import { type GeometryContext, type RampNode, rampStations } from '@pascal-app/core' +import { + type ColorPreset, + createDefaultMaterial, + createSurfaceRoleMaterial, + type RenderShading, + resolveMaterialRef, +} from '@pascal-app/viewer' +import { + BufferGeometry, + Float32BufferAttribute, + FrontSide, + Group, + type Material, + Mesh, +} from 'three' + +type Station = ReturnType[number] +type Point3 = [number, number, number] +type UV = [number, number] +type Row = { left: Point3; right: Point3; distance: number } +type RibbonWriter = ReturnType + +function ribbonWriter() { + const positions: number[] = [] + const uvs: number[] = [] + const quad = (points: [Point3, Point3, Point3, Point3], texture: [UV, UV, UV, UV]) => { + for (const index of [0, 1, 2, 0, 2, 3]) { + const point = points[index] + const uv = texture[index] + if (point && uv) { + positions.push(...point) + uvs.push(...uv) + } + } + } + return { positions, uvs, quad } +} + +function ribbonRows(stations: Station[], width: number): Row[] { + let distance = 0 + return stations.map((station, index): Row => { + const previous = stations[index - 1] + if (previous) + distance += Math.hypot(station.distance - previous.distance, station.height - previous.height) + const [x, z] = station.point + const [tx, tz] = station.tangent + return { + left: [x - (tz * width) / 2, station.height, z + (tx * width) / 2], + right: [x + (tz * width) / 2, station.height, z - (tx * width) / 2], + distance, + } + }) +} + +function writeRibbonTop(rows: Row[], width: number, writer: RibbonWriter) { + for (let i = 1; i < rows.length; i++) { + const a = rows[i - 1] + const b = rows[i] + if (!a || !b) continue + // Forward along the left edge, then across to the right: upward-facing in XZ. + writer.quad( + [a.left, b.left, b.right, a.right], + [ + [a.distance, 0], + [b.distance, 0], + [b.distance, width], + [a.distance, width], + ], + ) + } +} + +function writeRibbonEdges(rows: Row[], width: number, thickness: number, writer: RibbonWriter) { + const bottom = (point: Point3): Point3 => [point[0], point[1] - thickness, point[2]] + const length3 = (a: Point3, b: Point3) => Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) + let leftDistance = 0 + let rightDistance = 0 + for (let i = 1; i < rows.length; i++) { + const a = rows[i - 1] + const b = rows[i] + if (!a || !b) continue + const nextLeft = leftDistance + length3(a.left, b.left) + const nextRight = rightDistance + length3(a.right, b.right) + writer.quad( + [bottom(a.left), bottom(a.right), bottom(b.right), bottom(b.left)], + [ + [a.distance, 0], + [a.distance, width], + [b.distance, width], + [b.distance, 0], + ], + ) + writer.quad( + [a.left, bottom(a.left), bottom(b.left), b.left], + [ + [leftDistance, 0], + [leftDistance, thickness], + [nextLeft, thickness], + [nextLeft, 0], + ], + ) + writer.quad( + [a.right, b.right, bottom(b.right), bottom(a.right)], + [ + [rightDistance, 0], + [nextRight, 0], + [nextRight, thickness], + [rightDistance, thickness], + ], + ) + leftDistance = nextLeft + rightDistance = nextRight + } + const first = rows[0] + const last = rows.at(-1) + if (!first || !last) return + writer.quad( + [first.left, first.right, bottom(first.right), bottom(first.left)], + [ + [0, 0], + [width, 0], + [width, thickness], + [0, thickness], + ], + ) + writer.quad( + [last.left, bottom(last.left), bottom(last.right), last.right], + [ + [0, 0], + [0, thickness], + [width, thickness], + [width, 0], + ], + ) +} + +/** Separate faces keep top and solid edges crisp; each UV unit is one metre. */ +function solidRibbon(stations: Station[], width: number, thickness: number): BufferGeometry { + const geometry = new BufferGeometry() + if (stations.length < 2) return geometry + const rows = ribbonRows(stations, width) + const writer = ribbonWriter() + writeRibbonTop(rows, width, writer) + const edgeStart = writer.positions.length / 3 + writeRibbonEdges(rows, width, thickness, writer) + geometry.addGroup(0, edgeStart, 0) + geometry.addGroup(edgeStart, writer.positions.length / 3 - edgeStart, 1) + geometry.setAttribute('position', new Float32BufferAttribute(writer.positions, 3)) + geometry.setAttribute('uv', new Float32BufferAttribute(writer.uvs, 2)) + geometry.setAttribute('uv2', new Float32BufferAttribute(writer.uvs, 2)) + geometry.computeVertexNormals() + geometry.computeBoundingBox() + geometry.computeBoundingSphere() + return geometry +} + +/** Site-local positions, absolute Site-local top Y, thickness down. */ +export function buildRampRibbonGeometry(node: RampNode): BufferGeometry { + return solidRibbon(rampStations(node), node.width, node.thickness) +} + +function addRibbonMeshes(group: Group, ribbon: BufferGeometry, materials: Material[]) { + for (const [index, slot] of ['surface', 'edge'].entries()) { + const range = ribbon.groups[index] + const material = materials[index] + if (!range || !material) continue + const geometry = new BufferGeometry() + for (const key of ['position', 'normal', 'uv', 'uv2']) { + const attribute = ribbon.getAttribute(key) + geometry.setAttribute( + key, + new Float32BufferAttribute( + Array.from(attribute.array).slice( + range.start * attribute.itemSize, + (range.start + range.count) * attribute.itemSize, + ), + attribute.itemSize, + ), + ) + } + geometry.computeBoundingBox() + geometry.computeBoundingSphere() + const mesh = new Mesh(geometry, material) + mesh.name = `ramp-${slot}` + mesh.userData.slotId = slot + mesh.castShadow = true + mesh.receiveShadow = true + group.add(mesh) + } + ribbon.dispose() +} + +function addRetainingSides(group: Group, node: RampNode, material: Material) { + const wallWidth = 0.2 + const stations = rampStations(node) + for (const side of [-1, 1]) { + const offset = side * (node.width / 2 + wallWidth / 2) + const wallStations = stations.map((station) => ({ + ...station, + height: station.height + node.retainingHeight, + point: [ + station.point[0] - station.tangent[1] * offset, + station.point[1] + station.tangent[0] * offset, + ] as [number, number], + })) + // The side retains the cut above the roadway and embeds to its underside. + const wall = new Mesh( + solidRibbon(wallStations, wallWidth, node.retainingHeight + node.thickness), + material, + ) + wall.name = side > 0 ? 'ramp-retaining-left' : 'ramp-retaining-right' + wall.userData.slotId = 'retaining' + wall.castShadow = true + wall.receiveShadow = true + group.add(wall) + } +} + +export function buildRampGeometry( + node: RampNode, + ctx?: GeometryContext, + shading: RenderShading = 'rendered', + textures = true, + colorPreset: ColorPreset = 'clay', + sceneTheme?: string, +): Group { + const group = new Group() + const material = (slot: string, color: string) => { + if (!textures) return createSurfaceRoleMaterial('floor', colorPreset, FrontSide, sceneTheme) + const resolved = resolveMaterialRef(node.slots?.[slot], ctx?.materials, shading) + if (resolved) return resolved + return createDefaultMaterial(color, 0.85, shading, FrontSide) + } + addRibbonMeshes(group, buildRampRibbonGeometry(node), [ + material('surface', '#aaa69c'), + material('edge', '#88857e'), + ]) + if (node.retainingHeight > 0) addRetainingSides(group, node, material('retaining', '#88857e')) + return group +} diff --git a/packages/nodes/src/ramp/index.ts b/packages/nodes/src/ramp/index.ts new file mode 100644 index 0000000000..ce5202f005 --- /dev/null +++ b/packages/nodes/src/ramp/index.ts @@ -0,0 +1,11 @@ +export { moveRampPoint, rampSegmentEnd, rampSegmentFrames, rampSegmentThrough } from './centreline' +export { rampDefinition } from './definition' +export { + commitRampCreation, + commitRampEdit, + rampFloorplanFrame, + rampPlanToSite, + rampSiteToPlan, +} from './edit' +export { buildRampFloorplan } from './floorplan' +export { buildRampGeometry, buildRampRibbonGeometry } from './geometry' diff --git a/packages/nodes/src/ramp/number-field.tsx b/packages/nodes/src/ramp/number-field.tsx new file mode 100644 index 0000000000..e005348608 --- /dev/null +++ b/packages/nodes/src/ramp/number-field.tsx @@ -0,0 +1,62 @@ +'use client' + +import { useEffect, useRef, useState } from 'react' + +export function RampNumberField({ + label, + value, + onCommit, + unit = 'm', + min, +}: { + label: string + value: number + onCommit: (value: number) => void + unit?: string + min?: number +}) { + const [text, setText] = useState(String(value)) + const cancelled = useRef(false) + useEffect(() => setText(String(value)), [value]) + const commit = () => { + if (cancelled.current) { + cancelled.current = false + return + } + const next = Number(text) + if ( + text.trim() && + Number.isFinite(next) && + (min === undefined || next >= min) && + next !== value + ) + onCommit(next) + setText(String(value)) + } + return ( + + ) +} diff --git a/packages/nodes/src/ramp/panel.tsx b/packages/nodes/src/ramp/panel.tsx new file mode 100644 index 0000000000..c1008d0c67 --- /dev/null +++ b/packages/nodes/src/ramp/panel.tsx @@ -0,0 +1,413 @@ +'use client' + +import { + createSceneApi, + type RampNode, + rampFacts, + rampStations, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { isTypingTarget, PanelSection, PanelWrapper, useInteractionScope } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { type PointerEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { moveRampPoint, type PlanPoint, rampSegmentFrames, rampSegmentThrough } from './centreline' +import { commitRampEdit } from './edit' +import { RampNumberField } from './number-field' + +type Grip = { kind: 'point' | 'bend'; index: number } + +/** The same little plan editor is available from either viewport's inspector. */ +function CentrelineEditor({ + node, + commit, + report, +}: { + node: RampNode + commit: (patch: Partial) => void + report: (message: string | null) => void +}) { + const [preview, setPreview] = useState(node) + const [activeSegment, setActiveSegment] = useState(0) + const drag = useRef<{ grip: Grip; initial: RampNode; patch: Partial | null } | null>( + null, + ) + const svgRef = useRef(null) + const frames = rampSegmentFrames(preview) + const stations = rampStations(preview) + const original = rampStations(node) + const xs = original.map((station) => station.point[0]) + const zs = original.map((station) => station.point[1]) + const minX = Math.min(...xs) - node.width + const minZ = Math.min(...zs) - node.width + const size = Math.max(Math.max(...xs) - minX + node.width, Math.max(...zs) - minZ + node.width, 5) + const radius = size / 55 + const clear = useCallback(() => { + drag.current = null + useLiveNodeOverrides.getState().clear(node.id) + useScene.getState().markDirty(node.id) + useInteractionScope + .getState() + .endIf( + (scope) => + scope.kind === 'handle-drag' && + scope.nodeId === node.id && + scope.handle === 'ramp-centreline', + ) + }, [node.id]) + useEffect(() => { + setPreview(node) + setActiveSegment((index) => Math.min(index, node.segments.length - 1)) + }, [node]) + useEffect(() => clear, [clear]) + useEffect(() => { + const cancel = () => { + if (drag.current) { + clear() + setPreview(node) + } + } + const onKey = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || !drag.current || isTypingTarget(event.target)) return + event.preventDefault() + cancel() + } + window.addEventListener('keydown', onKey) + window.addEventListener('blur', cancel) + return () => { + window.removeEventListener('keydown', onKey) + window.removeEventListener('blur', cancel) + } + }, [clear, node]) + const start = (event: PointerEvent, grip: Grip) => { + if (event.button !== 0) return + event.preventDefault() + event.stopPropagation() + svgRef.current?.setPointerCapture(event.pointerId) + drag.current = { grip, initial: node, patch: null } + if (grip.kind === 'bend') setActiveSegment(grip.index) + useInteractionScope + .getState() + .begin({ kind: 'handle-drag', nodeId: node.id, handle: 'ramp-centreline' }) + } + const move = (event: PointerEvent) => { + const current = drag.current + const matrix = event.currentTarget.getScreenCTM() + if (!(current && matrix)) return + const local = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix.inverse()) + const point: PlanPoint = [local.x, local.y] + try { + let patch: Partial + if (current.grip.kind === 'point') + patch = moveRampPoint(current.initial, current.grip.index, point) + else { + const frame = rampSegmentFrames(current.initial)[current.grip.index] + if (!frame) return + const segments = [...current.initial.segments] + segments[current.grip.index] = rampSegmentThrough(frame.start, frame.end, point) + patch = { segments } + } + const next = { ...current.initial, ...patch } + rampStations(next) + current.patch = patch + setPreview(next) + useLiveNodeOverrides.getState().set(node.id, patch) + useScene.getState().markDirty(node.id) + report(null) + } catch (error) { + current.patch = null + report(error instanceof Error ? error.message : String(error)) + } + } + const end = (event: PointerEvent, cancelled = false) => { + const patch = drag.current?.patch + clear() + if (event.currentTarget.hasPointerCapture(event.pointerId)) + event.currentTarget.releasePointerCapture(event.pointerId) + if (!cancelled && patch) commit(patch) + setPreview(node) + } + const frame = frames[activeSegment] + return ( +
+

+ Drag orange endpoints to route the ramp. Drag a blue midpoint sideways to bend a segment + into an arc. +

+ { + if (drag.current) { + clear() + setPreview(node) + } + }} + onPointerCancel={(event) => end(event, true)} + onPointerMove={move} + onPointerUp={(event) => end(event)} + ref={svgRef} + style={{ touchAction: 'none' }} + viewBox={`${minX} ${minZ} ${size} ${size}`} + > + station.point.join(',')).join(' ')} + stroke="#a8a29e" + strokeLinecap="butt" + strokeLinejoin="round" + strokeWidth={node.width} + /> + station.point.join(',')).join(' ')} + stroke="#0369a1" + strokeWidth={radius / 3} + /> + {[preview.start, ...frames.map((part) => part.end)].map((point, index) => ( + start(event, { kind: 'point', index })} + r={radius} + style={{ cursor: 'grab' }} + /> + ))} + {frames.map((part, index) => ( + start(event, { kind: 'bend', index })} + r={radius} + style={{ cursor: 'grab' }} + /> + ))} + + + {frame && ( + <> + commit(moveRampPoint(node, activeSegment + 1, [x, frame.end[1]]))} + value={frame.end[0]} + /> + commit(moveRampPoint(node, activeSegment + 1, [frame.end[0], z]))} + value={frame.end[1]} + /> + {frame.segment.type === 'arc' && ( + <> + { + const segments = [...node.segments] + segments[activeSegment] = { + ...(frame.segment as Extract), + sweep: (degrees * Math.PI) / 180, + } + commit({ segments }) + }} + unit="°" + value={(frame.segment.sweep * 180) / Math.PI} + /> + + + )} + + + )} +
+ ) +} + +export default function RampPanel({ node }: { node: RampNode }) { + return +} + +function RampPanelContent({ node }: { node: RampNode }) { + const sceneApi = useMemo(() => createSceneApi(useScene), []) + const [error, setError] = useState(null) + const nodes = useScene((state) => state.nodes) + const facts = rampFacts(node, nodes) + const commit = useCallback( + (patch: Partial) => { + try { + commitRampEdit(sceneApi, node.id, patch) + setError(null) + } catch (error) { + setError(error instanceof Error ? error.message : String(error)) + } + }, + [node.id, sceneApi], + ) + return ( + useViewer.getState().setSelection({ selectedIds: [] })} + title="Ramp" + width={320} + > + {error && ( +

+ {error} +

+ )} + + commit({ width })} + value={node.width} + /> + commit({ startHeight })} + value={node.startHeight} + /> + commit({ endHeight })} + value={node.endHeight} + /> +

+ Heights are absolute in the Site frame. Terrain regrades with each edit when cut and fill + is on. +

+ commit({ startTransition })} + value={node.startTransition} + /> + commit({ endTransition })} + value={node.endTransition} + /> + commit({ thickness })} + value={node.thickness} + /> + commit({ retainingHeight })} + value={node.retainingHeight} + /> + commit({ maxSlopePercent })} + unit="%" + value={node.maxSlopePercent} + /> + + +
+ +

+ Length {facts.lengthM.toFixed(2)} m · Rise {facts.riseM.toFixed(2)} m +

+

+ Average slope {facts.averageSlopePercent.toFixed(1)}% · Maximum{' '} + {facts.maximumSlopePercent.toFixed(1)}% +

+ {facts.warnings.map((warning, index) => ( +

+ {warning.message} +

+ ))} +
+ + commit(moveRampPoint(node, 0, [x, node.start[1]]))} + value={node.start[0]} + /> + commit(moveRampPoint(node, 0, [node.start[0], z]))} + value={node.start[1]} + /> + + +
+ ) +} diff --git a/packages/nodes/src/ramp/ramp-geometry.test.ts b/packages/nodes/src/ramp/ramp-geometry.test.ts new file mode 100644 index 0000000000..a37b0dc4e1 --- /dev/null +++ b/packages/nodes/src/ramp/ramp-geometry.test.ts @@ -0,0 +1,231 @@ +import { describe, expect, test } from 'bun:test' +import { type GeometryContext, rampFacts } from '@pascal-app/core' +import { isAgentRefusal } from '@pascal-app/core/agent-tools' +import { RampNode } from '@pascal-app/core/schema' +import { buildRampFloorplan, buildRampRibbonGeometry } from '@pascal-app/nodes' +import { type BufferGeometry, DoubleSide, Mesh, MeshBasicMaterial, Raycaster, Vector3 } from 'three' + +function ramp(overrides: Partial = {}): RampNode { + return RampNode.parse({ + id: 'ramp_geometry', + parentId: 'site_geometry', + start: [0, 0], + segments: [{ type: 'line', end: [20, 0] }], + width: 4, + startHeight: 4, + endHeight: 0.8, + thickness: 0.25, + startTransition: 0, + endTransition: 0, + retainingHeight: 0, + terrainMode: 'none', + ...overrides, + }) +} + +function vertices(geometry: BufferGeometry): [number, number, number][] { + const position = geometry.getAttribute('position') + return Array.from({ length: position.count }, (_, index) => [ + position.getX(index), + position.getY(index), + position.getZ(index), + ]) +} + +// These assertions observe the solid, not a tessellation, vertex order or material implementation. +// A linear ramp has an analytical top plane; the thickness extends vertically downward from it. +describe('ramp solid ribbon', () => { + test('rejects a non-tangent joint while constructing ramp facts and ribbon geometry', () => { + const node = ramp({ + start: [0, 0], + segments: [ + { type: 'line', end: [10, 0] }, + { + type: 'line', + end: [10 + 10 * Math.cos((20 * Math.PI) / 180), 10 * Math.sin((20 * Math.PI) / 180)], + }, + ], + startHeight: 0, + endHeight: 2, + startTransition: 0, + endTransition: 0, + maxSlopePercent: 18, + }) + for (const create of [() => rampFacts(node, {}), () => buildRampRibbonGeometry(node)]) { + try { + create() + throw new Error('expected non-tangent joint refusal') + } catch (error) { + if (!isAgentRefusal(error)) throw error + expect(error.code).toBe('ramp_joint_not_tangent') + expect(error.details).toMatchObject({ + jointIndex: 1, + toleranceRadians: 1e-6, + }) + expect(error.details?.angleDegrees).toBeCloseTo(20, 9) + } + } + }) + + test('accepts a straight two-segment centreline', () => { + const geometry = buildRampRibbonGeometry( + ramp({ + segments: [ + { type: 'line', end: [10, 0] }, + { type: 'line', end: [20, 0] }, + ], + }), + ) + geometry.computeBoundingBox() + expect(geometry.boundingBox?.min.x).toBeCloseTo(0, 8) + expect(geometry.boundingBox?.max.x).toBeCloseTo(20, 8) + geometry.dispose() + }) + + test('a 1100 m accepted ramp has a complete ribbon and floorplan at default resolution', () => { + const node = ramp({ + segments: [{ type: 'line', end: [1100, 0] }], + startHeight: 0, + endHeight: 110, + }) + const geometry = buildRampRibbonGeometry(node) + try { + geometry.computeBoundingBox() + expect(geometry.boundingBox?.min.x).toBeCloseTo(0, 5) + expect(geometry.boundingBox?.max.x).toBeCloseTo(1100, 5) + expect(geometry.boundingBox?.min.y).toBeCloseTo(-0.25, 5) + expect(geometry.boundingBox?.max.y).toBeCloseTo(110, 5) + const context = { + resolve: () => undefined, + parent: null, + children: [], + siblings: [], + } satisfies GeometryContext + const plan = buildRampFloorplan(node, context) + if (plan?.kind !== 'group') throw new Error('The long ramp has no floorplan') + const outline = plan.children.find((child) => child.kind === 'polygon') + if (outline?.kind !== 'polygon') throw new Error('The long ramp has no floorplan outline') + expect(Math.min(...outline.points.map(([x]) => x))).toBeCloseTo(0, 5) + expect(Math.max(...outline.points.map(([x]) => x))).toBeCloseTo(1100, 5) + expect(Math.min(...outline.points.map(([, z]) => z))).toBeCloseTo(-2, 5) + expect(Math.max(...outline.points.map(([, z]) => z))).toBeCloseTo(2, 5) + } finally { + geometry.dispose() + } + }) + + test('the rendered top includes the entry and exit grade transitions', () => { + const geometry = buildRampRibbonGeometry(ramp({ startTransition: 2, endTransition: 6 })) + const material = new MeshBasicMaterial({ side: DoubleSide }) + const mesh = new Mesh(geometry, material) + try { + mesh.updateMatrixWorld(true) + for (const [distance, height] of [ + [2, 3.8], + [10, 2.2], + [14, 1.4], + ] as const) { + const ray = new Raycaster(new Vector3(distance, 10, 0), new Vector3(0, -1, 0)) + const top = ray.intersectObject(mesh)[0] + if (!top) throw new Error(`The ramp has no surface at distance ${distance}`) + expect(top.point.y).toBeCloseTo(height, 3) + } + } finally { + geometry.dispose() + material.dispose() + } + }) + + test('keeps the requested width, both endpoint elevations and downward thickness', () => { + const geometry = buildRampRibbonGeometry(ramp()) + try { + const points = vertices(geometry) + expect(points.length).toBeGreaterThan(0) + geometry.computeBoundingBox() + expect(geometry.boundingBox?.min.x).toBeCloseTo(0, 5) + expect(geometry.boundingBox?.max.x).toBeCloseTo(20, 5) + expect(geometry.boundingBox?.min.z).toBeCloseTo(-2, 5) + expect(geometry.boundingBox?.max.z).toBeCloseTo(2, 5) + expect(geometry.boundingBox?.min.y).toBeCloseTo(0.55, 5) + expect(geometry.boundingBox?.max.y).toBeCloseTo(4, 5) + for (const [x, y, z] of points) { + const top = 4 - 0.16 * x + expect(Number.isFinite(x + y + z)).toBe(true) + expect(y).toBeLessThanOrEqual(top + 0.00001) + expect(y).toBeGreaterThanOrEqual(top - 0.25001) + } + for (const [x, y] of [ + [0, 4], + [20, 0.8], + ] as const) { + for (const z of [-2, 2]) { + for (const height of [y, y - 0.25]) { + expect( + points.some( + (point) => + Math.abs(point[0] - x) < 0.00001 && + Math.abs(point[1] - height) < 0.00001 && + Math.abs(point[2] - z) < 0.00001, + ), + ).toBe(true) + } + } + } + } finally { + geometry.dispose() + } + }) + + test('a three-quarter spiral is an annular strip, not a fan filling the centre', () => { + const geometry = buildRampRibbonGeometry( + ramp({ + start: [10, 0], + segments: [{ type: 'arc', center: [0, 0], sweep: (3 * Math.PI) / 2 }], + startHeight: 4, + endHeight: 1, + }), + ) + try { + const points = vertices(geometry) + expect(points.length).toBeGreaterThan(0) + for (const [x, y, z] of points) { + expect(Number.isFinite(x + y + z)).toBe(true) + expect(Math.hypot(x, z)).toBeGreaterThanOrEqual(7.99999) + expect(Math.hypot(x, z)).toBeLessThanOrEqual(12.00001) + expect(y).toBeGreaterThanOrEqual(0.74999) + expect(y).toBeLessThanOrEqual(4.00001) + } + for (const [x, z, height] of [ + [8, 0, 4], + [12, 0, 4], + [0, -8, 1], + [0, -12, 1], + ] as const) { + expect( + points.some( + ([px, py, pz]) => + Math.abs(px - x) < 0.00001 && + Math.abs(py - height) < 0.00001 && + Math.abs(pz - z) < 0.00001, + ), + ).toBe(true) + } + const position = geometry.getAttribute('position') + const index = geometry.getIndex() + const count = index?.count ?? position.count + expect(count % 3).toBe(0) + for (let offset = 0; offset < count; offset += 3) { + const triangle = [0, 1, 2].map((corner) => { + const vertex = index ? index.getX(offset + corner) : offset + corner + return [position.getX(vertex), position.getZ(vertex)] as const + }) + const x = triangle.reduce((sum, point) => sum + point[0], 0) / 3 + const z = triangle.reduce((sum, point) => sum + point[1], 0) / 3 + // 0.1 m chord allowance accommodates a different valid station tessellation. + expect(Math.hypot(x, z)).toBeGreaterThan(7.9) + } + } finally { + geometry.dispose() + } + }) +}) diff --git a/packages/nodes/src/ramp/ramp-plan.test.ts b/packages/nodes/src/ramp/ramp-plan.test.ts new file mode 100644 index 0000000000..4548e15cdb --- /dev/null +++ b/packages/nodes/src/ramp/ramp-plan.test.ts @@ -0,0 +1,190 @@ +import { describe, expect, test } from 'bun:test' +import { + BuildingNode, + createSceneApi, + createTerrainField, + encodeTerrainField, + type FloorplanGeometry, + heightAt, + LevelNode, + loadPlugin, + nodeRegistry, + persistedTerrainFieldOf, + RampNode, + type SceneSnapshot, + SiteNode, + useScene, +} from '@pascal-app/core' +import { buildSitePlanDrawing } from '@pascal-app/editor' +import { + builtinPlugin, + commitRampCreation, + commitRampEdit, + rampFloorplanFrame, + rampPlanToSite, + rampSiteToPlan, +} from '@pascal-app/nodes' + +type Point = [number, number] + +function polygonPoints( + geometry: FloorplanGeometry, + toWorld: (point: Point) => Point = (point) => point, +): Point[][] { + if (geometry.kind === 'polygon') return [geometry.points.map(toWorld)] + if (geometry.kind !== 'group') return [] + const { translate = [0, 0], rotate = 0 } = geometry.transform ?? {} + const transform = ([x, z]: Point): Point => + toWorld([ + x * Math.cos(rotate) - z * Math.sin(rotate) + translate[0], + x * Math.sin(rotate) + z * Math.cos(rotate) + translate[1], + ]) + return geometry.children.flatMap((child) => polygonPoints(child, transform)) +} + +function hasRampOutline(primitives: FloorplanGeometry[]): boolean { + return primitives + .flatMap((primitive) => polygonPoints(primitive)) + .some((points) => { + const xs = points.map(([x]) => x) + const zs = points.map(([, z]) => z) + return ( + Math.abs(Math.min(...xs)) < 1e-8 && + Math.abs(Math.max(...xs) - 10) < 1e-8 && + Math.abs(Math.min(...zs) + 2) < 1e-8 && + Math.abs(Math.max(...zs) - 2) < 1e-8 + ) + }) +} + +describe('ramp plan coordinate frames', () => { + const building = BuildingNode.parse({ + id: 'building_plan', + position: [10, 0, 20], + rotation: [0, Math.PI / 2, 0], + }) + + test('Site-plan clicks remain in Site metres despite the active building transform', () => { + const frame = rampFloorplanFrame(building, 'level_plan', 'site-plan') + for (const point of [ + [0, 0], + [10, 0], + [2, 3], + ] satisfies Point[]) { + expect(rampPlanToSite(frame.building, point)).toEqual(point) + expect(rampSiteToPlan(frame.building, point)).toEqual(point) + } + expect(frame.activeLevelId).toBeNull() + }) + + test('ordinary floor-plan clicks still convert from the active building frame', () => { + const frame = rampFloorplanFrame(building, 'level_plan', 'floor-plan') + const sitePoint = rampPlanToSite(frame.building, [2, 3]) + expect(sitePoint[0]).toBeCloseTo(13, 8) + expect(sitePoint[1]).toBeCloseTo(18, 8) + const planPoint = rampSiteToPlan(frame.building, [13, 18]) + expect(planPoint[0]).toBeCloseTo(2, 8) + expect(planPoint[1]).toBeCloseTo(3, 8) + expect(frame.activeLevelId).toBe('level_plan') + }) + + test('a committed built-in ramp appears in the Site drawing without building translation or rotation', async () => { + const restore = nodeRegistry._snapshot() + try { + nodeRegistry._reset() + await loadPlugin(builtinPlugin) + const site = SiteNode.parse({ + id: 'site_plan', + children: [building.id, 'ramp_plan'], + polygon: { + type: 'polygon', + points: [ + [-20, -20], + [40, -20], + [40, 40], + [-20, 40], + ], + }, + }) + const host = BuildingNode.parse({ ...building, parentId: site.id, children: ['level_plan'] }) + const level = LevelNode.parse({ id: 'level_plan', parentId: host.id, level: 0, height: 3 }) + const ramp = RampNode.parse({ + id: 'ramp_plan', + parentId: site.id, + start: [0, 0], + segments: [{ type: 'line', end: [10, 0] }], + width: 4, + startHeight: 0, + endHeight: 1, + terrainMode: 'none', + }) + const scene: SceneSnapshot = { + nodes: Object.fromEntries([site, host, level, ramp].map((node) => [node.id, node])), + rootNodeIds: [site.id], + collections: {}, + materials: {}, + installedPlugins: [], + } + expect(hasRampOutline(buildSitePlanDrawing(scene).primitives)).toBe(true) + const hidden = { + ...scene, + nodes: { ...scene.nodes, [ramp.id]: { ...ramp, visible: false } }, + } + expect(hasRampOutline(buildSitePlanDrawing(hidden).primitives)).toBe(false) + } finally { + restore() + } + }) +}) + +test('the inspector reroutes its owned ground in one undo step', () => { + const original = useScene.getState() + try { + const site = SiteNode.parse({ + id: 'site_inspector', + terrain: encodeTerrainField( + createTerrainField({ origin: [-2, -3], cols: 29, rows: 25, spacing: 0.5 }), + ), + }) + useScene.getState().setScene({ [site.id]: site }, [site.id]) + const api = createSceneApi(useScene) + const ramp = RampNode.parse({ + parentId: site.id, + start: [0, 0], + segments: [{ type: 'line', end: [10, 0] }], + width: 3, + startHeight: 0, + endHeight: -2, + thickness: 0.15, + terrainMode: 'cut-fill', + }) + commitRampCreation(api, ramp) + useScene.temporal.getState().clear() + const before = structuredClone(useScene.getState().nodes) + const beforeField = persistedTerrainFieldOf(site, before) + if (!beforeField) throw new Error('Missing initial ramp grading') + expect(heightAt(beforeField, 5, 0)).toBeCloseTo(-1.15, 8) + expect(heightAt(beforeField, 5, 5)).toBeCloseTo(0, 8) + commitRampEdit(api, ramp.id, { + start: [0, 5], + segments: [{ type: 'line', end: [10, 5] }], + }) + const after = useScene.getState().nodes + const ground = after[site.id] + if (ground?.type !== 'site') throw new Error('The Site was removed') + const field = persistedTerrainFieldOf(ground, after) + if (!field) throw new Error('Missing terrain') + expect(heightAt(field, 5, 0)).toBeCloseTo(0, 8) + expect(heightAt(field, 5, 5)).toBeCloseTo(-1.15, 8) + expect(ground.terrain).toEqual(site.terrain) + const moved = structuredClone(after) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(moved) + } finally { + useScene.setState(original) + useScene.temporal.getState().clear() + } +}) diff --git a/packages/nodes/src/ramp/snapping.ts b/packages/nodes/src/ramp/snapping.ts new file mode 100644 index 0000000000..e05807e509 --- /dev/null +++ b/packages/nodes/src/ramp/snapping.ts @@ -0,0 +1,40 @@ +import type { AnyNodeId, BuildingNode } from '@pascal-app/core' +import { + isAngleSnapActive, + isGridSnapActive, + isMagneticSnapActive, + resolveSurfacePlanPointSnap, +} from '@pascal-app/editor' +import type { PlanPoint } from './centreline' +import { rampPlanToSite, rampSiteToPlan } from './edit' + +export function snapRampPlanPoint( + raw: PlanPoint, + lastSite: PlanPoint | null, + building: BuildingNode | null, + activeLevelId: AnyNodeId | null, + gridStep: number, + force: boolean, +): PlanPoint { + let point = raw + if (!force && lastSite && isAngleSnapActive()) { + const start = rampSiteToPlan(building, lastSite) + const length = Math.hypot(raw[0] - start[0], raw[1] - start[1]) + const angle = + (Math.round(Math.atan2(raw[1] - start[1], raw[0] - start[0]) / (Math.PI / 4)) * Math.PI) / 4 + point = [start[0] + Math.cos(angle) * length, start[1] + Math.sin(angle) * length] + } + const step = !force && isGridSnapActive() ? gridStep : 0 + const fallback: PlanPoint = + step > 0 ? [Math.round(point[0] / step) * step, Math.round(point[1] / step) * step] : point + const result = activeLevelId + ? resolveSurfacePlanPointSnap({ + rawPoint: point, + fallbackPoint: fallback, + levelId: activeLevelId, + magnetic: !force && isMagneticSnapActive(), + align: !force && isMagneticSnapActive(), + }).point + : fallback + return rampPlanToSite(building, result) +} diff --git a/packages/nodes/src/ramp/tool.tsx b/packages/nodes/src/ramp/tool.tsx new file mode 100644 index 0000000000..2c29441119 --- /dev/null +++ b/packages/nodes/src/ramp/tool.tsx @@ -0,0 +1,114 @@ +'use client' + +import { emitter, type GridEvent } from '@pascal-app/core' +import { + clearSurfacePlanSnapFeedback, + EDITOR_LAYER, + useEditor, + useRegistryToolContext, +} from '@pascal-app/editor' +import { createPortal, useThree } from '@react-three/fiber' +import { useCallback, useEffect, useMemo } from 'react' +import { + stopPlacementCommitPropagation, + subscribeFloorPlacementClicks, + subscribeFloorPlacementDoubleClicks, +} from '../shared/floor-placement' +import { + RampDraftControls, + rampDraftLastPoint, + useRampDraft, + useRampDraftController, +} from './draft' +import { rampSiteToPlan } from './edit' +import { buildRampGeometry } from './geometry' +import { snapRampPlanPoint } from './snapping' + +export default function RampTool() { + const context = useRegistryToolContext() + const scene = useThree((state) => state.scene) + const finishTool = useCallback(() => useEditor.getState().setTool(null), []) + const controller = useRampDraftController({ ...context, finishTool, view: '3d' }) + const { frame, addPoint, finish, preview, previewError, draft } = controller + const siteId = frame?.site.id + const building = frame?.building ?? null + const ghost = useMemo(() => { + if (!preview) return null + const group = buildRampGeometry(preview, undefined, 'solid', false) + group.traverse((object) => { + object.raycast = () => {} + object.layers.set(EDITOR_LAYER) + object.castShadow = false + object.receiveShadow = false + }) + return group + }, [preview]) + useEffect( + () => () => { + ghost?.traverse((object) => { + if ('geometry' in object) (object.geometry as { dispose: () => void }).dispose() + }) + }, + [ghost], + ) + useEffect(() => { + if (!siteId) return + const resolve = (position: [number, number, number], alt = false) => + snapRampPlanPoint( + rampSiteToPlan(building, [position[0], position[2]]), + rampDraftLastPoint(useRampDraft.getState()), + building, + context.activeLevelId, + useEditor.getState().gridSnapStep, + alt, + ) + const isCanvasEvent = (native?: { target: EventTarget | null }) => + typeof HTMLCanvasElement !== 'undefined' && native?.target instanceof HTMLCanvasElement + const move = (event: GridEvent) => { + if (!isCanvasEvent(event.nativeEvent) || context.isCameraDragging()) return + useRampDraft.setState({ hover: resolve(event.position, event.nativeEvent?.altKey) }) + } + emitter.on('grid:move', move) + const unsubscribeClick = subscribeFloorPlacementClicks((event) => { + if (!isCanvasEvent(event.nativeEvent) || context.isCameraDragging()) return + addPoint(resolve(event.position, event.nativeEvent?.altKey)) + stopPlacementCommitPropagation(event) + }) + const unsubscribeDouble = subscribeFloorPlacementDoubleClicks((event) => { + if (!isCanvasEvent(event.nativeEvent) || context.isCameraDragging()) return + stopPlacementCommitPropagation(event) + finish() + }) + return () => { + emitter.off('grid:move', move) + unsubscribeClick() + unsubscribeDouble() + clearSurfacePlanSnapFeedback() + } + }, [addPoint, context.activeLevelId, context.isCameraDragging, finish, siteId, building]) + return ( + <> + {createPortal( + <> + {ghost && } + {draft.start && ( + {}} + > + + + + )} + , + scene, + )} + + + ) +} diff --git a/packages/nodes/src/rock/material.ts b/packages/nodes/src/rock/material.ts new file mode 100644 index 0000000000..47fe2ce0da --- /dev/null +++ b/packages/nodes/src/rock/material.ts @@ -0,0 +1,67 @@ +import { + color, + float, + mix, + mx_fractal_noise_float, + normalWorld, + positionWorld, + sin, + smoothstep, +} from 'three/tsl' +import { MeshStandardNodeMaterial } from 'three/webgpu' + +export type RockLook = { strata: boolean; lichen: number } + +const STONE_DARK = color('#6f6a62') +const STONE_LIGHT = color('#a49d90') +const STRATA_TINT = color('#8a7c68') +const LICHEN = color('#7c8a4a') +/** Metres of rock a stone-colour patch spans. */ +const PATCH = 0.7 +/** Metres between strata bands. */ +const BAND = 0.35 + +/** + * Stone colour for a rock from where each point is in the world, so it needs no UVs and a rock + * keeps its look when its outline or height changes: patches of light and dark stone, optional + * horizontal strata, and lichen on the faces that look up. + */ +export function rockColorNode({ strata, lichen }: RockLook) { + const patches = mx_fractal_noise_float(positionWorld.div(PATCH), 3, 2, 0.5).mul(0.5).add(0.5) + let stone = mix(STONE_DARK, STONE_LIGHT, smoothstep(0.25, 0.75, patches)) + if (strata) { + const wobble = mx_fractal_noise_float(positionWorld.mul(0.9), 2, 2, 0.5).mul(0.12) + const band = sin( + positionWorld.y + .add(wobble) + .div(BAND) + .mul(Math.PI * 2), + ) + .mul(0.5) + .add(0.5) + stone = mix(stone, STRATA_TINT, smoothstep(0.55, 0.9, band).mul(0.45)) + } + if (lichen > 0) { + const up = smoothstep(0.55, 0.9, normalWorld.y) + const spots = smoothstep( + float(1).sub(lichen), + float(1).sub(lichen).add(0.15), + mx_fractal_noise_float(positionWorld.mul(1.8), 2, 2, 0.5).mul(0.5).add(0.5), + ) + stone = mix(stone, LICHEN, up.mul(spots).mul(0.85)) + } + return stone +} + +const cache = new Map() + +/** One material per look: rocks that look alike share it. */ +export function rockMaterial(look: RockLook): MeshStandardNodeMaterial { + const key = `${look.strata}:${Math.round(look.lichen * 20)}` + const cached = cache.get(key) + if (cached) return cached + const material = new MeshStandardNodeMaterial({ roughness: 0.92, metalness: 0 }) + material.colorNode = rockColorNode(look) + cache.set(key, material) + return material +} diff --git a/packages/nodes/src/site/__fixtures__/terrain-break-ground-golden.json b/packages/nodes/src/site/__fixtures__/terrain-break-ground-golden.json new file mode 100644 index 0000000000..b90f9b56f2 --- /dev/null +++ b/packages/nodes/src/site/__fixtures__/terrain-break-ground-golden.json @@ -0,0 +1,192 @@ +{ + "one straight break, oblique": [ + { + "key": "terrain-tile_x0z0", + "positions": "41e8df88eaed9f525cdc5533", + "normals": "4fd119f629e42a42031a8d09", + "uvs": "792a7e77e74816a6b9498dd2", + "indices": "8aa90e0785be14147634c1d9", + "verts": 25842, + "tris": 8614 + }, + { + "key": "terrain-tile_x1z0", + "positions": "59cfda4d812bf7e5a793b131", + "normals": "011ee8ff5e8b3be020d3dc0d", + "uvs": "0986ce0677d0c5600db76f8a", + "indices": "fc0be75c3434331d153fe1e2", + "verts": 24648, + "tris": 8216 + }, + { + "key": "terrain-tile_x0z1", + "positions": "99f8276f189cb8bcbc980c7b", + "normals": "920159a71f627aed492c62b1", + "uvs": "da305989fcf7bfe082a7c893", + "indices": "694176534b129f6c3205ff03", + "verts": 24576, + "tris": 8192 + }, + { + "key": "terrain-tile_x1z1", + "positions": "e3a37305f400cefa1b7f69bc", + "normals": "6f351cdac47202e3ab69e8df", + "uvs": "4287618ba3292097af312fff", + "indices": "641c12701dcbbe0d2ab316ff", + "verts": 25782, + "tris": 8594 + } + ], + "one closed ring across the tile seams": [ + { + "key": "terrain-tile_x0z0", + "positions": "09239d3306ccededf91c804d", + "normals": "da124607ac637ae66966c4ad", + "uvs": "801476e6bac6ce11aaa89718", + "indices": "49d3adc2877a46a04f5099da", + "verts": 26976, + "tris": 8992 + }, + { + "key": "terrain-tile_x1z0", + "positions": "fa2558f7e74373bc31f118b5", + "normals": "deea167f4a4ff0009707bd7c", + "uvs": "673d5fb6b93786084e75aaff", + "indices": "b1e8409420bbcd236a3f9982", + "verts": 24810, + "tris": 8270 + }, + { + "key": "terrain-tile_x0z1", + "positions": "a7482f046dee196acbf78bd0", + "normals": "76ede2ddbdb957f4b942a553", + "uvs": "2ebd1e54bf43997487a451ac", + "indices": "f0165fe62d6ad13e6cece4fe", + "verts": 25278, + "tris": 8426 + }, + { + "key": "terrain-tile_x1z1", + "positions": "98378ad6edd9a67824d6e9e6", + "normals": "825806339c6ae863d152b8f9", + "uvs": "b192d502c0a35fa2a9c91bc7", + "indices": "9c3b21d2150bdf4bda6be117", + "verts": 25860, + "tris": 8620 + } + ], + "a ring standing off a straight break (a T that does not touch)": [ + { + "key": "terrain-tile_x0z0", + "positions": "2cfec7ff4de24a6364f4ef4d", + "normals": "05d4eae544c90feb7823c1f5", + "uvs": "3a3faf7d7ce0201515bc3b11", + "indices": "6125e9bb625af9816d65e06f", + "verts": 25344, + "tris": 8448 + }, + { + "key": "terrain-tile_x1z0", + "positions": "0760174d88475f3598da5edd", + "normals": "aa8d91b3ecdb81ced41a5ef7", + "uvs": "55de7e8ba55b2997677ce5f6", + "indices": "17a4cf18e286f0da3b526cf1", + "verts": 25512, + "tris": 8504 + }, + { + "key": "terrain-tile_x0z1", + "positions": "4535f4dc395568ef64588c45", + "normals": "bb6749f2b371bb2b5a1a5014", + "uvs": "e256b33f2872a9a69b9d02c2", + "indices": "433684d9c42a3b8ecbd97b96", + "verts": 26112, + "tris": 8704 + }, + { + "key": "terrain-tile_x1z1", + "positions": "a0edab13fb1494ee21d5215a", + "normals": "0c719af97761b7b49c8a4973", + "uvs": "37d177778a9d5cf1fe17882d", + "indices": "e4147d86396f6cd2c44aae40", + "verts": 26280, + "tris": 8760 + } + ], + "a ring that ends inside one tile": [ + { + "key": "terrain-tile_x0z0", + "positions": "668947bcba8d9442e93e6087", + "normals": "0ae991a3c8ad8c185d2b5292", + "uvs": "c0dd6d2eed08c0edff854812", + "indices": "545f36a593d4ee759d8d7a5d", + "verts": 26040, + "tris": 8680 + }, + { + "key": "terrain-tile_x1z0", + "positions": "8c9ca93c2a6bf67b790d6490", + "normals": "557b914124951303bc30f8eb", + "uvs": "3f6404e628eddb3d5ebba680", + "indices": "694176534b129f6c3205ff03", + "verts": 24576, + "tris": 8192 + }, + { + "key": "terrain-tile_x0z1", + "positions": "03837451d378f054c8c676f8", + "normals": "4ceb0237a97322bad3646c1e", + "uvs": "80eda32d69f116637b7c15d8", + "indices": "142135763d3b5a2dba039edf", + "verts": 25314, + "tris": 8438 + }, + { + "key": "terrain-tile_x1z1", + "positions": "fa83d995072881ae0424ec1c", + "normals": "30e55fe623848f52fbe492a5", + "uvs": "bed638a637540de9d8e5fe71", + "indices": "42a2bad2706a03eb33141c48", + "verts": 26466, + "tris": 8822 + } + ], + "a straight break on the tile seam": [ + { + "key": "terrain-tile_x0z0", + "positions": "49d4f907b6382b26144b7631", + "normals": "ad60c6fe10adecc2970d5fa4", + "uvs": "50478b4ad3bca8e8b634172f", + "indices": "694176534b129f6c3205ff03", + "verts": 24576, + "tris": 8192 + }, + { + "key": "terrain-tile_x1z0", + "positions": "8e06be7a2cb5f04a90c5369f", + "normals": "e4ae504e929d9f437ef2ef8c", + "uvs": "3f6404e628eddb3d5ebba680", + "indices": "694176534b129f6c3205ff03", + "verts": 24576, + "tris": 8192 + }, + { + "key": "terrain-tile_x0z1", + "positions": "99f8276f189cb8bcbc980c7b", + "normals": "920159a71f627aed492c62b1", + "uvs": "da305989fcf7bfe082a7c893", + "indices": "694176534b129f6c3205ff03", + "verts": 24576, + "tris": 8192 + }, + { + "key": "terrain-tile_x1z1", + "positions": "bff26a48c0a658985d23d24b", + "normals": "e4ae504e929d9f437ef2ef8c", + "uvs": "f1855933b67abbe69d4af3d5", + "indices": "694176534b129f6c3205ff03", + "verts": 24576, + "tris": 8192 + } + ] +} diff --git a/packages/nodes/src/site/__fixtures__/terrain-break-ground-scenes.ts b/packages/nodes/src/site/__fixtures__/terrain-break-ground-scenes.ts new file mode 100644 index 0000000000..bdbc9e4cab --- /dev/null +++ b/packages/nodes/src/site/__fixtures__/terrain-break-ground-scenes.ts @@ -0,0 +1,151 @@ +import { + createTerrainField, + encodeTerrainField, + persistedTerrainFieldOf, + type TerrainField, + tileFieldOf, +} from '@pascal-app/core' +import { SiteNode, TerrainBreakNode, TerrainTileNode } from '@pascal-app/core/schema' + +type Point = [number, number] +type Break = { line: Point[]; left: number | 'ground'; right: number | 'ground' } + +/** Rolling ground with a fall, in whole centimetres: no plane, so a normal has something to say. */ +export const rollingGround = (x: number, z: number) => + Math.round((0.08 * x + 0.05 * z + 0.6 * Math.sin(x / 3) * Math.cos(z / 4)) * 100) / 100 + +function tile(ix: number, iz: number, ground: (x: number, z: number) => number) { + const field = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + for (let row = 0; row < 65; row++) + for (let col = 0; col < 65; col++) + field.heights[row * 65 + col] = Math.round(ground(ix * 32 + col * 0.5, iz * 32 + row * 0.5) * 100) + return TerrainTileNode.parse({ + id: `terrain-tile_x${ix + 1}z${iz + 1}`, + parentId: 'site_break_ground', + ix, + iz, + level: 0, + step: 0.01, + heights: encodeTerrainField(field).heights, + }) +} + +/** A `w` by `d` rectangle about (cx, cz), turned by `degrees`, counter-clockwise and closed. */ +export function turnedRing(cx: number, cz: number, w: number, d: number, degrees: number): Point[] { + const a = (degrees * Math.PI) / 180 + const ring = ( + [ + [-w / 2, -d / 2], + [w / 2, -d / 2], + [w / 2, d / 2], + [-w / 2, d / 2], + ] as Point[] + ).map( + ([x, z]): Point => [ + Math.round((cx + x * Math.cos(a) - z * Math.sin(a)) * 1000) / 1000, + Math.round((cz + x * Math.sin(a) + z * Math.cos(a)) * 1000) / 1000, + ], + ) + return [...ring, ring[0] as Point] +} + +export type BreakGroundScene = { + name: string + site: SiteNode + nodes: Record + field: TerrainField + /** The four tiles about the origin: [-1,-1], [0,-1], [-1,0], [0,0]. */ + grids: { key: string; grid: TerrainField }[] + breaks: TerrainBreakNode[] +} + +/** A 24 m lot on four tiles of rolling ground, with the given breaks. */ +export function breakGroundScene( + name: string, + shapes: Break[], + ground: (x: number, z: number) => number = rollingGround, +): BreakGroundScene { + const tiles = [ + [-1, -1], + [0, -1], + [-1, 0], + [0, 0], + ].map(([ix, iz]) => tile(ix as number, iz as number, ground)) + const breaks = shapes.map((shape, index) => + TerrainBreakNode.parse({ + id: `terrain-break_${name.replace(/[^a-z0-9]/g, '')}${index}`, + parentId: 'site_break_ground', + kind: 'retaining', + ...shape, + }), + ) + const site = SiteNode.parse({ + id: 'site_break_ground', + children: [...tiles, ...breaks].map((node) => node.id), + polygon: { + type: 'polygon', + points: [ + [-12, -12], + [12, -12], + [12, 12], + [-12, 12], + ], + }, + }) + const nodes = Object.fromEntries([site, ...tiles, ...breaks].map((node) => [node.id, node])) + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error(`No ground for ${name}`) + return { + name, + site, + nodes, + field, + breaks, + grids: tiles.map((node) => ({ key: node.id, grid: tileFieldOf(node) as TerrainField })), + } +} + +/** + * The shapes a break can take against the grid. Breaks may not touch or cross and an open break + * is one straight line across the whole site, so "a T" is a ring standing 0.3 m off a line (their + * two faces inside one cell) and "a break that ends inside a tile" is a ring wholly inside one. + */ +export const BREAK_GROUND_SHAPES: Record = { + 'one straight break, oblique': [ + { + line: [ + [-12, -9.3], + [12, 7.1], + ], + left: 'ground', + right: -0.5, + }, + ], + 'one closed ring across the tile seams': [ + { line: turnedRing(0.7, -0.4, 7, 4.5, 30), left: 1.2, right: 'ground' }, + ], + 'a ring standing off a straight break (a T that does not touch)': [ + { + line: [ + [-12, 2.2], + [12, 2.2], + ], + left: 2.5, + right: 'ground', + }, + { line: turnedRing(3.1, -0.65, 4, 5.1, 0), left: -0.8, right: 'ground' }, + ], + 'a ring that ends inside one tile': [ + { line: turnedRing(6.3, 5.8, 3, 2, 20), left: 0.9, right: 'ground' }, + ], + 'a straight break on the tile seam': [ + { + line: [ + [0, -12], + [0, 12], + ], + left: 'ground', + right: 0.8, + }, + ], +} diff --git a/packages/nodes/src/site/__fixtures__/terrain-lag-mesh-golden.json b/packages/nodes/src/site/__fixtures__/terrain-lag-mesh-golden.json new file mode 100644 index 0000000000..9226d09a5e --- /dev/null +++ b/packages/nodes/src/site/__fixtures__/terrain-lag-mesh-golden.json @@ -0,0 +1 @@ +{"three rings, ground outside":[{"id":"terrain-tile_0_0","positions":"32113758eca6ba8216073bfe","normals":"145d7f77804fdc9cbf8db3e2","indices":"1fced82ddbf9d35026908a48","verts":24840,"tris":8280},{"id":"terrain-tile_1_1","positions":"8e5ad115c508380cb80c5d4b","normals":"a745ccc8c5f6322e7df59c18","indices":"d46487efedff54d6dc3775da","verts":26412,"tris":8804},{"id":"terrain-tile_2_1","positions":"b26d1f4878bc01cb5834a671","normals":"5f1deb03851e60a24df470b6","indices":"6125e9bb625af9816d65e06f","verts":25344,"tris":8448}],"open break":[{"id":"terrain-tile_0_0","positions":"931be1eec572b3db690e6295","normals":"e4ae504e929d9f437ef2ef8c","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192},{"id":"terrain-tile_1_1","positions":"fe19ff9631979e00dae6bfc8","normals":"68bb0ee4059af7215f8bfb14","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192},{"id":"terrain-tile_2_1","positions":"4765e93106f81f69256da56a","normals":"3ff808f0ab8574fa841c41a7","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192}],"open break, ground on its left":[{"id":"terrain-tile_0_0","positions":"3ecd40134d68e17962052077","normals":"9c14d8032b3936c4d03dfe32","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192},{"id":"terrain-tile_1_1","positions":"ef971a9a1fb015a04286558f","normals":"ac90e5a3945b5029858eb765","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192},{"id":"terrain-tile_2_1","positions":"9566f0d72a2799dd4556972c","normals":"e4ae504e929d9f437ef2ef8c","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192}],"one ring, numeric both sides":[{"id":"terrain-tile_0_0","positions":"c24a1fbbf3485309c65e8c59","normals":"e4ae504e929d9f437ef2ef8c","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192},{"id":"terrain-tile_1_1","positions":"dcfc01e345ad3aeda2aff3d8","normals":"e4ae504e929d9f437ef2ef8c","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192},{"id":"terrain-tile_2_1","positions":"74a61892ebf628cd9114376a","normals":"e4ae504e929d9f437ef2ef8c","indices":"694176534b129f6c3205ff03","verts":24576,"tris":8192}],"legacy and a ring":[],"legacy, tiles and rings":[{"id":"terrain-tile_0_0","positions":"32113758eca6ba8216073bfe","normals":"145d7f77804fdc9cbf8db3e2","indices":"1fced82ddbf9d35026908a48","verts":24840,"tris":8280},{"id":"terrain-tile_1_1","positions":"308ca7943cfd15011c6b87e4","normals":"e2532c4328848d2042722aeb","indices":"d46487efedff54d6dc3775da","verts":26412,"tris":8804},{"id":"terrain-tile_2_1","positions":"b26d1f4878bc01cb5834a671","normals":"5f1deb03851e60a24df470b6","indices":"6125e9bb625af9816d65e06f","verts":25344,"tris":8448}]} \ No newline at end of file diff --git a/packages/nodes/src/site/ground-hole.test.tsx b/packages/nodes/src/site/ground-hole.test.tsx index 0c9f7320a5..03c4ad5229 100644 --- a/packages/nodes/src/site/ground-hole.test.tsx +++ b/packages/nodes/src/site/ground-hole.test.tsx @@ -1,5 +1,5 @@ import { afterEach, expect, test } from 'bun:test' -import { groundHoleOpenNode } from '@pascal-app/viewer' +import { groundHoleOpenNode, undergroundAmbianceNode } from '@pascal-app/viewer' import { groundHoleColorNode, groundHoleContains, @@ -9,6 +9,7 @@ import { HOLE_MARGIN, setGroundHoleEdge, setGroundHoleFootprints, + setSolidGroundMask, solidGroundMaskNode, } from './ground-hole' @@ -83,3 +84,32 @@ test('the mask, the rim and the shadow word build as TSL nodes', () => { expect(groundHoleColorNode('#4a5470')).toBeTruthy() expect(typeof groundHoleShadowNode()).toBe('function') }) + +test('a solid ground surface is masked by the dark mode only when the earth is implied under the ground', () => { + const reads = (root: unknown, wanted: unknown) => { + let found = false + ;(root as { traverse: (visit: (node: unknown) => void) => void }).traverse((node) => { + if (node === wanted) found = true + }) + return found + } + type Masked = { maskNode: unknown; maskShadowNode: unknown } + for (const hasBasement of [false, true]) { + // As it ships: the window's mask (and the hole's with a level below grade), nothing else, and + // no mask of its own for the shadow. What a break's face and the lot's ground both get. + const shipped: Masked = { maskNode: null, maskShadowNode: null } + setSolidGroundMask(shipped, hasBasement, false) + expect(reads(shipped.maskNode, undergroundAmbianceNode())).toBe(false) + expect(reads(shipped.maskNode, groundHoleOpenNode())).toBe(hasBasement) + expect(shipped.maskShadowNode).toBeNull() + + // Implied: the surface leaves with the dark mode, and still casts the shadow it cast. + const implied: Masked = { maskNode: null, maskShadowNode: null } + setSolidGroundMask(implied, hasBasement, true) + expect(reads(implied.maskNode, undergroundAmbianceNode())).toBe(true) + expect(reads(implied.maskNode, groundHoleOpenNode())).toBe(hasBasement) + expect(implied.maskShadowNode).not.toBeNull() + expect(reads(implied.maskShadowNode, undergroundAmbianceNode())).toBe(false) + expect(reads(implied.maskShadowNode, groundHoleOpenNode())).toBe(hasBasement) + } +}) diff --git a/packages/nodes/src/site/ground-hole.tsx b/packages/nodes/src/site/ground-hole.tsx index af69191249..a882119e18 100644 --- a/packages/nodes/src/site/ground-hole.tsx +++ b/packages/nodes/src/site/ground-hole.tsx @@ -31,6 +31,7 @@ import { import { Vector2 } from 'three/webgpu' import { GroundPit, setGroundPitEdge } from './ground-pit' import { buildPitWalls, type PitWalls } from './ground-pit-geometry' +import { groundDrawnToEyeNode } from './ground-veil' import { fractalNoise3 } from './hole-noise' import { EDGE_LOOKS, type EdgeLook } from './underground-edge' @@ -290,6 +291,28 @@ export function solidGroundMaskNode() { return groundWindowMaskNode().and(holePieces().inHole.not()) } +/** + * Gives a solid ground surface (the lot's ground, its skirt, the horizon disc, a break's face) the + * mask it draws with: out of the ground window and, where the scene has a level below grade, out + * of the hole. With the earth implied under the ground (`undergroundLook.ground`), the surface is + * also not drawn to an eye under it; its shadow still falls as it does in daylight, so what stands + * on the ground is lit the same. + */ +export function setSolidGroundMask( + material: object, + hasBasement: boolean, + impliedBelow: boolean, +): void { + const drawn = hasBasement ? solidGroundMaskNode() : groundWindowMaskNode() + const masked = material as { maskNode: unknown; maskShadowNode: unknown } + if (!impliedBelow) { + masked.maskNode = drawn + return + } + masked.maskNode = drawn.and(groundDrawnToEyeNode()) + masked.maskShadowNode = drawn +} + /** Whether a fragment is in the hole, a hand's width over: what the pit's floor is drawn in. */ export function groundHoleFloorNode() { return holePieces().floorInHole diff --git a/packages/nodes/src/site/ground-pit.test.tsx b/packages/nodes/src/site/ground-pit.test.tsx new file mode 100644 index 0000000000..8458f4fb6b --- /dev/null +++ b/packages/nodes/src/site/ground-pit.test.tsx @@ -0,0 +1,69 @@ +import { expect, test } from 'bun:test' +import { create } from '@react-three/test-renderer' +import type { Mesh, Object3D } from 'three' +import { float } from 'three/tsl' +import type { NodeMaterial } from 'three/webgpu' +import { GroundPit } from './ground-pit' +import { buildPitWalls } from './ground-pit-geometry' + +// The pit's walls hang from the ground, and the ground is not always the flat grade: on a slope +// each wall starts at its own height, and on a lot that stands above the datum every one of them +// starts above it. + +/** A flat grade no other number of the pit comes near, so a shader that reads it is found. */ +const FLAT_GRADE = 123.25 + +/** A round hole of 4 m radius in ground that climbs 0.3 m a metre, well over the datum. */ +const walls = buildPitWalls({ + originX: -8, + originZ: -8, + span: 16, + distanceAt: (x, z) => Math.hypot(x, z) - 3, + radiusAt: () => 1, + topAt: (x) => 6 + 0.3 * x, + radiusMin: 1, + radiusMax: 1, + cell: 0.5, +}) + +/** Every number a material's node reads as a uniform. */ +function uniformsRead(root: unknown): number[] { + const values: number[] = [] + ;(root as { traverse: (visit: (node: unknown) => void) => void }).traverse((node) => { + const uniform = node as { isUniformNode?: boolean; value?: unknown } + if (uniform.isUniformNode === true && typeof uniform.value === 'number') + values.push(uniform.value) + }) + return values +} + +test('a wall of the pit is measured from the ground it hangs from: only the floor travels from the flat grade', async () => { + expect(walls).not.toBeNull() + const renderer = await create( + , + ) + await renderer.advanceFrames(1, 0.05) + const parts = new Map() + ;(renderer.scene.instance as Object3D).traverse((object) => { + const part = object.userData.groundPit as string | undefined + if (part) parts.set(part, (object as Mesh).material as NodeMaterial) + }) + const wall = parts.get('walls')! + const floor = parts.get('floor')! + // The floor slides from the flat grade down (or up) to its place as the hole opens. + expect(uniformsRead(floor.positionNode)).toContain(FLAT_GRADE) + // A wall's shape and its section (the topsoil band, the line at grade) know nothing of it: on + // sloping ground, or on a lot above the datum, the band would be as deep as the flat grade is + // far, or cover the whole wall. + expect(uniformsRead(wall.positionNode)).not.toContain(FLAT_GRADE) + expect(uniformsRead(wall.colorNode)).not.toContain(FLAT_GRADE) + await renderer.unmount() +}) diff --git a/packages/nodes/src/site/ground-pit.tsx b/packages/nodes/src/site/ground-pit.tsx index beaeddb03e..7d1a7b371f 100644 --- a/packages/nodes/src/site/ground-pit.tsx +++ b/packages/nodes/src/site/ground-pit.tsx @@ -7,10 +7,12 @@ import { attribute, color, float, + min, mix, mx_noise_float, normalize, normalLocal, + positionGeometry, positionLocal, positionWorld, smoothstep, @@ -107,13 +109,17 @@ function wallMaterial(topsoil: string, foot: string) { const material = new MeshLambertNodeMaterial({ side: FrontSide }) const drop = attribute<'float'>('drop', 'float') const slide = drop.mul(pitEase()) - const drawnY = mix(positionLocal.y, pitDrawnFloorY.sub(FOOT_TUCK), slide) + // A wall hangs from the ground it starts at down to the pit's floor. Where that ground lies + // under the floor (a cut or a bank inside the hole's reach) there is no wall to hang: it stays + // at its top, without height, rather than standing up from the ground to the floor. + const footY = min(positionLocal.y, pitDrawnFloorY.sub(FOOT_TUCK)) + const drawnY = mix(positionLocal.y, footY, slide) // An earth cut is rough in depth: past the rim's own cut the wall is pushed sideways by a 3D // noise that changes with depth, so a wiggle of the rim does not run straight down as a fold. // Nothing at the rim (the top stays on the shader's cut) nor at the foot (it stays under the // floor's plate), both eased in over a few tenths of a metre. const belowRim = positionLocal.y.sub(drawnY) - const aboveFoot = drawnY.sub(pitDrawnFloorY.sub(FOOT_TUCK)) + const aboveFoot = drawnY.sub(footY) const rough = smoothstep(float(CRUMBLE_RIM), float(CRUMBLE_RIM * 5), belowRim).mul( smoothstep(float(0), float(CRUMBLE_FOOT), aboveFoot), ) @@ -149,8 +155,11 @@ function wallMaterial(topsoil: string, foot: string) { const strata = smoothstep(float(-0.06), float(0.06), mx_noise_float(sample)) const layers = mix(color(STRATA.dark), color(STRATA.light), strata) const toFoot = mix(layers, color(foot), drop.mul(0.6).mul(float(1).sub(pitSection))) - // The ground's own layer along the cut, its lower edge a noise threshold like the rim. - const depthBelowTop = drop.mul(pitTopY.sub(pitFloorY)).mul(pitEase()) + // The ground's own layer along the cut, its lower edge a noise threshold like the rim. Its depth + // is counted from the ground this wall hangs from (the vertex as stored, before it is slid + // down), not from the flat grade: on a slope, or on a lot that stands over the datum, the walls + // start at other heights, and the layer would be as thick as the flat grade is far from them. + const depthBelowTop = positionGeometry.y.sub(positionWorld.y) const edge = float(TOPSOIL_DEPTH).add( mx_noise_float(positionWorld.mul(vec3(1.3, 0, 1.3))).mul(0.12), ) diff --git a/packages/nodes/src/site/ground-veil.test.tsx b/packages/nodes/src/site/ground-veil.test.tsx index 5a8981fe7c..76abcbd59b 100644 --- a/packages/nodes/src/site/ground-veil.test.tsx +++ b/packages/nodes/src/site/ground-veil.test.tsx @@ -18,6 +18,7 @@ import { SCENE_LAYER, SITE_GROUND, setSurfaceRaycastLayers, + undergroundAmbianceNode, useViewer, } from '@pascal-app/viewer' import { act, create } from '@react-three/test-renderer' @@ -90,6 +91,15 @@ function readsHoleOpening(root: unknown) { const solidMasks = (root: Object3D) => ground(root, 'solid').map((surface) => (surface.material as MeshBasicNodeMaterial).maskNode) +/** True when the node graph under `root` reads the dark mode's factor. */ +function readsDarkMode(root: unknown) { + let reads = false + ;(root as { traverse: (visit: (child: unknown) => void) => void } | null)?.traverse((child) => { + if (child === undergroundAmbianceNode()) reads = true + }) + return reads +} + let previous: { viewer: ReturnType scene: ReturnType @@ -167,6 +177,68 @@ test.each([false, true])( }, ) +test('a sculpted site says where its ground is drawn past the property line; a flat one has one ground', async () => { + setNodes([]) + const sculpted = await create() + await sculpted.advanceFrames(1, 0.05) + const past = useViewer.getState().groundPastLot + // The horizon disc, under the base of the lot's block (a metre under its lowest ground), and + // the property line the sculpted ground is cut to. + expect(past?.lot).toEqual(lotPoints) + expect(past?.y).toBeLessThan(-1) + const disc = ground(sculpted.scene.instance as Object3D, 'solid').find( + (surface) => surface.userData.pascalExport === 'strip', + ) + expect(disc?.position.y).toBe(past?.y) + await sculpted.unmount() + expect(useViewer.getState().groundPastLot).toBeNull() + + const flat = await create() + await flat.advanceFrames(1, 0.05) + expect(useViewer.getState().groundPastLot).toBeNull() + await flat.unmount() +}) + +test.each([false, true])( + 'with the earth implied under the ground, no ground is drawn to an eye under it; off, the ground knows nothing of the dark mode (basement: %p)', + async (basement) => { + if (basement) withBasement() + else setNodes([]) + const renderer = await create() + const scene = renderer.scene.instance as Object3D + const shadowMasks = () => + ground(scene, 'solid').map( + (surface) => (surface.material as unknown as { maskShadowNode: unknown }).maskShadowNode, + ) + const veilOpacities = () => + ground(scene, 'veil').map( + (surface) => (surface.material as MeshBasicNodeMaterial).opacityNode, + ) + // As it ships: the block's surface, its skirt and the horizon disc are drawn whatever the eye + // does, and nothing in them reads the dark mode's factor. + expect(useViewer.getState().undergroundLook.ground).toBe('drawn') + expect(ground(scene, 'solid').length).toBeGreaterThanOrEqual(3) + expect(solidMasks(scene).some(readsDarkMode)).toBe(false) + expect(veilOpacities().some(readsDarkMode)).toBe(false) + expect(shadowMasks().every((mask) => mask == null)).toBe(true) + + await act(async () => useViewer.getState().setUndergroundLook({ ground: 'implied' })) + await renderer.advanceFrames(2, 0.05) + // Every solid surface (the horizon disc and the skirt with it) and every veil steps aside + // with the dark mode; the shadow each one casts does not. + expect(solidMasks(scene).length).toBeGreaterThanOrEqual(3) + expect(solidMasks(scene).every(readsDarkMode)).toBe(true) + expect(veilOpacities().length).toBeGreaterThan(0) + expect(veilOpacities().every(readsDarkMode)).toBe(true) + expect(shadowMasks().every((mask) => mask != null && !readsDarkMode(mask))).toBe(true) + + await act(async () => useViewer.getState().setUndergroundLook({ ground: 'drawn' })) + await renderer.advanceFrames(2, 0.05) + expect(solidMasks(scene).some(readsDarkMode)).toBe(false) + await renderer.unmount() + }, +) + test.each([ ['the person keeps the ground Solid', { groundMode: 'solid' }], ['the walkthrough walks', { walkthroughMode: true }], diff --git a/packages/nodes/src/site/ground-veil.tsx b/packages/nodes/src/site/ground-veil.tsx index 6d5bcb88f4..d7495d97f7 100644 --- a/packages/nodes/src/site/ground-veil.tsx +++ b/packages/nodes/src/site/ground-veil.tsx @@ -2,6 +2,7 @@ import { groundWindowEnabledNode, inGroundWindowNode, SITE_GROUND, + undergroundAmbianceNode, useViewer, } from '@pascal-app/viewer' import { type BufferGeometry, DoubleSide, type Material } from 'three' @@ -17,6 +18,20 @@ import { insideLotNode } from './lot-mask' /** Presentation-only meshes are never picked: clicks fall through to what lies under them. */ export const noopRaycast = () => {} +/** How far the dark mode has to be in before the implied ground is gone: the middle of the crossing. */ +const GROUND_GONE_AT = 0.5 + +/** + * Whether the ground is drawn to this eye, for the look that implies the earth under the ground + * (`undergroundLook.ground: 'implied'`): yes until the eye is under it, the dark mode's own factor + * past its middle. A flat lot's ground is gone from below as it is (it is seen from one side); a + * sculpted lot's block, its skirt, the disc under its base and the veil are not, and this takes + * them away the same. Zero on Solid, in the walkthrough and in a capture, as the factor is. + */ +export function groundDrawnToEyeNode(): Node<'bool'> { + return undergroundAmbianceNode().lessThan(GROUND_GONE_AT) as unknown as Node<'bool'> +} + /** How much of the ground shows as a veil: enough to read where grade is, and no more. */ const VEIL_OPACITY = 0.1 @@ -28,7 +43,7 @@ type Point = readonly [number, number] * colour, or the screen-space ink would outline the whole sheet. `coverage` (0 to 1) is how much * of the ground this sheet draws. */ -function veilMaterial(groundColor: string, coverage: Node<'float'>) { +function veilMaterial(groundColor: string, coverage: Node<'float'>, impliedBelow: boolean) { const material = new MeshBasicNodeMaterial({ transparent: true, depthWrite: false, @@ -38,11 +53,12 @@ function veilMaterial(groundColor: string, coverage: Node<'float'>) { // Wholesale, the veil is the whole ground at `VEIL_OPACITY`. While the ground window is open // (the hillside in the way, not a floor under it), only the ground in the window veils — // at the same faintness — and the rest of this sheet draws nothing over the solid ground. - material.opacityNode = select( + const opacity = select( groundWindowEnabledNode(), select(inGroundWindowNode(), float(VEIL_OPACITY), float(0)), coverage.mul(VEIL_OPACITY), ) + material.opacityNode = impliedBelow ? select(groundDrawnToEyeNode(), opacity, float(0)) : opacity // The plain field too: Follow's sight reads it, not the node, to tell what it sees through. material.opacity = VEIL_OPACITY material.mrtNode = mrt({ output, diffuseColor: vec4(0), normal: vec4(0) }) @@ -50,8 +66,8 @@ function veilMaterial(groundColor: string, coverage: Node<'float'>) { } /** The veil of the lot's own ground: its fill, or its sculpted terrain. */ -export function groundVeilMaterial(groundColor: string) { - return veilMaterial(groundColor, float(1)) +export function groundVeilMaterial(groundColor: string, impliedBelow = false) { + return veilMaterial(groundColor, float(1), impliedBelow) } /** @@ -63,11 +79,12 @@ export function horizonVeilMaterial( groundColor: string, lot: ReadonlyArray, bounds: { cx: number; cz: number; radius: number }, + impliedBelow = false, ) { const distance = positionWorld.xz.sub(vec2(bounds.cx, bounds.cz)).length() const fade = float(1).sub(smoothstep(float(bounds.radius), float(bounds.radius * 2), distance)) const outsideLot = insideLotNode(lot, positionWorld.xz).not() - return veilMaterial(groundColor, select(outsideLot, fade, float(0))) + return veilMaterial(groundColor, select(outsideLot, fade, float(0)), impliedBelow) } /** diff --git a/packages/nodes/src/site/lot-mask.test.ts b/packages/nodes/src/site/lot-mask.test.ts new file mode 100644 index 0000000000..b5e785b5dc --- /dev/null +++ b/packages/nodes/src/site/lot-mask.test.ts @@ -0,0 +1,41 @@ +import { expect, test } from 'bun:test' +import { float } from 'three/tsl' +import { MeshBasicNodeMaterial } from 'three/webgpu' +import { lotMaskedMaterial } from './lot-mask' + +const LOT = [ + [-15, -15], + [15, -15], + [15, 15], + [-15, 15], +] as const + +function reads(root: unknown, wanted: unknown) { + let found = false + ;(root as { traverse: (visit: (node: unknown) => void) => void }).traverse((node) => { + if (node === wanted) found = true + }) + return found +} + +type Masked = { maskNode: unknown; maskShadowNode: unknown } + +test('the ground cut to the lot keeps the mask it carries, and its shadow mask stops at the line too', () => { + const drawn = float(1).greaterThan(0) + const shadow = float(2).greaterThan(0) + const ground = new MeshBasicNodeMaterial() + ;(ground as unknown as Masked).maskNode = drawn + // A ground with no shadow mask of its own (as it ships) gets none: its mask serves the shadow. + const plain = lotMaskedMaterial(ground, LOT) as unknown as Masked + expect(reads(plain.maskNode, drawn)).toBe(true) + expect(plain.maskNode).not.toBe(drawn) + expect(plain.maskShadowNode).toBeNull() + + // A ground that casts its shadow where it is not drawn carries a shadow mask: the tiles reach + // past the lot, and their shadow must not. + ;(ground as unknown as Masked).maskShadowNode = shadow + const implied = lotMaskedMaterial(ground, LOT) as unknown as Masked + expect(reads(implied.maskShadowNode, shadow)).toBe(true) + expect(implied.maskShadowNode).not.toBe(shadow) + expect(reads(implied.maskShadowNode, drawn)).toBe(false) +}) diff --git a/packages/nodes/src/site/lot-mask.ts b/packages/nodes/src/site/lot-mask.ts index d8adeb9ca2..2862ce3cb6 100644 --- a/packages/nodes/src/site/lot-mask.ts +++ b/packages/nodes/src/site/lot-mask.ts @@ -40,5 +40,9 @@ export function lotMaskedMaterial(material: Material, polygon: ReadonlyArray).and(inside) : inside + // A ground that keeps its shadow where it is not drawn (the earth implied under the ground) + // carries its own shadow mask: that one stops at the property line as well. + if (masked.maskShadowNode) + masked.maskShadowNode = (masked.maskShadowNode as Node<'bool'>).and(inside) return masked as unknown as Material } diff --git a/packages/nodes/src/site/ramp-cut-faces.ts b/packages/nodes/src/site/ramp-cut-faces.ts new file mode 100644 index 0000000000..402201414c --- /dev/null +++ b/packages/nodes/src/site/ramp-cut-faces.ts @@ -0,0 +1,168 @@ +import { heightAt, type TerrainField } from '@pascal-app/core' +import type { RampGroundCut } from './ramp-ground-holes' +import type { TerrainHoleBoundary } from './terrain-holes' + +export type RampCutFaceBuffers = { + positions: Float32Array + normals: Float32Array + uvs: Float32Array + indices: Uint32Array +} + +/** A rim edge is the ground's own cut edge when its midpoint lies on the cut's ring (to the clipper's 0.1 mm lattice). */ +const ON_RING_M = 2e-4 + +function ringDistance(ring: readonly (readonly [number, number])[], x: number, z: number): number { + let nearest = Number.POSITIVE_INFINITY + for (let i = 0; i < ring.length; i++) { + const [x0, z0] = ring[i] as readonly [number, number] + const [x1, z1] = ring[(i + 1) % ring.length] as readonly [number, number] + const dx = x1 - x0 + const dz = z1 - z0 + const length2 = dx * dx + dz * dz + const t = + length2 === 0 ? 0 : Math.max(0, Math.min(1, ((x - x0) * dx + (z - z0) * dz) / length2)) + nearest = Math.min(nearest, Math.hypot(x - x0 - t * dx, z - z0 - t * dz)) + } + return nearest +} + +type End = { x: number; z: number; ground: number; top: number; bottom: number } + +/** + * The soil face that closes a ground cut against the roadway beside it. + * + * Where the ground stands above the roadway's side (its wall top, or the deck where there is no + * wall) the face runs from that side up to the ground; where the ground lies below the deck's + * underside it runs from the ground up to the underside. Between the two the roadway's own side + * meets the ground and there is nothing to close. The face is built on the ground's own cut edge, + * vertex for vertex, so it closes against the ground without a gap. + */ +export function rampCutFaces( + boundary: TerrainHoleBoundary, + cuts: readonly RampGroundCut[], + field: TerrainField, +): RampCutFaceBuffers | null { + if (!cuts.length || !boundary.rim.length) return null + const { points } = boundary + const positions: number[] = [] + const normals: number[] = [] + const uvs: number[] = [] + const indices: number[] = [] + + // One piece of face on the rim edge from `from` to `to`: `high` and `low` are each end's + // upper and lower heights, kept only where the upper is above the lower. + const piece = ( + from: End, + to: End, + high: (end: End) => number, + low: (end: End) => number, + normal: [number, number], + ) => { + const dA = high(from) - low(from) + const dB = high(to) - low(to) + if (dA <= 0 && dB <= 0) return + const at = (t: number) => { + const x = from.x + (to.x - from.x) * t + const z = from.z + (to.z - from.z) * t + const h = high(from) + (high(to) - high(from)) * t + const l = low(from) + (low(to) - low(from)) * t + return { x, z, h, l } + } + // The vertices of the piece, in order along the edge: the top edge, then back along the bottom. + let corners: { x: number; z: number; y: number }[] + if (dA > 0 && dB > 0) { + const a = at(0) + const b = at(1) + corners = [ + { x: a.x, z: a.z, y: a.h }, + { x: b.x, z: b.z, y: b.h }, + { x: b.x, z: b.z, y: b.l }, + { x: a.x, z: a.z, y: a.l }, + ] + } else { + // The face closes to nothing where upper and lower cross. + const t = dA / (dA - dB) + const cross = at(t) + const end = dA > 0 ? at(0) : at(1) + corners = [ + { x: end.x, z: end.z, y: end.h }, + { x: cross.x, z: cross.z, y: cross.h }, + { x: end.x, z: end.z, y: end.l }, + ] + } + const along = (x: number, z: number) => x * -normal[1] + z * normal[0] + const base = positions.length / 3 + for (const corner of corners) { + positions.push(corner.x, corner.y, corner.z) + normals.push(normal[0], 0, normal[1]) + uvs.push(along(corner.x, corner.z), corner.y) + } + // Wound so the face looks toward the roadway, the way its normal points. + const first = corners[0] as { x: number; z: number; y: number } + const second = corners[1] as { x: number; z: number; y: number } + const last = corners[corners.length - 1] as { x: number; z: number; y: number } + const ux = second.x - first.x + const uy = second.y - first.y + const uz = second.z - first.z + const vx = last.x - first.x + const vy = last.y - first.y + const vz = last.z - first.z + const facing = (uy * vz - uz * vy) * normal[0] + (ux * vy - uy * vx) * normal[1] + const order = facing >= 0 ? [0, 1, 2] : [0, 2, 1] + for (let i = 1; i < corners.length - 1; i++) { + const triangle = [0, i, i + 1] + for (const k of order) indices.push(base + (triangle[k] as number)) + } + } + + for (const { a, b } of boundary.rim) { + const [ax, az] = points[a] as [number, number] + const [bx, bz] = points[b] as [number, number] + const length = Math.hypot(bx - ax, bz - az) + if (length < 1e-9) continue + const mx = (ax + bx) / 2 + const mz = (az + bz) / 2 + const cut = cuts.find((candidate) => ringDistance(candidate.ring, mx, mz) <= ON_RING_M) + if (!cut) continue + const [sa, sb] = [cut.structureAt(ax, az), cut.structureAt(bx, bz)] + if (!sa || !sb) continue + const from: End = { + x: ax, + z: az, + ground: heightAt(field, ax, az), + top: sa.top, + bottom: sa.bottom, + } + const to: End = { + x: bx, + z: bz, + ground: heightAt(field, bx, bz), + top: sb.top, + bottom: sb.bottom, + } + // The ground is on this edge's left, so the roadway is on its right: (dz, -dx). + const normal: [number, number] = [(bz - az) / length, -(bx - ax) / length] + piece( + from, + to, + (end) => end.ground, + (end) => end.top, + normal, + ) + piece( + from, + to, + (end) => end.bottom, + (end) => end.ground, + normal, + ) + } + if (!indices.length) return null + return { + positions: Float32Array.from(positions), + normals: Float32Array.from(normals), + uvs: Float32Array.from(uvs), + indices: Uint32Array.from(indices), + } +} diff --git a/packages/nodes/src/site/ramp-ground-holes.ts b/packages/nodes/src/site/ramp-ground-holes.ts new file mode 100644 index 0000000000..eb56b2e01d --- /dev/null +++ b/packages/nodes/src/site/ramp-ground-holes.ts @@ -0,0 +1,84 @@ +import { + type AnyNode, + type RampNode, + type Ring, + rampHeightAt, + rampOffsetPoint, + rampProjectPoint, + rampStations, + rampStepForSag, +} from '@pascal-app/core' +import { isAgentRefusal } from '@pascal-app/core/agent-tools' + +/** How far the clipped edge may lie off the corridor's true edge, metres. */ +const EDGE_SAG_M = 0.005 + +/** The roadway's structure where it meets the ground along a cut's rim, at one rim point. */ +export type RampRimStructure = { + /** The highest the roadway's own side stands: the wall's top, or the deck without a wall. */ + top: number + /** The underside of the deck. */ + bottom: number +} + +/** + * A graded ramp's footprint on the ground: the ring its roadway replaces, and what stands at + * that ring, so the ground's cut edge can be closed against the roadway. + */ +export type RampGroundCut = { + ramp: RampNode + ring: Ring + structureAt: (x: number, z: number) => RampRimStructure | null +} + +function structureOf(ramp: RampNode) { + return (x: number, z: number): RampRimStructure | null => { + try { + const { distance } = rampProjectPoint(ramp, [x, z]) + const deck = rampHeightAt(ramp, distance) + return { + top: deck + (ramp.retainingHeight > 0 ? ramp.retainingHeight : 0), + bottom: deck - ramp.thickness, + } + } catch (error) { + if (isAgentRefusal(error)) return null + throw error + } + } +} + +export function getRampGroundCuts(nodes: Record, siteId: string): RampGroundCut[] { + return Object.values(nodes).flatMap((node) => { + if ( + node.type !== 'ramp' || + node.parentId !== siteId || + node.visible === false || + node.terrainMode !== 'cut-fill' + ) + return [] + + try { + // Finer than the default on a tight arc, so a chord of the clipped edge stays within + // `EDGE_SAG_M` of the true curve however tightly the road turns. + const stations = rampStations(node, rampStepForSag(node, EDGE_SAG_M)) + return [ + { + ramp: node, + ring: [ + ...stations.map((station) => rampOffsetPoint(station, node.width / 2)), + ...[...stations].reverse().map((station) => rampOffsetPoint(station, -node.width / 2)), + ], + structureAt: structureOf(node), + }, + ] + } catch (error) { + // A refused legacy ramp must not take down the Site; coherence reports its geometry. + if (isAgentRefusal(error)) return [] + throw error + } + }) +} + +export function getRampGroundHoles(nodes: Record, siteId: string): Ring[] { + return getRampGroundCuts(nodes, siteId).map((cut) => cut.ring) +} diff --git a/packages/nodes/src/site/renderer.tsx b/packages/nodes/src/site/renderer.tsx index 2d22f0dd43..af05bf4fb1 100644 --- a/packages/nodes/src/site/renderer.tsx +++ b/packages/nodes/src/site/renderer.tsx @@ -7,16 +7,22 @@ import { coveredBelowGradeFootprints, groundPitFloorY, intersection, + persistedTerrainFieldOf, + type RampNode, + rampsGradingOf, type SiteNode, sightTriangle, siteFrontEdge, siteSetbackEnvelope, streetCorners, surfaceHeightAt, + type TerrainBreakNode, type TerrainField, + type TerrainTileNode, + terrainBreaksOf, terrainContours, - terrainFieldOf, terrainOverFloors, + terrainTilesOf, union, unionPolygons, useLiveNodeOverrides, @@ -29,7 +35,6 @@ import { backdropGradient, createDaylightGroundMaterial, DAYLIGHT_PARCEL, - groundWindowMaskNode, isDaylightAtmosphere, NodeRenderer, SITE_GROUND, @@ -65,7 +70,7 @@ import { GroundHole, groundHoleColorNode, groundHoleShadowNode, - solidGroundMaskNode, + setSolidGroundMask, } from './ground-hole' import { GroundVeil, groundVeilMaterial, horizonVeilMaterial, noopRaycast } from './ground-veil' import { GroundWindowSystem } from './ground-window-system' @@ -75,6 +80,7 @@ import { SETBACK_LINE_PATTERN, updateRibbonHeights, } from './line-ribbon' +import { getRampGroundCuts, getRampGroundHoles, type RampGroundCut } from './ramp-ground-holes' import { getRecessedSlabGroundHoles } from './recessed-slab-ground-holes' import { buildDrapedPolyline, @@ -83,6 +89,9 @@ import { updateDrapedHeights, } from './terrain-drape' import { HORIZON_PLANE_Y, terrainBlockBase } from './terrain-geometry' +import { needsTerrainContinuation } from './terrain-ground' +import { TerrainGroundRenderer } from './terrain-ground-renderer' +import { TerrainGroundContext } from './terrain-ground-surface' import { TerrainRenderer } from './terrain-renderer' const Y_OFFSET = 0.01 @@ -211,19 +220,95 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { (state) => (state.overrides.get(node.id)?.polygon as SiteNode['polygon'] | undefined) ?? null, ) const polygonPoints = livePolygon?.points ?? node.polygon?.points + const renderSite = useMemo( + () => (livePolygon ? { ...node, polygon: livePolygon } : node), + [node, livePolygon], + ) + const tilesCache = useRef([]) + const tiles = useScene((state) => { + const next = terrainTilesOf(node, state.nodes) + const previous = tilesCache.current + if (next.length === previous.length && next.every((tile, index) => tile === previous[index])) { + return previous + } + tilesCache.current = next + return next + }) + const breaksCache = useRef([]) + const breaks = useScene((state) => { + const next = terrainBreaksOf(node, state.nodes) + const previous = breaksCache.current + if (next.length === previous.length && next.every((edge, index) => edge === previous[index])) { + return previous + } + breaksCache.current = next + return next + }) + + // The ramps whose grading the ground carries: beside their corridor the ground is the natural + // ground, which only the ramps' receipts can say. + const gradedRampsCache = useRef([]) + const gradedRamps = useScene((state) => { + const next = rampsGradingOf(node, state.nodes) + const previous = gradedRampsCache.current + if (next.length === previous.length && next.every((ramp, index) => ramp === previous[index])) { + return previous + } + gradedRampsCache.current = next + return next + }) + // What stands along each cut's edge, kept while the ramps are the same objects. + const rampCutsCache = useRef<{ ramps: RampNode[]; cuts: RampGroundCut[] }>({ + ramps: [], + cuts: [], + }) + const rampCuts = useScene((state) => { + const ramps = Object.values(state.nodes).filter( + (entry): entry is RampNode => + entry.type === 'ramp' && + entry.parentId === node.id && + entry.visible !== false && + entry.terrainMode === 'cut-fill', + ) + const previous = rampCutsCache.current + if ( + ramps.length === previous.ramps.length && + ramps.every((ramp, index) => ramp === previous.ramps[index]) + ) + return previous.cuts + rampCutsCache.current = { ramps, cuts: getRampGroundCuts(state.nodes, node.id) } + return rampCutsCache.current.cuts + }) // Persisted terrain only. A stroke is applied imperatively further down, for the - // same reason `TerrainRenderer` does it: a dab must not re-render this subtree. + // same reason `TerrainGroundSurface` does it: a dab must not re-render this subtree. const persistedField = useMemo( - () => terrainFieldOf({ id: node.id, terrain: node.terrain }), - [node.id, node.terrain], + () => + persistedTerrainFieldOf( + renderSite, + Object.fromEntries( + [renderSite, ...tiles, ...breaks, ...gradedRamps].map((entry) => [entry.id, entry]), + ), + ), + [renderSite, tiles, breaks, gradedRamps], ) // The terrain *grid* — mounting, resizing, or re-origining it. `hasTerrain` // catches the first dab on a site that had no terrain at all, which is the one // case where a stroke legitimately changes the grid and everything keyed on it // (the horizon punch, the boundary subdivision) has to rebuild. - const hasTerrain = useLiveTerrain((state) => state.strokes.has(node.id)) + const hasTerrain = useLiveTerrain( + (state) => state.strokes.has(node.id) || state.remoteStrokes.has(node.id), + ) + const compositeGround = useMemo( + () => + hasTerrain || tiles.length > 0 || breaks.length > 0 || needsTerrainContinuation(renderSite), + [hasTerrain, tiles, breaks, renderSite], + ) + const presentationField = useMemo( + () => persistedField ?? useLiveTerrain.getState().fieldOf(node.id) ?? null, + [persistedField, hasTerrain, node.id], + ) const terrainGrid = hasTerrain ? (useLiveTerrain.getState().fieldOf(node.id) ?? persistedField) : persistedField @@ -258,6 +343,8 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { ) const belowGrade = useViewer((state) => state.belowGrade) const groundMode = useViewer((state) => state.groundMode) + // The look that implies the earth under the ground: off, the materials are built as they were. + const impliedBelow = useViewer((state) => state.undergroundLook.ground === 'implied') const buriedCache = useRef<{ all: [number, number][][] shown: [number, number][][] @@ -316,15 +403,13 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { // The ground window cuts the solid ground where it stands in the eye's way (viewer // lib/ground-window), and the hole opens over a level below grade (ground-hole.tsx), its // edge a noise threshold with a thin slate rim; with both closed the mask passes everywhere. + setSolidGroundMask(material, hasBasement, impliedBelow) if (hasBasement) { - ;(material as unknown as { maskNode: unknown }).maskNode = solidGroundMaskNode() material.colorNode = groundHoleColorNode(UNDERGROUND_RIM) material.receivedShadowNode = groundHoleShadowNode() - } else { - ;(material as unknown as { maskNode: unknown }).maskNode = groundWindowMaskNode() } return material - }, [bgColor, daylight, hasBasement, solid]) + }, [bgColor, daylight, hasBasement, impliedBelow, solid]) // Presentation horizon: a large ground disc under the lot, fading into the // active fog radiance (or the theme backdrop when there is no atmosphere) so @@ -336,12 +421,8 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { material.polygonOffset = true material.polygonOffsetFactor = 2 material.polygonOffsetUnits = 2 - if (hasBasement) { - ;(material as unknown as { maskNode: unknown }).maskNode = solidGroundMaskNode() - material.receivedShadowNode = groundHoleShadowNode() - } else { - ;(material as unknown as { maskNode: unknown }).maskNode = groundWindowMaskNode() - } + setSolidGroundMask(material, hasBasement, impliedBelow) + if (hasBasement) material.receivedShadowNode = groundHoleShadowNode() return material } const material = new MeshLambertNodeMaterial({ color: bgColor }) @@ -389,17 +470,14 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { material.polygonOffset = true material.polygonOffsetFactor = 2 material.polygonOffsetUnits = 2 - if (hasBasement) { - ;(material as unknown as { maskNode: unknown }).maskNode = solidGroundMaskNode() - material.receivedShadowNode = groundHoleShadowNode() - } else { - ;(material as unknown as { maskNode: unknown }).maskNode = groundWindowMaskNode() - } + setSolidGroundMask(material, hasBasement, impliedBelow) + if (hasBasement) material.receivedShadowNode = groundHoleShadowNode() return material }, [ solid, daylight, hasBasement, + impliedBelow, atmosphere, bgColor, backgroundColor, @@ -412,21 +490,27 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { ]) // Over a level below grade the ground is drawn as a veil (ground-veil.tsx). - const groundVeil = useMemo(() => groundVeilMaterial(bgColor), [bgColor]) + const groundVeil = useMemo( + () => groundVeilMaterial(bgColor, impliedBelow), + [bgColor, impliedBelow], + ) useEffect(() => () => groundVeil.dispose(), [groundVeil]) const horizonVeil = useMemo( () => fadeBounds && polygonPoints && !groundReplaced - ? horizonVeilMaterial(bgColor, polygonPoints, fadeBounds) + ? horizonVeilMaterial(bgColor, polygonPoints, fadeBounds, impliedBelow) : null, - [bgColor, fadeBounds, polygonPoints, groundReplaced], + [bgColor, fadeBounds, polygonPoints, groundReplaced, impliedBelow], ) useEffect(() => () => horizonVeil?.dispose(), [horizonVeil]) // Cache computed polygons to keep the selector stable across unrelated store updates. const slabPolygonsCache = useRef<[number, number][][]>([]) const slabPolygons = useScene((state: S) => { - const next = getRecessedSlabGroundHoles(state.nodes) + const next = [ + ...getRecessedSlabGroundHoles(state.nodes), + ...getRampGroundHoles(state.nodes, node.id), + ] const prev = slabPolygonsCache.current if (polygonsMatch(next, prev)) return prev @@ -507,12 +591,8 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { // Boundary line geometry, subdivided against the terrain grid when there is one. // - // Keyed on `terrainKey`, not on the field: the crease set depends on the grid - // (origin/spacing/extent) and not on the heights, so a sculpt stroke — which - // produces a new field object every dab — must not rebuild this. Heights are - // rewritten in place by the subscription below. - // - // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the grid, not the field — see above. + // Commits rebuild against the new authority. Live dabs only rewrite heights + // through the subscription below, without rebuilding the crease set. const boundary = useMemo(() => { if (!polygonPoints || polygonPoints.length < 2) return null // The live field, not the persisted one: mounting mid-stroke (the very first @@ -520,7 +600,7 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { // ground actually on screen. const field = useLiveTerrain.getState().fieldOf(node.id) ?? persistedField return createBoundaryLineGeometry(polygonPoints, field) - }, [polygonPoints, terrainKey, node.id]) + }, [polygonPoints, terrainKey, node.id, persistedField]) useEffect(() => () => boundary?.geometry.dispose(), [boundary]) const lineGeometry = boundary?.geometry ?? null @@ -582,6 +662,7 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { node.northRotation, terrainKey, node.id, + persistedField, ]) useEffect( () => () => { @@ -608,14 +689,14 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { return useLiveTerrain.subscribe((state) => { const current = boundaryRef.current if (!current) return - const stroke = state.strokes.get(node.id) + const stroke = state.strokes.get(node.id) ?? state.remoteStrokes.get(node.id) if (!stroke) { // The stroke ended. Its heights are now the node's, and the commit // re-rendered this subtree with them — but a *cancelled* stroke (Escape) // commits nothing, so the ring has to be put back explicitly. if (lastPatch) { lastPatch = null - const field = terrainFieldOf({ id: node.id, terrain: node.terrain }) + const field = persistedField updateDrapedHeights(current.ring, field, Y_OFFSET) markPositionsDirty(current.geometry) redrapeRibbons(ribbonsRef.current, field) @@ -629,7 +710,7 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { // the property and setback ribbons follow the same dab redrapeRibbons(ribbonsRef.current, stroke.field) }) - }, [node.id, node.terrain]) + }, [node.id, persistedField]) // The CONTOUR LINES on the ground (toggleable in 3D, drawn as faint, // translucent near-black lines): the site's surveyed lines (the dossier's 3DEP set) at the @@ -691,6 +772,40 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { useEffect(() => () => groundGeometry?.dispose(), [groundGeometry]) const handlers = useNodeEvents(node, 'site') + // `showGround` hides both ground and horizon when authored geometry supplies them, unless a level + // below grade is shown: the level display hides that geometry then, and the ground stands in. + // The composite terrain (patches, tiles, skirt) reads the same word through the presentation. + const showGround = siteGroundShown(node, { belowGrade }) + const groundPresentation = useMemo( + () => + presentationField + ? { + siteId: node.id, + field: presentationField, + material: groundMaterial, + veil: groundVeil, + holes, + cuts: rampCuts, + polygon: polygonPoints, + visible: node.visible !== false && showGround, + showSkirt: !groundReplaced, + tiles, + } + : null, + [ + presentationField, + node.id, + node.visible, + showGround, + groundMaterial, + groundVeil, + holes, + rampCuts, + polygonPoints, + groundReplaced, + tiles, + ], + ) // Terrain replaces the flat ground fill rather than sitting on top of it: two // coplanar ground surfaces z-fight, and the flat one would poke through any @@ -704,10 +819,37 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { // line — while everything standing on the site keeps its own flag (the // exporter and the 2D plan draw the same line). The horizon disc is a world // backdrop rather than part of the parcel, so `visible` does not hide it. - // `showGround` hides both ground and horizon when authored geometry supplies them, unless a level - // below grade is shown: the level display hides that geometry then, and the ground stands in. const showSiteSurfaces = node.visible !== false - const showGround = siteGroundShown(node, { belowGrade }) + + // Past the property line the sculpted ground is not drawn (its material is cut to the lot): the + // horizon disc is, under the block's base. The viewer measures an eye out there against that. + const groundPastLot = useMemo( + () => + showTerrain && + showSiteSurfaces && + showGround && + !immersiveXR && + horizonGeometry && + polygonPoints && + polygonPoints.length >= 3 + ? { y: horizonY, lot: polygonPoints } + : null, + [ + showTerrain, + showSiteSurfaces, + showGround, + immersiveXR, + horizonGeometry, + polygonPoints, + horizonY, + ], + ) + useEffect(() => { + useViewer.setState({ groundPastLot }) + return () => { + useViewer.setState({ groundPastLot: null }) + } + }, [groundPastLot]) if (!(node && lineGeometry)) { return null @@ -725,21 +867,27 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { topsoil={bgColor} topY={GROUND_FILL_POSITION[1]} /> - {/* Render children (buildings and items) */} - {(node.children ?? []).map((childId) => ( - - ))} - - {/* Sculpted ground, when the site has terrain */} - {showSiteSurfaces && showGround && showTerrain && ( - - )} + + {/* Render children (buildings, items, and authored terrain tiles) */} + {(node.children ?? []).map((childId) => ( + + ))} + + {/* Sculpted ground, when the site has terrain */} + {showSiteSurfaces && showGround && showTerrain && compositeGround && ( + + )} + {showSiteSurfaces && showGround && showTerrain && !compositeGround && ( + + )} + {/* Ground fill: site polygon with slab holes, occludes below-grade geometry */} {showSiteSurfaces && showGround && groundGeometry && !showTerrain && ( diff --git a/packages/nodes/src/site/terrain-break-ground.test.ts b/packages/nodes/src/site/terrain-break-ground.test.ts new file mode 100644 index 0000000000..b680ba4c0b --- /dev/null +++ b/packages/nodes/src/site/terrain-break-ground.test.ts @@ -0,0 +1,425 @@ +import { afterAll, describe, expect, test } from 'bun:test' +import { createHash } from 'node:crypto' +import { + applyHeightPatch, + createTerrainField, + normalAt, + type TerrainField, + terrainEditField, + terrainPreviewField, +} from '@pascal-app/core' +import golden from './__fixtures__/terrain-break-ground-golden.json' +import { + BREAK_GROUND_SHAPES, + type BreakGroundScene, + breakGroundScene, + turnedRing, +} from './__fixtures__/terrain-break-ground-scenes' +import { getTerrainBreakGround, setTerrainBreakGround } from './terrain-break-split' +import type { TerrainMeshBuffers } from './terrain-geometry' +import { + buildTerrainGroundMesh, + groundMeshInReach, + terrainFieldBounds, + updateTerrainGroundMesh, +} from './terrain-ground' + +/* + * The ground beside a terrain break (`setTerrainBreakGround`). Faceted is the first build and the + * default: it must stay the buffers the commit before this switch produced, hash for hash. Smooth + * must be the same surface (every height the faceted build drew, the same break edges), shaded + * with each side's own normals, the same along a tile seam, and the same after a live stroke as + * after a rebuild. + */ + +const initial = getTerrainBreakGround() +afterAll(() => setTerrainBreakGround(initial)) + +const hash = (array: ArrayBufferView) => + createHash('sha256') + .update(Buffer.from(array.buffer, array.byteOffset, array.byteLength)) + .digest('hex') + .slice(0, 24) + +type Built = { key: string; grid: TerrainField; mesh: TerrainMeshBuffers } + +function build(scene: BreakGroundScene, ground: 'faceted' | 'smooth'): Built[] { + setTerrainBreakGround(ground) + try { + return scene.grids.map(({ key, grid }) => ({ + key, + grid, + mesh: buildTerrainGroundMesh(grid, scene.field, []), + })) + } finally { + setTerrainBreakGround(initial) + } +} + +const scenes = Object.entries(BREAK_GROUND_SHAPES).map(([name, shapes]) => + breakGroundScene(name, shapes), +) +const plain = breakGroundScene('no break', []) + +/** The distance in plan from a point to the nearest break line (an open break is its whole line). */ +function toBreaks(scene: BreakGroundScene, x: number, z: number): number { + let nearest = Number.POSITIVE_INFINITY + for (const { line } of scene.breaks) { + const closed = line[0]?.[0] === line.at(-1)?.[0] && line[0]?.[1] === line.at(-1)?.[1] + for (let i = 1; i < line.length; i++) { + const [ax, az] = line[i - 1] as [number, number] + const [bx, bz] = line[i] as [number, number] + const length2 = (bx - ax) ** 2 + (bz - az) ** 2 + let t = ((x - ax) * (bx - ax) + (z - az) * (bz - az)) / length2 + if (closed) t = Math.max(0, Math.min(1, t)) + nearest = Math.min(nearest, Math.hypot(x - ax - t * (bx - ax), z - az - t * (bz - az))) + } + } + return nearest +} + +/** The height of a mesh's surface over a plan point, read from the triangle that holds it. */ +function surfaceReader(mesh: TerrainMeshBuffers) { + const cells = new Map() + const cell = (x: number, z: number) => Math.floor(x * 2) * 100_003 + Math.floor(z * 2) + const P = mesh.positions + for (let t = 0; t < mesh.indices.length; t += 3) { + const [a, b, c] = [0, 1, 2].map((k) => (mesh.indices[t + k] as number) * 3) as [ + number, + number, + number, + ] + const xs = [P[a], P[b], P[c]] as number[] + const zs = [P[a + 2], P[b + 2], P[c + 2]] as number[] + for (let x = Math.floor(Math.min(...xs) * 2); x <= Math.floor(Math.max(...xs) * 2); x++) + for (let z = Math.floor(Math.min(...zs) * 2); z <= Math.floor(Math.max(...zs) * 2); z++) { + const key = x * 100_003 + z + const list = cells.get(key) + if (list) list.push(t) + else cells.set(key, [t]) + } + } + return (x: number, z: number): number[] => { + const found: number[] = [] + for (const t of cells.get(cell(x, z)) ?? []) { + const [a, b, c] = [0, 1, 2].map((k) => (mesh.indices[t + k] as number) * 3) as [ + number, + number, + number, + ] + const ax = P[a] as number + const az = P[a + 2] as number + const bx = P[b] as number + const bz = P[b + 2] as number + const cx = P[c] as number + const cz = P[c + 2] as number + const det = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz) + if (Math.abs(det) < 1e-12) continue + const u = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / det + const v = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / det + if (u < -1e-9 || v < -1e-9 || u + v > 1 + 1e-9) continue + found.push( + u * (P[a + 1] as number) + v * (P[b + 1] as number) + (1 - u - v) * (P[c + 1] as number), + ) + } + return found + } +} + +describe('faceted, the default, is the build before the switch', () => { + for (const scene of scenes) + test(`${scene.name}: positions, normals, uvs and indices, hash for hash`, () => { + const read = build(scene, 'faceted').map(({ key, mesh }) => ({ + key, + positions: hash(mesh.positions), + normals: hash(mesh.normals), + uvs: hash(mesh.uvs), + indices: hash(mesh.indices), + verts: mesh.positions.length / 3, + tris: mesh.indices.length / 3, + })) + expect(read).toEqual((golden as Record)[scene.name] as typeof read) + }) + + test('breaks that touch are refused by the core, so no scene holds a true T', () => { + expect(() => + breakGroundScene('touching', [ + { + line: [ + [-12, 2.2], + [12, 2.2], + ], + left: 2.5, + right: 'ground', + }, + { line: turnedRing(3, -0.3, 4, 5, 0), left: -0.8, right: 'ground' }, + ]), + ).toThrow('Terrain breaks may not cross, touch') + }) +}) + +describe('smooth is the same surface with each side’s own normals', () => { + test('a tile no break cuts is the shared grid again, and a cut one adds only its pieces', () => { + const scene = scenes.find(({ name }) => name === 'a ring that ends inside one tile') + if (!scene) throw new Error('Missing scene') + const count = (built: Built[]) => + built.map(({ mesh }) => [mesh.positions.length / 3, mesh.indices.length / 3]) + const faceted = count(build(scene, 'faceted')) + const smooth = count(build(scene, 'smooth')) + // 65 x 65 samples and two triangles a cell: the ring stands in the fourth tile alone, yet + // the faceted build cut the other three along the extensions of its sides. + expect(smooth.slice(0, 3)).toEqual([ + [4225, 8192], + [4225, 8192], + [4225, 8192], + ]) + expect(faceted.every(([vertices, triangles]) => vertices === (triangles as number) * 3)).toBe( + true, + ) + expect((smooth[3] as number[])[0]).toBeLessThan(4225 * 1.2) + expect((faceted[3] as number[])[0]).toBeGreaterThan(4225 * 5) + }) + + for (const scene of scenes) { + const faceted = build(scene, 'faceted') + const smooth = build(scene, 'smooth') + + test(`${scene.name}: every height the faceted build drew is on the smooth surface`, () => { + let checked = 0 + let uncovered = 0 + let worst = 0 + faceted.forEach(({ mesh: old }, tile) => { + const read = surfaceReader((smooth[tile] as Built).mesh) + const P = old.positions + for (let t = 0; t < old.indices.length; t += 3) { + const corners = [0, 1, 2].map((k) => (old.indices[t + k] as number) * 3) + const centre = [0, 1, 2].map( + (axis) => corners.reduce((sum, i) => sum + (P[i + axis] as number), 0) / 3, + ) as [number, number, number] + // Each corner, drawn a hair into its own triangle so the point has one region. + for (const i of corners) { + const at = [0, 1, 2].map( + (axis) => (P[i + axis] as number) + (centre[axis] - (P[i + axis] as number)) * 1e-3, + ) as [number, number, number] + const heights = read(at[0], at[2]) + if (!heights.length) uncovered++ + else worst = Math.max(worst, Math.min(...heights.map((h) => Math.abs(h - at[1])))) + checked++ + } + } + }) + expect(checked).toBeGreaterThan(90_000) + expect(uncovered).toBe(0) + expect(worst).toBeLessThan(2e-5) + }) + + test(`${scene.name}: away from a break the normal is the ground’s own, on a level side it is up`, () => { + let own = 0 + let level = 0 + let worstOwn = 0 + let worstLevel = 0 + for (const { mesh } of smooth) { + const sides = mesh.terrainBreakSides ?? [] + for (let i = 0; i < sides.length; i++) { + const x = mesh.positions[i * 3] as number + const z = mesh.positions[i * 3 + 2] as number + const normal = [0, 1, 2].map((axis) => mesh.normals[i * 3 + axis] as number) + const numeric = scene.breaks.some( + (edge, index) => + typeof edge[(sides[i] as ('left' | 'right')[])[index] as 'left'] === 'number', + ) + if (numeric) { + worstLevel = Math.max( + worstLevel, + Math.abs(normal[0] as number), + Math.abs(normal[2] as number), + 1 - (normal[1] as number), + ) + level++ + } else if (toBreaks(scene, x, z) > 1.5 && Math.max(Math.abs(x), Math.abs(z)) < 31) { + // (The outer rim of the tiles is left out: past it the two fields continue differently.) + const expected = normalAt(plain.field, x, z) + for (const axis of [0, 1, 2]) + worstOwn = Math.max( + worstOwn, + Math.abs((normal[axis] as number) - (expected[axis] as number)), + ) + own++ + } + } + } + expect(own).toBeGreaterThan(5_000) + expect(worstOwn).toBeLessThan(1e-6) + expect(worstLevel).toBe(0) + if (scene.name !== 'one straight break, oblique') expect(level).toBeGreaterThan(0) + }) + + test(`${scene.name}: beside a break the ground keeps its own slope (no bleed from the other side)`, () => { + let beside = 0 + let worst = 0 + for (const { mesh } of smooth) { + const sides = mesh.terrainBreakSides ?? [] + for (let i = 0; i < sides.length; i++) { + const x = mesh.positions[i * 3] as number + const z = mesh.positions[i * 3 + 2] as number + const numeric = scene.breaks.some( + (edge, index) => + typeof edge[(sides[i] as ('left' | 'right')[])[index] as 'left'] === 'number', + ) + if (numeric || toBreaks(scene, x, z) > 1.5) continue + const expected = normalAt(plain.field, x, z) + const dot = [0, 1, 2].reduce( + (sum, axis) => + sum + (mesh.normals[i * 3 + axis] as number) * (expected[axis] as number), + 0, + ) + worst = Math.max(worst, (Math.acos(Math.min(1, dot)) * 180) / Math.PI) + beside++ + } + } + expect(beside).toBeGreaterThan(50) + // The ground here rolls by a few degrees over a metre; a step of 0.8 to 2.5 m read into the + // normal would turn it by 40 degrees or more. + expect(worst).toBeLessThan(12) + }) + + test(`${scene.name}: two tiles agree on height and normal along their seam`, () => { + const seam = new Map() + let shared = 0 + let apart = 0 + for (const { mesh } of smooth) { + const own = new Map() + const sides = mesh.terrainBreakSides ?? [] + for (let i = 0; i < sides.length; i++) { + const x = mesh.positions[i * 3] as number + const z = mesh.positions[i * 3 + 2] as number + if (x !== 0 && z !== 0) continue + own.set(`${x}:${z}:${(sides[i] as string[]).join('')}`, [ + mesh.positions[i * 3 + 1] as number, + ...[0, 1, 2].map((axis) => mesh.normals[i * 3 + axis] as number), + ]) + } + for (const [key, value] of own) { + const other = seam.get(key) + if (other) { + if (value.some((number, index) => number !== other[index])) apart++ + shared++ + } else seam.set(key, value) + } + } + // Four seams of 65 samples; a break on a seam leaves its two sides apart there, by design. + expect(shared).toBeGreaterThan(scene.name === 'a straight break on the tile seam' ? 120 : 250) + expect(apart).toBe(0) + }) + + test(`${scene.name}: a live stroke leaves the buffers a rebuild would make`, () => { + // The stroke as the sculpt tool holds it: an edit field over the lot and its 4 m margin, + // previewed over the persisted ground (the surface reads all of it once, when the stroke + // begins), then a patch of it raised (the surface reads the patch and its halo). Three + // dabs: in open ground, on the break, and across the tile seam. + const live = terrainEditField(scene.site, scene.nodes, { + minX: -16, + minZ: -16, + maxX: 16, + maxZ: 16, + }) + const dabs: [number, number][] = [ + [-7.5, -7], + [0.5, -0.5], + [0, 6], + ] + for (const [cx, cz] of dabs) { + const half = 4 + const col0 = Math.round((cx - live.origin[0]) / live.spacing) - half + const row0 = Math.round((cz - live.origin[1]) / live.spacing) - half + const size = half * 2 + 1 + const heights = new Int16Array(size * size) + for (let row = 0; row < size; row++) + for (let col = 0; col < size; col++) + heights[row * size + col] = + (live.heights[(row0 + row) * live.cols + col0 + col] as number) + + Math.round(60 * Math.max(0, 1 - Math.hypot(col - half, row - half) / half)) + const patch = { col0, row0, cols: size, rows: size, heights } + const begun = terrainPreviewField(live, scene.field) + const after = terrainPreviewField(applyHeightPatch(live, patch), scene.field) + setTerrainBreakGround('smooth') + try { + const uploads: (number | null)[] = [] + for (const { grid } of scene.grids) { + const want = buildTerrainGroundMesh(grid, after, []) + const mesh = buildTerrainGroundMesh(grid, scene.field, []) + updateTerrainGroundMesh(mesh, begun) + // The patch and its halo of one spacing, as the ground surface hands them over. + const range = updateTerrainGroundMesh(mesh, after, { + minX: live.origin[0] + (col0 - 1) * live.spacing, + minZ: live.origin[1] + (row0 - 1) * live.spacing, + maxX: live.origin[0] + (col0 + size) * live.spacing, + maxZ: live.origin[1] + (row0 + size) * live.spacing, + }) + expect(hash(mesh.indices)).toBe(hash(want.indices)) + expect(hash(mesh.positions)).toBe(hash(want.positions)) + expect(hash(mesh.normals)).toBe(hash(want.normals)) + uploads.push(range ? range.count / 3 : null) + } + // The dab in open ground is 4.5 m from the seams: one tile is read again, three are not. + if (cx === -7.5) + expect(uploads.map((count) => count !== null)).toEqual([true, false, false, false]) + } finally { + setTerrainBreakGround(initial) + } + } + }, 60_000) + } +}) + +describe('a stroke reads only what it can reach', () => { + // The edit field of a 12 m lot inside these four tiles: the stroke's start is read inside its + // rectangle alone, and must leave what reading every vertex leaves. + for (const scene of [plain, ...scenes]) + for (const ground of ['faceted', 'smooth'] as const) { + if (scene === plain && ground === 'faceted') continue + test(`${scene.name}, ${scene === plain ? 'no break' : ground}: the start of a stroke inside its rectangle is the start read everywhere`, () => { + const live = terrainEditField(scene.site, scene.nodes, { + minX: -6, + minZ: -10, + maxX: 6, + maxZ: 2, + }) + const begun = terrainPreviewField(live, scene.field) + setTerrainBreakGround(ground) + try { + let skipped = 0 + for (const { grid } of scene.grids) { + const everywhere = buildTerrainGroundMesh(grid, scene.field, []) + updateTerrainGroundMesh(everywhere, begun) + const inside = buildTerrainGroundMesh(grid, scene.field, []) + const range = updateTerrainGroundMesh(inside, begun, terrainFieldBounds(live, 0.5)) + expect(hash(inside.positions)).toBe(hash(everywhere.positions)) + expect(hash(inside.normals)).toBe(hash(everywhere.normals)) + if (range && range.count < inside.positions.length) skipped++ + } + // Faceted, the whole mesh is read whatever the rectangle; otherwise rows are left alone. + if (scene !== plain && ground === 'faceted') expect(skipped).toBe(0) + else expect(skipped).toBeGreaterThanOrEqual(3) + } finally { + setTerrainBreakGround(initial) + } + }, 60_000) + } + + test('a mesh whose bounding sphere is out of a dab’s reach is not asked', () => { + const dab = { minX: -3, minZ: -3, maxX: 3, maxZ: 3 } + // A 32 m tile about (16, 16): its sphere reaches the origin, the next tile's does not. + const tile = (cx: number, cz: number) => ({ center: { x: cx, z: cz }, radius: 16 * Math.SQRT2 }) + expect(groundMeshInReach(tile(16, 16), dab, 2.5)).toBe(true) + expect(groundMeshInReach(tile(48, 16), dab, 2.5)).toBe(false) + expect(groundMeshInReach(tile(24, 16), dab, 2.5)).toBe(true) + expect(groundMeshInReach(null, dab, 2.5)).toBe(true) + expect( + terrainFieldBounds( + createTerrainField({ origin: [-4, 2], cols: 9, rows: 5, spacing: 0.5 }), + 0.5, + ), + ).toEqual({ minX: -4.5, minZ: 1.5, maxX: 0.5, maxZ: 4.5 }) + }) +}) diff --git a/packages/nodes/src/site/terrain-break-split.ts b/packages/nodes/src/site/terrain-break-split.ts new file mode 100644 index 0000000000..dc4beaffdd --- /dev/null +++ b/packages/nodes/src/site/terrain-break-split.ts @@ -0,0 +1,656 @@ +import { + heightAt, + type TerrainBreakNode, + type TerrainField, + terrainBreakHeightAt, + terrainBreakSideAt, +} from '@pascal-app/core' +import type { TerrainMeshBuffers, TerrainSkirtBuffers } from './terrain-geometry' + +type Point = [number, number] +type Side = 'left' | 'right' +type Piece = { points: Point[]; sides: Side[] } +const EPSILON = 1e-9 + +/** + * How the ground is shaded where the site has terrain breaks. `faceted` is the first build: one + * normal per triangle. `smooth` gives each vertex the normal of the ground on its own side of the + * breaks, as the ground without a break has it, so only the break itself is an edge. + */ +export type TerrainBreakGround = 'faceted' | 'smooth' + +function terrainBreakGroundFromEnvironment(): TerrainBreakGround { + try { + return process.env.NEXT_PUBLIC_PASCAL_TERRAIN_BREAK_GROUND === 'smooth' ? 'smooth' : 'faceted' + } catch { + return 'faceted' + } +} + +let terrainBreakGround = terrainBreakGroundFromEnvironment() + +export function getTerrainBreakGround(): TerrainBreakGround { + return terrainBreakGround +} + +/** A host chooses once, before the first ground is built; a mesh keeps the choice it was built with. */ +export function setTerrainBreakGround(ground: TerrainBreakGround): void { + terrainBreakGround = ground +} + +function distance(a: Point, b: Point, p: Point): number { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + return (dx * (p[1] - a[1]) - dz * (p[0] - a[0])) / Math.hypot(dx, dz) +} + +function halfPlane(points: Point[], a: Point, b: Point, side: Side): Point[] { + const result: Point[] = [] + const sign = side === 'left' ? 1 : -1 + for (let i = 0; i < points.length; i++) { + const p = points[i] as Point + const q = points[(i + 1) % points.length] as Point + const dp = distance(a, b, p) * sign + const dq = distance(a, b, q) * sign + if (dp >= -EPSILON) result.push(p) + if ((dp > EPSILON && dq < -EPSILON) || (dp < -EPSILON && dq > EPSILON)) { + const t = dp / (dp - dq) + result.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]) + } + } + return result.filter((p, i) => { + const q = result[(i + result.length - 1) % result.length] as Point + return Math.hypot(p[0] - q[0], p[1] - q[1]) > EPSILON + }) +} + +function partition(piece: Piece, edge: TerrainBreakNode): Piece[] { + const first = edge.line[0] as Point + const last = edge.line.at(-1) as Point + const closed = first[0] === last[0] && first[1] === last[1] + if (!closed) { + return (['left', 'right'] as const).map((side) => ({ + points: halfPlane(piece.points, first, last, side), + sides: [...piece.sides, side], + })) + } + const result: Piece[] = [] + let inside = piece.points + for (let i = 0; i < edge.line.length - 1 && inside.length >= 3; i++) { + const a = edge.line[i] as Point + const b = edge.line[i + 1] as Point + result.push({ + points: halfPlane(inside, a, b, 'right'), + sides: [...piece.sides, 'right'], + }) + inside = halfPlane(inside, a, b, 'left') + } + result.push({ points: inside, sides: [...piece.sides, 'left'] }) + return result +} + +export function terrainRegionHeight( + field: TerrainField, + breaks: readonly TerrainBreakNode[], + sides: readonly Side[], + x: number, + z: number, +): number { + for (let i = breaks.length - 1; i >= 0; i--) { + const edge = breaks[i] as TerrainBreakNode + const side = sides[i] as Side + if (typeof edge[side] === 'number') return terrainBreakHeightAt(field, edge, side, x, z) + } + for (let i = breaks.length - 1; i >= 0; i--) { + const edge = breaks[i] as TerrainBreakNode + const side = sides[i] as Side + if (terrainBreakSideAt(edge, x, z) !== side) + return terrainBreakHeightAt(field, edge, side, x, z) + } + const edge = breaks.at(-1) + return edge + ? terrainBreakHeightAt(field, edge, sides.at(-1) as Side, x, z) + : heightAt(field, x, z) +} + +/** + * The normal of the ground of one region at a point of it: central differences of that region's + * own ground one spacing away, as `normalAt` takes them, never the ground across a break. A + * read the region has no ground for (past the last triangle of its side) leaves the difference + * one-sided. + */ +function regionNormal( + field: TerrainField, + read: (px: number, pz: number) => number | null, + x: number, + y: number, + z: number, +): [number, number, number] { + const d = field.spacing + const slope = (low: number | null, high: number | null) => + low !== null && high !== null + ? (high - low) / (2 * d) + : high !== null + ? (high - y) / d + : low !== null + ? (y - low) / d + : 0 + const dhdx = slope(read(x - d, z), read(x + d, z)) + const dhdz = slope(read(x, z - d), read(x, z + d)) + const length = Math.hypot(dhdx, 1, dhdz) + return [-dhdx / length, 1 / length, -dhdz / length] +} + +type RegionReads = { + /** A region's ground at a point, or null where the region has none to read. */ + read(sides: readonly Side[], x: number, z: number): number | null + /** A height already read the plain way, kept for the neighbours that will ask for it. */ + keep(sides: readonly Side[], x: number, z: number, height: number): void +} + +/** + * The reads of one pass over a ground. A vertex on the grid asks for its region's ground at its + * four neighbours, which are those neighbours' own heights: each (region, grid point) is read + * once and kept, five reads a vertex become about one. A point off the grid (a cut triangle's + * corner) is read each time, as before; the values are the same either way. + */ +function regionReads(field: TerrainField, breaks: readonly TerrainBreakNode[]): RegionReads { + const d = field.spacing + const kept = new Map>() + const SPAN = 2 ** 20 + const place = (sides: readonly Side[], x: number, z: number) => { + const ix = Math.round(x / d) + const iz = Math.round(z / d) + if ( + sides.length > 30 || + Math.abs(x - ix * d) > 1e-9 || + Math.abs(z - iz * d) > 1e-9 || + Math.abs(ix) >= SPAN || + Math.abs(iz) >= SPAN + ) + return null + let region = 0 + for (let i = 0; i < sides.length; i++) if (sides[i] === 'left') region |= 1 << i + let heights = kept.get(region) + if (!heights) { + heights = new Map() + kept.set(region, heights) + } + return { heights, key: (ix + SPAN) * 2 * SPAN + iz + SPAN } + } + const plain = (sides: readonly Side[], x: number, z: number) => { + try { + return terrainRegionHeight(field, breaks, sides, x, z) + } catch { + return null + } + } + return { + read(sides, x, z) { + const at = place(sides, x, z) + if (!at) return plain(sides, x, z) + let height = at.heights.get(at.key) + if (height === undefined) { + height = plain(sides, x, z) ?? Number.NaN + at.heights.set(at.key, height) + } + return Number.isNaN(height) ? null : height + }, + keep(sides, x, z, height) { + place(sides, x, z)?.heights.set( + (Math.round(x / d) + SPAN) * 2 * SPAN + Math.round(z / d) + SPAN, + height, + ) + }, + } +} + +/** + * How far past a stroke's rectangle a break ground is read again. Beside a break a height is the + * plane of the nearest triangle wholly on its own side, which can stand a few cells away, and a + * normal reads one spacing farther. + */ +const BREAK_READ_REACH_CELLS = 4 + +/** + * Heights and normals of a ground built smooth, in `bounds` when given: the range of the buffers + * it wrote, as `updateTerrainGroundMesh` reports it, or null when nothing of this mesh is in reach. + */ +export function updateSmoothTerrainBreakSurface( + buffers: TerrainMeshBuffers, + field: TerrainField, + bounds?: { minX: number; minZ: number; maxX: number; maxZ: number }, +): { start: number; count: number } | null { + const regions = buffers.terrainBreakSides + const breaks = buffers.terrainBreaks + if (!regions || !breaks) return null + const reach = BREAK_READ_REACH_CELLS * field.spacing + const reads = regionReads(field, breaks) + const heights = new Float64Array(regions.length) + const within = (i: number) => { + if (!bounds) return true + const x = buffers.positions[i * 3] ?? 0 + const z = buffers.positions[i * 3 + 2] ?? 0 + return !( + x < bounds.minX - reach || + x > bounds.maxX + reach || + z < bounds.minZ - reach || + z > bounds.maxZ + reach + ) + } + // Every height first, so that a normal finds its neighbours' already read. + for (let i = 0; i < regions.length; i++) { + if (!within(i)) continue + const sides = regions[i] as readonly Side[] + const x = buffers.positions[i * 3] ?? 0 + const z = buffers.positions[i * 3 + 2] ?? 0 + const y = terrainRegionHeight(field, breaks, sides, x, z) + heights[i] = y + reads.keep(sides, x, z, y) + } + let start = regions.length * 3 + let end = 0 + for (let i = 0; i < regions.length; i++) { + if (!within(i)) continue + const x = buffers.positions[i * 3] ?? 0 + const z = buffers.positions[i * 3 + 2] ?? 0 + const sides = regions[i] as readonly Side[] + const y = heights[i] as number + buffers.positions[i * 3 + 1] = y + buffers.normals.set( + regionNormal(field, (px, pz) => reads.read(sides, px, pz), x, y, z), + i * 3, + ) + start = Math.min(start, i * 3) + end = i * 3 + 3 + } + return end > start ? { start, count: end - start } : null +} + +export function updateTerrainBreakSurface(buffers: TerrainMeshBuffers, field: TerrainField): void { + if (buffers.terrainBreakGround === 'smooth') { + updateSmoothTerrainBreakSurface(buffers, field) + return + } + const regions = buffers.terrainBreakSides + const breaks = buffers.terrainBreaks + if (!regions || !breaks) return + for (let i = 0; i < regions.length; i++) { + const x = buffers.positions[i * 3] ?? 0 + const z = buffers.positions[i * 3 + 2] ?? 0 + buffers.positions[i * 3 + 1] = terrainRegionHeight( + field, + breaks, + regions[i] as readonly Side[], + x, + z, + ) + } + for (let i = 0; i < buffers.indices.length; i += 3) { + const a = (buffers.indices[i] ?? 0) * 3 + const b = (buffers.indices[i + 1] ?? 0) * 3 + const c = (buffers.indices[i + 2] ?? 0) * 3 + const ux = (buffers.positions[b] ?? 0) - (buffers.positions[a] ?? 0) + const uy = (buffers.positions[b + 1] ?? 0) - (buffers.positions[a + 1] ?? 0) + const uz = (buffers.positions[b + 2] ?? 0) - (buffers.positions[a + 2] ?? 0) + const vx = (buffers.positions[c] ?? 0) - (buffers.positions[a] ?? 0) + const vy = (buffers.positions[c + 1] ?? 0) - (buffers.positions[a + 1] ?? 0) + const vz = (buffers.positions[c + 2] ?? 0) - (buffers.positions[a + 2] ?? 0) + const nx = uy * vz - uz * vy + const ny = uz * vx - ux * vz + const nz = ux * vy - uy * vx + const length = Math.hypot(nx, ny, nz) || 1 + for (const index of [a, b, c]) + buffers.normals.set([nx / length, ny / length, nz / length], index) + } +} + +export function splitTerrainBreaks( + source: TerrainMeshBuffers, + field: TerrainField, +): TerrainMeshBuffers { + const breaks = field.terrainBreaks ?? [] + if (!breaks.length) return source + if (terrainBreakGround === 'smooth') return splitSmoothTerrainBreaks(source, field, breaks) + const positions: number[] = [] + const uvs: number[] = [] + const indices: number[] = [] + const regions: Side[][] = [] + for (let i = 0; i < source.indices.length; i += 3) { + const triangle = Array.from(source.indices.subarray(i, i + 3)) + let pieces: Piece[] = [ + { + points: triangle.map((index) => [ + source.positions[index * 3] ?? 0, + source.positions[index * 3 + 2] ?? 0, + ]), + sides: [], + }, + ] + for (const edge of breaks) + pieces = pieces + .flatMap((piece) => partition(piece, edge)) + .filter((piece) => piece.points.length >= 3) + for (const { points, sides } of pieces) { + for (let j = 1; j < points.length - 1; j++) { + const a = points[0] as Point + const b = points[j] as Point + const c = points[j + 1] as Point + const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if (Math.abs(area) <= EPSILON) continue + const ordered = area < 0 ? [a, b, c] : [a, c, b] + for (const [x, z] of ordered) { + indices.push(positions.length / 3) + positions.push(x, 0, z) + uvs.push(x, z) + regions.push(sides) + } + } + } + } + // Duplicated seam vertices carry region identity even when their XZ is identical. + const buffers: TerrainMeshBuffers = { + positions: Float32Array.from(positions), + normals: new Float32Array(positions.length), + uvs: Float32Array.from(uvs), + indices: Uint32Array.from(indices), + terrainBreaks: breaks, + terrainBreakSides: regions, + } + updateTerrainBreakSurface(buffers, field) + return buffers +} + +/** Whether a corner of the triangle stands within `reach` of a break's line in plan. */ +function nearBreakLine( + points: readonly Point[], + breaks: readonly TerrainBreakNode[], + reach: number, +): boolean { + for (const edge of breaks) { + const first = edge.line[0] as Point + const last = edge.line.at(-1) as Point + const closed = first[0] === last[0] && first[1] === last[1] + // An open break is its whole straight line; a ring is its sides, not their extensions. + const sides: [Point, Point][] = closed + ? edge.line.slice(0, -1).map((p, j) => [p, edge.line[j + 1] as Point]) + : [[first, last]] + for (const [a, b] of sides) { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const length2 = dx * dx + dz * dz + for (const p of points) { + let t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length2 + if (closed) t = Math.max(0, Math.min(1, t)) + if (Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dz) < reach) return true + } + } + } + return false +} + +/** + * The smooth ground: the grid keeps its vertices, one per sample and shared, in their rows, and + * only a triangle that a break really cuts is redrawn in pieces with vertices of its own. So a + * tile no break comes near is the mesh it would be without one, and a stroke uploads rows again. + * + * A grid vertex is given once more for each further region whose triangles meet at it (a break + * through a sample): the two sides keep their own height and normal there. A triangle the + * partition cut only along the extension of a ring's side, all of it in one region, is drawn + * whole when it stands clear of every break: there each of its heights is its own samples' plane. + */ +function splitSmoothTerrainBreaks( + source: TerrainMeshBuffers, + field: TerrainField, + breaks: readonly TerrainBreakNode[], +): TerrainMeshBuffers { + const count = source.positions.length / 3 + const positions: number[] = [] + const uvs: number[] = [] + const regions: Side[][] = [] + const signatures: string[] = [] + for (let i = 0; i < count; i++) { + const x = source.positions[i * 3] ?? 0 + const z = source.positions[i * 3 + 2] ?? 0 + positions.push(x, 0, z) + uvs.push(x, z) + } + const again = new Map() + const shared = (vertex: number, sides: Side[], signature: string): number => { + if (signatures[vertex] === undefined) { + regions[vertex] = sides + signatures[vertex] = signature + return vertex + } + if (signatures[vertex] === signature) return vertex + const key = `${vertex}:${signature}` + let index = again.get(key) + if (index === undefined) { + index = positions.length / 3 + positions.push(positions[vertex * 3] as number, 0, positions[vertex * 3 + 2] as number) + uvs.push(uvs[vertex * 2] as number, uvs[vertex * 2 + 1] as number) + regions[index] = sides + signatures[index] = signature + again.set(key, index) + } + return index + } + const indices: number[] = [] + const clear = field.spacing * 2 + // Which side of every line a break is cut along each sample stands on (0: on it, to a micron). + // A triangle whose three corners agree on every line is not cut and needs no clipping: all but + // a few hundred of a tile's 8 192. + const lines = breaks.map((edge) => { + const first = edge.line[0] as Point + const last = edge.line.at(-1) as Point + const closed = first[0] === last[0] && first[1] === last[1] + return { + closed, + sides: closed + ? edge.line.slice(0, -1).map((p, j): [Point, Point] => [p, edge.line[j + 1] as Point]) + : ([[first, last]] as [Point, Point][]), + } + }) + const lineCount = lines.reduce((sum, line) => sum + line.sides.length, 0) + const standing = new Int8Array(count * lineCount) + for (let v = 0; v < count; v++) { + const p: Point = [positions[v * 3] as number, positions[v * 3 + 2] as number] + let at = v * lineCount + for (const line of lines) + for (const [a, b] of line.sides) { + const d = distance(a, b, p) + standing[at++] = d > 1e-6 ? 1 : d < -1e-6 ? -1 : 0 + } + } + const uncutRegions = new Map() + const uncutRegion = (vertex: number) => { + let region = 0 + let at = vertex * lineCount + for (let k = 0; k < lines.length; k++) { + let left = true + for (let j = 0; j < (lines[k] as (typeof lines)[number]).sides.length; j++) + if (standing[at++] !== 1) left = false + if (left) region |= 1 << k + } + let found = uncutRegions.get(region) + if (!found) { + const sides = lines.map((_, k): Side => (region & (1 << k) ? 'left' : 'right')) + found = { sides, signature: sides.join() } + uncutRegions.set(region, found) + } + return found + } + for (let i = 0; i < source.indices.length; i += 3) { + const triangle = Array.from(source.indices.subarray(i, i + 3)) + const corners: Point[] = triangle.map((index) => [ + source.positions[index * 3] ?? 0, + source.positions[index * 3 + 2] ?? 0, + ]) + let apart = lines.length > 30 + for (let k = 0; k < lineCount && !apart; k++) { + const side = standing[(triangle[0] as number) * lineCount + k] + apart = + side === 0 || + side !== standing[(triangle[1] as number) * lineCount + k] || + side !== standing[(triangle[2] as number) * lineCount + k] + } + if (!apart) { + const [a, b, c] = corners as [Point, Point, Point] + const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if (Math.abs(area) <= EPSILON) continue + const { sides, signature } = uncutRegion(triangle[0] as number) + for (const corner of area < 0 ? [0, 1, 2] : [0, 2, 1]) + indices.push(shared(triangle[corner] as number, sides, signature)) + continue + } + let pieces: Piece[] = [{ points: corners, sides: [] }] + for (const edge of breaks) + pieces = pieces + .flatMap((piece) => partition(piece, edge)) + .filter((piece) => piece.points.length >= 3) + const first = pieces[0] + if (!first) continue + const signature = first.sides.join() + const uncut = + pieces.length === 1 && + first.points.length === 3 && + first.points.every((p, j) => p[0] === corners[j]?.[0] && p[1] === corners[j]?.[1]) + const whole = + uncut || + (pieces.every((piece) => piece.sides.join() === signature) && + !nearBreakLine(corners, breaks, clear)) + if (whole) { + const [a, b, c] = corners as [Point, Point, Point] + const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if (Math.abs(area) <= EPSILON) continue + for (const corner of area < 0 ? [0, 1, 2] : [0, 2, 1]) + indices.push(shared(triangle[corner] as number, first.sides, signature)) + continue + } + for (const { points, sides } of pieces) { + for (let j = 1; j < points.length - 1; j++) { + const a = points[0] as Point + const b = points[j] as Point + const c = points[j + 1] as Point + const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if (Math.abs(area) <= EPSILON) continue + for (const [x, z] of area < 0 ? [a, b, c] : [a, c, b]) { + const index = positions.length / 3 + indices.push(index) + positions.push(x, 0, z) + uvs.push(x, z) + regions[index] = sides + } + } + } + } + // A sample no whole triangle uses (cut on every side, or under a hole) still has a height. + for (let i = 0; i < count; i++) + regions[i] ??= breaks.map((edge) => + terrainBreakSideAt(edge, positions[i * 3] as number, positions[i * 3 + 2] as number), + ) + const buffers: TerrainMeshBuffers = { + positions: Float32Array.from(positions), + normals: new Float32Array(positions.length), + uvs: Float32Array.from(uvs), + indices: Uint32Array.from(indices), + terrainBreaks: breaks, + terrainBreakSides: regions, + terrainBreakGround: 'smooth', + } + updateSmoothTerrainBreakSurface(buffers, field) + return buffers +} + +function skirtSegmentCuts(a: Point, b: Point, breaks: readonly TerrainBreakNode[]): number[] { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const cuts = [0, 1] + for (const edge of breaks) { + const first = edge.line[0] as Point + const last = edge.line.at(-1) as Point + const closed = first[0] === last[0] && first[1] === last[1] + const lines: [Point, Point][] = closed + ? edge.line.slice(0, -1).map((p, j) => [p, edge.line[j + 1] as Point]) + : [[first, last]] + for (const [p, q] of lines) { + const ex = q[0] - p[0] + const ez = q[1] - p[1] + const det = dx * ez - dz * ex + if (Math.abs(det) < EPSILON) continue + const t = ((p[0] - a[0]) * ez - (p[1] - a[1]) * ex) / det + const u = ((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / det + if (t > 0 && t < 1 && (!closed || (u >= 0 && u <= 1))) cuts.push(t) + } + } + return cuts.sort((p, q) => p - q) +} + +export function buildTerrainBreakSkirt( + field: TerrainField, + ring: Float32Array, + base: number, +): TerrainSkirtBuffers { + const breaks = field.terrainBreaks ?? [] + const positions: number[] = [] + const indices: number[] = [] + const regions: Side[][] = [] + const count = ring.length / 2 + for (let i = 0; i < count; i++) { + const next = (i + 1) % count + const a: Point = [ring[i * 2] ?? 0, ring[i * 2 + 1] ?? 0] + const b: Point = [ring[next * 2] ?? 0, ring[next * 2 + 1] ?? 0] + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const cuts = skirtSegmentCuts(a, b, breaks) + for (let j = 1; j < cuts.length; j++) { + const lo = cuts[j - 1] ?? 0 + const hi = cuts[j] ?? 1 + if (hi - lo < EPSILON) continue + const at = (t: number): Point => [a[0] + dx * t, a[1] + dz * t] + const sides = breaks.map((edge) => terrainBreakSideAt(edge, ...at((lo + hi) / 2))) + const offset = positions.length / 3 + for (const point of [at(lo), at(hi), at(lo), at(hi)]) positions.push(point[0], 0, point[1]) + indices.push(offset, offset + 1, offset + 2, offset + 2, offset + 1, offset + 3) + regions.push(sides) + } + } + const buffers: TerrainSkirtBuffers = { + positions: Float32Array.from(positions), + normals: new Float32Array(positions.length), + indices: Uint32Array.from(indices), + ring, + terrainBreaks: breaks, + terrainBreakSides: regions, + } + updateTerrainBreakSkirt(field, buffers, base) + return buffers +} + +export function updateTerrainBreakSkirt( + field: TerrainField, + buffers: TerrainSkirtBuffers, + base: number, +): void { + const breaks = buffers.terrainBreaks ?? [] + for (const [i, sides] of (buffers.terrainBreakSides ?? []).entries()) { + const offset = i * 12 + const dx = (buffers.positions[offset + 3] ?? 0) - (buffers.positions[offset] ?? 0) + const dz = (buffers.positions[offset + 5] ?? 0) - (buffers.positions[offset + 2] ?? 0) + const length = Math.hypot(dx, dz) || 1 + for (let j = 0; j < 4; j++) { + const at = offset + j * 3 + buffers.positions[at + 1] = + j < 2 + ? terrainRegionHeight( + field, + breaks, + sides, + buffers.positions[at] ?? 0, + buffers.positions[at + 2] ?? 0, + ) + : base + buffers.normals.set([dz / length, 0, -dx / length], at) + } + } +} diff --git a/packages/nodes/src/site/terrain-breaks.test.ts b/packages/nodes/src/site/terrain-breaks.test.ts new file mode 100644 index 0000000000..51598bc6ae --- /dev/null +++ b/packages/nodes/src/site/terrain-breaks.test.ts @@ -0,0 +1,304 @@ +import { describe, expect, test } from 'bun:test' +import { + createTerrainField, + encodeTerrainField, + persistedTerrainFieldOf, + type TerrainField, +} from '@pascal-app/core' +import { SiteNode, TerrainBreakNode } from '@pascal-app/core/schema' +import { buildTerrainBreakMesh, buildTerrainGroundMesh } from '@pascal-app/nodes' + +type Mesh = ReturnType +type Point = [number, number, number] + +function vertex(mesh: Mesh, index: number): Point { + const x = mesh.positions[index * 3] + const y = mesh.positions[index * 3 + 1] + const z = mesh.positions[index * 3 + 2] + if (x === undefined || y === undefined || z === undefined) + throw new Error(`Incomplete terrain vertex at index ${index}`) + return [x, y, z] +} + +function triangles(mesh: Mesh): [Point, Point, Point][] { + const result: [Point, Point, Point][] = [] + for (let i = 0; i < mesh.indices.length; i += 3) { + const a = mesh.indices[i] + const b = mesh.indices[i + 1] + const c = mesh.indices[i + 2] + if (a === undefined || b === undefined || c === undefined) + throw new Error(`Incomplete terrain triangle at offset ${i}`) + result.push([vertex(mesh, a), vertex(mesh, b), vertex(mesh, c)]) + } + return result +} + +function cross(a: Point, b: Point, c: Point): Point { + const u: Point = [b[0] - a[0], b[1] - a[1], b[2] - a[2]] + const v: Point = [c[0] - a[0], c[1] - a[1], c[2] - a[2]] + return [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]] +} + +function area(mesh: Mesh): number { + return triangles(mesh).reduce((sum, [a, b, c]) => sum + Math.hypot(...cross(a, b, c)) / 2, 0) +} + +function float32PositionError(point: Point): number { + return Math.hypot( + ...point.map((value) => 2 ** Math.max(-150, Math.floor(Math.log2(Math.abs(value))) - 24)), + ) +} + +function expectFaceDirection(a: Point, b: Point, c: Point, sign = 1) { + const normal = cross(a, b, c) + const length = Math.hypot(...normal) + const expected: Point = [sign * 0.8, 0, sign * -0.6] + expect(length).toBeGreaterThan(0) + expect(normal[0] * expected[0] + normal[2] * expected[2]).toBeGreaterThan(0) + const errorA = float32PositionError(a) + const errorU = errorA + float32PositionError(b) + const errorV = errorA + float32PositionError(c) + const lengthU = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) + const lengthV = Math.hypot(c[0] - a[0], c[1] - a[1], c[2] - a[2]) + // Float32 endpoint rounding is amplified by short edges. Bound the cross-product + // error, then its normalization; this does not relax winding or stored normals. + const crossError = lengthU * errorV + lengthV * errorU + errorU * errorV + const budget = Math.max(0.000005, (2 * crossError) / length) + for (const axis of [0, 1, 2] as const) + expect(Math.abs(normal[axis] / length - expected[axis])).toBeLessThanOrEqual(budget) +} + +// Independent closure oracle: barycentric coordinates on the XZ projection of +// an actual emitted surface triangle, not a height query into production authority. +function surfaceDistance(point: Point, surfaces: [Point, Point, Point][]): number { + let distance = Number.POSITIVE_INFINITY + for (const [a, b, c] of surfaces) { + const denominator = (b[2] - c[2]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[2] - c[2]) + if (Math.abs(denominator) < 1e-12) continue + const u = ((b[2] - c[2]) * (point[0] - c[0]) + (c[0] - b[0]) * (point[2] - c[2])) / denominator + const v = ((c[2] - a[2]) * (point[0] - c[0]) + (a[0] - c[0]) * (point[2] - c[2])) / denominator + if (u < -1e-5 || v < -1e-5 || u + v > 1 + 1e-5) continue + distance = Math.min(distance, Math.abs(point[1] - (u * a[1] + v * b[1] + (1 - u - v) * c[1]))) + } + return distance +} + +function fixture(left = 5, right = 2) { + const ground = createTerrainField({ origin: [28, 0], cols: 17, rows: 17, spacing: 0.5 }) + const edge = TerrainBreakNode.parse({ + id: 'terrain-break_geometry', + parentId: 'site_geometry', + kind: 'cliff', + line: [ + [29, 0], + [35, 8], + ], + left, + right, + }) + const site = SiteNode.parse({ + id: 'site_geometry', + children: [edge.id], + terrain: encodeTerrainField(ground), + }) + const field = persistedTerrainFieldOf(site, { [site.id]: site, [edge.id]: edge }) + if (!field) throw new Error('Expected break-aware terrain') + // Two windows of the canonical half-metre lattice meet at the 32 m tile seam. + const grids = [28, 32].map((x) => + createTerrainField({ origin: [x, 0], cols: 9, rows: 17, spacing: 0.5 }), + ) + return { ground, edge, field, grids } +} + +// Analytical oracle: 6-8-10 line across an 8×8 square, two constant planes, +// exposed area 10×3. Any tessellation is valid if its coverage, closure and +// winding agree; no triangulation order or vertex count is prescribed. +describe('exact terrain break surfaces and faces', () => { + test('clips both flat surfaces exactly at an oblique edge crossing the tile seam', () => { + const { field, grids } = fixture() + const surfaces = grids.map((grid) => buildTerrainGroundMesh(grid, field)) + expect(surfaces.reduce((sum, mesh) => sum + area(mesh), 0)).toBeCloseTo(64, 5) + for (const mesh of surfaces) { + expect(mesh.indices.length).toBeGreaterThan(0) + for (const [a, b, c] of triangles(mesh)) { + expect(cross(a, b, c)[1]).toBeGreaterThan(0) + const centreX = (a[0] + b[0] + c[0]) / 3 + const centreZ = (a[2] + b[2] + c[2]) / 3 + const side = 6 * centreZ - 8 * (centreX - 29) + const expected = side >= 0 ? 5 : 2 + for (const point of [a, b, c]) { + expect(Math.abs(point[1] - expected)).toBeLessThanOrEqual(0.001) + const vertexSide = 6 * point[2] - 8 * (point[0] - 29) + expect(side >= 0 ? vertexSide : -vertexSide).toBeGreaterThanOrEqual(-1e-4) + } + } + for (let i = 0; i < mesh.normals.length; i += 3) { + expect(mesh.normals[i]).toBeCloseTo(0, 6) + expect(mesh.normals[i + 1]).toBeCloseTo(1, 6) + expect(mesh.normals[i + 2]).toBeCloseTo(0, 6) + } + } + }) + + for (const [left, right, sign] of [ + [5, 2, 1], + [2, 5, -1], + ] as const) { + test(`face area, outward normals and two-sided closure with left=${left}, right=${right}`, () => { + const { edge, field, grids } = fixture(left, right) + const mesh = buildTerrainBreakMesh(edge, field, grids) + const surfaces = grids.flatMap((grid) => triangles(buildTerrainGroundMesh(grid, field))) + expect(area(mesh)).toBeCloseTo(30, 4) + expect(mesh.indices.length).toBeGreaterThan(0) + for (const [a, b, c] of triangles(mesh)) { + expectFaceDirection(a, b, c, sign) + for (const point of [a, b, c]) { + expect(Math.abs(6 * point[2] - 8 * (point[0] - 29))).toBeLessThanOrEqual(1e-4) + expect(Math.min(Math.abs(point[1] - 2), Math.abs(point[1] - 5))).toBeLessThanOrEqual( + 0.001, + ) + expect(surfaceDistance(point, surfaces)).toBeLessThanOrEqual(0.01) + } + for (const [p, q] of [ + [a, b], + [b, c], + [c, a], + ] as const) { + if (Math.abs(p[1] - q[1]) > 0.001) continue + const midpoint: Point = [(p[0] + q[0]) / 2, p[1], (p[2] + q[2]) / 2] + expect(surfaceDistance(midpoint, surfaces)).toBeLessThanOrEqual(0.01) + } + } + for (let i = 0; i < mesh.normals.length; i += 3) { + expect(mesh.normals[i]).toBeCloseTo(sign * 0.8, 5) + expect(mesh.normals[i + 1]).toBeCloseTo(0, 5) + expect(mesh.normals[i + 2]).toBeCloseTo(sign * -0.6, 5) + } + // Both levels must close at the exact seam point, independently of how + // either tile or the face is triangulated. + for (const y of [2, 5]) + expect(surfaceDistance([32, y, 4], surfaces)).toBeLessThanOrEqual(0.01) + }) + } + + test('an oblique face closes against a sloping keep-ground side across the tile seam', () => { + const { ground, edge: numericEdge, grids } = fixture() + for (let row = 0; row < ground.rows; row++) + for (let col = 0; col < ground.cols; col++) ground.heights[row * ground.cols + col] = row * 25 + const edge = TerrainBreakNode.parse({ ...numericEdge, right: 'ground' }) + const site = SiteNode.parse({ + id: 'site_geometry', + children: [edge.id], + terrain: encodeTerrainField(ground), + }) + const field = persistedTerrainFieldOf(site, { + [site.id]: site, + [edge.id]: edge, + }) as TerrainField + const surfaces = grids.flatMap((grid) => triangles(buildTerrainGroundMesh(grid, field))) + const face = buildTerrainBreakMesh(edge, field, grids) + // Lower ground y=.5z: the 10 m edge's average drop is 3 m. + expect(area(face)).toBeCloseTo(30, 4) + for (const [a, b, c] of triangles(face)) { + expectFaceDirection(a, b, c) + for (const point of [a, b, c]) { + expect( + Math.min(Math.abs(point[1] - 5), Math.abs(point[1] - 0.5 * point[2])), + ).toBeLessThanOrEqual(0.001) + expect(surfaceDistance(point, surfaces)).toBeLessThanOrEqual(0.01) + } + for (const [p, q] of [ + [a, b], + [b, c], + [c, a], + ] as const) { + const bothTop = Math.abs(p[1] - 5) < 0.001 && Math.abs(q[1] - 5) < 0.001 + const bothBottom = + Math.abs(p[1] - 0.5 * p[2]) < 0.001 && Math.abs(q[1] - 0.5 * q[2]) < 0.001 + if (bothTop || bothBottom) + expect( + surfaceDistance([(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2], surfaces), + ).toBeLessThanOrEqual(0.01) + } + } + expect(surfaceDistance([32, 2, 4], surfaces)).toBeLessThanOrEqual(0.01) + expect(surfaceDistance([32, 5, 4], surfaces)).toBeLessThanOrEqual(0.01) + }) + + test('a retaining terrace closes to the composed upper cliff, not the underlying legacy samples', () => { + const { ground, edge: cliff, grids } = fixture() + const terrace = TerrainBreakNode.parse({ + id: 'terrain-break_terrace', + parentId: 'site_geometry', + kind: 'retaining', + line: [ + [29, 4], + [30, 4], + [30, 6], + [29, 6], + [29, 4], + ], + left: 7, + right: 'ground', + }) + const site = SiteNode.parse({ + id: 'site_geometry', + children: [cliff.id, terrace.id], + terrain: encodeTerrainField(ground), + }) + const field = persistedTerrainFieldOf(site, { + [site.id]: site, + [cliff.id]: cliff, + [terrace.id]: terrace, + }) as TerrainField + const surfaces = grids.flatMap((grid) => triangles(buildTerrainGroundMesh(grid, field))) + const face = buildTerrainBreakMesh(terrace, field, grids) + expect(area(face)).toBeCloseTo(12, 4) + expect(surfaceDistance([29.5, 7, 5], surfaces)).toBeLessThanOrEqual(0.001) + expect(surfaceDistance([30.25, 5, 5], surfaces)).toBeLessThanOrEqual(0.001) + expect(surfaceDistance([35, 2, 5], surfaces)).toBeLessThanOrEqual(0.001) + for (const triangle of triangles(face)) + for (const point of triangle) { + expect(Math.min(Math.abs(point[1] - 5), Math.abs(point[1] - 7))).toBeLessThanOrEqual(0.001) + expect(surfaceDistance(point, surfaces)).toBeLessThanOrEqual(0.01) + } + }) + + test('a closed retaining terrace has a flat top, unchanged outside and a closed perimeter face', () => { + const ground = createTerrainField({ origin: [0, 0], cols: 17, rows: 17, spacing: 0.5 }) + ground.heights.fill(100) + const edge = TerrainBreakNode.parse({ + id: 'terrain-break_closed', + parentId: 'site_closed', + kind: 'retaining', + line: [ + [2.13, 2.27], + [5.13, 2.27], + [5.13, 4.27], + [2.13, 4.27], + [2.13, 2.27], + ], + left: 4, + right: 'ground', + }) + const site = SiteNode.parse({ + id: 'site_closed', + children: [edge.id], + terrain: encodeTerrainField(ground), + }) + const field = persistedTerrainFieldOf(site, { + [site.id]: site, + [edge.id]: edge, + }) as TerrainField + const surface = buildTerrainGroundMesh(ground, field) + const face = buildTerrainBreakMesh(edge, field, [ground]) + expect(area(surface)).toBeCloseTo(64, 4) + expect(area(face)).toBeCloseTo(30, 4) + const surfaces = triangles(surface) + expect(surfaceDistance([3, 4, 3], surfaces)).toBeLessThanOrEqual(0.001) + expect(surfaceDistance([6, 1, 3], surfaces)).toBeLessThanOrEqual(0.001) + for (const triangle of triangles(face)) + for (const point of triangle) + expect(surfaceDistance(point, surfaces)).toBeLessThanOrEqual(0.01) + }) +}) diff --git a/packages/nodes/src/site/terrain-geometry.test.ts b/packages/nodes/src/site/terrain-geometry.test.ts index 4a536e8686..2da63a4780 100644 --- a/packages/nodes/src/site/terrain-geometry.test.ts +++ b/packages/nodes/src/site/terrain-geometry.test.ts @@ -537,6 +537,22 @@ describe('terrainFootprint — the horizon punch', () => { }) describe('the lot block — a skirt along the property line', () => { + test('a huge virtual field uses its height bounds without scanning empty space', () => { + const field: TerrainField = { + origin: [0, 0], + cols: 20_001, + rows: 20_001, + spacing: 0.5, + step: 0.01, + heights: new Int16Array(0), + heightBounds: [-12, 3], + readHeightAt: () => { + throw new Error('Sparse lot scanned for its skirt floor') + }, + } + expect(terrainBlockBase(field)).toBe(-13) + }) + // A dented lot inside a 21 x 21 m field on a 10% grade, wound clockwise on // purpose: the ring must come out in the field perimeter's own direction. const lot: [number, number][] = [ @@ -615,4 +631,44 @@ describe('the lot block — a skirt along the property line', () => { updateTerrainSkirt(dug, skirt) expect(Array.from(skirt.positions)).toEqual(Array.from(buildTerrainSkirt(dug, ring).positions)) }) + + test('a dab re-reads the ring points in its rectangle alone, and leaves a full rewrite’s buffers', () => { + const ring = skirtRing(field, lot) + const skirt = buildTerrainSkirt(field, ring) + // Raised ground over the lot's west edge: the block's base (its lowest point) does not move. + const bounds = { minX: 0, minZ: 5, maxX: 5, maxZ: 9 } + const raised = applyHeightPatch(field, flattenPatch(field, bounds, 3) as HeightPatch) + const before = Array.from(skirt.positions) + const range = updateTerrainSkirt(raised, skirt, { + minX: bounds.minX - 1, + minZ: bounds.minZ - 1, + maxX: bounds.maxX + 1, + maxZ: bounds.maxZ + 1, + }) + expect(Array.from(skirt.positions)).toEqual( + Array.from(buildTerrainSkirt(raised, ring).positions), + ) + expect(Array.from(skirt.normals)).toEqual(Array.from(buildTerrainSkirt(raised, ring).normals)) + // The points on the west edge between z 4 and 10, of a ring of some hundred and thirty. + const moved = before.flatMap((value, index) => + value === skirt.positions[index] ? [] : [index], + ) + expect(moved.length).toBeGreaterThan(0) + expect(range).not.toBeNull() + expect(range?.start).toBeLessThanOrEqual(moved[0] as number) + expect((range?.start ?? 0) + (range?.count ?? 0)).toBeGreaterThan(moved.at(-1) as number) + expect(range?.count).toBeLessThan(skirt.positions.length / 5) + // A dab away from the property line touches no point of it. + expect(updateTerrainSkirt(raised, skirt, { minX: 8, minZ: 6, maxX: 12, maxZ: 10 })).toBeNull() + }) + + test('a dab that lowers the block’s base moves every bottom vertex: the whole skirt is rewritten', () => { + const ring = skirtRing(field, lot) + const skirt = buildTerrainSkirt(field, ring) + const bounds = { minX: 6, minZ: 6, maxX: 14, maxZ: 12 } + const dug = applyHeightPatch(field, flattenPatch(field, bounds, -2) as HeightPatch) + const range = updateTerrainSkirt(dug, skirt, bounds) + expect(range).toEqual({ start: 0, count: skirt.positions.length }) + expect(Array.from(skirt.positions)).toEqual(Array.from(buildTerrainSkirt(dug, ring).positions)) + }) }) diff --git a/packages/nodes/src/site/terrain-geometry.ts b/packages/nodes/src/site/terrain-geometry.ts index db66f4b2d8..24021f582f 100644 --- a/packages/nodes/src/site/terrain-geometry.ts +++ b/packages/nodes/src/site/terrain-geometry.ts @@ -3,8 +3,10 @@ import { heightAt, heightAtSample, normalAt, + type TerrainBreakNode, type TerrainField, } from '@pascal-app/core' +import { buildTerrainBreakSkirt, updateTerrainBreakSkirt } from './terrain-break-split' /** * Builds the terrain mesh buffers from a `TerrainField`. @@ -60,6 +62,12 @@ export type TerrainMeshBuffers = { uvs: Float32Array /** Triangle indices, two per grid cell. */ indices: Uint32Array + terrainBreaks?: readonly TerrainBreakNode[] + terrainBreakSides?: readonly (readonly ('left' | 'right')[])[] + /** Set on a ground built smooth beside its breaks (`setTerrainBreakGround`); absent, faceted. */ + terrainBreakGround?: 'smooth' + /** Vertices from this one on are closing faces: a live stroke leaves them where they stand. */ + fixedFrom?: number } /** Vertex index of sample [c,r]. */ @@ -160,6 +168,8 @@ export type TerrainSkirtBuffers = { * counter-clockwise. Absent, the skirt runs round the field's own rectangle. */ ring?: Float32Array + terrainBreaks?: readonly TerrainBreakNode[] + terrainBreakSides?: readonly (readonly ('left' | 'right')[])[] } /** @@ -224,12 +234,16 @@ function boundarySample(field: TerrainField, i: number): { col: number; row: num * sit just beneath it without cutting into the lot anywhere. */ export function terrainBlockBase(field: TerrainField): number { + if (field.heightBounds && field.heights.length === 0) { + return Math.min(0, field.heightBounds[0], HORIZON_PLANE_Y) - SKIRT_DROP + } let minH = 0 - for (let i = 0; i < field.heights.length; i++) { - const h = field.heights[i] ?? 0 - if (h < minH) minH = h + for (let row = 0; row < field.rows; row++) { + for (let col = 0; col < field.cols; col++) { + minH = Math.min(minH, heightAtSample(field, col, row)) + } } - return Math.min(minH * field.step, HORIZON_PLANE_Y) - SKIRT_DROP + return Math.min(minH, HORIZON_PLANE_Y) - SKIRT_DROP } /** @@ -251,7 +265,14 @@ export function skirtRing( area += x0 * z1 - x1 * z0 } const ordered = area > 0 ? points : [...points].reverse() - const step = field.spacing / 2 + let perimeter = 0 + for (let i = 0; i < ordered.length; i++) { + const [ax, az] = ordered[i] as readonly [number, number] + const [bx, bz] = ordered[(i + 1) % ordered.length] as readonly [number, number] + perimeter += Math.hypot(bx - ax, bz - az) + } + // Keep the fallback horizon's skirt bounded on very large virtual lots. + const step = Math.max(field.spacing / 2, perimeter / 4096) const out: number[] = [] for (let i = 0; i < ordered.length; i++) { const [ax, az] = ordered[i] as readonly [number, number] @@ -267,6 +288,8 @@ export function buildTerrainSkirt( ring?: Float32Array | null, ): TerrainSkirtBuffers { const onRing = !!ring && ring.length >= 6 + if (onRing && field.terrainBreaks?.length) + return buildTerrainBreakSkirt(field, ring as Float32Array, terrainBlockBase(field)) const count = onRing ? (ring as Float32Array).length / 2 : perimeterCount(field) const vertices = count === 0 ? 0 : (count + 1) * 2 const buffers: TerrainSkirtBuffers = { @@ -299,14 +322,25 @@ export function buildTerrainSkirt( * bookkeeping to find which boundary samples a rectangular patch touched costs * more than re-uploading all of them. The surface's dirty range earns its * complexity because it saves 400 KB a dab; here there is nothing to save. + * + * The skirt along a property line is the exception: its points are spread at half a + * cell round the whole lot (1 920 vertices on a 30 m lot, 46 KB a dab), each a read of + * the ground, so with `bounds` (a stroke's rectangle) only the points inside are read + * again. Returns the range of `positions` it wrote, or null when the stroke touched none. */ -export function updateTerrainSkirt(field: TerrainField, buffers: TerrainSkirtBuffers): void { - if (buffers.ring) { - updateRingSkirt(field, buffers, buffers.ring) - return +export function updateTerrainSkirt( + field: TerrainField, + buffers: TerrainSkirtBuffers, + bounds?: { minX: number; minZ: number; maxX: number; maxZ: number }, +): { start: number; count: number } | null { + const whole = { start: 0, count: buffers.positions.length } + if (buffers.terrainBreakSides) { + updateTerrainBreakSkirt(field, buffers, terrainBlockBase(field)) + return whole } + if (buffers.ring) return updateRingSkirt(field, buffers, buffers.ring, bounds) const count = perimeterCount(field) - if (count === 0) return + if (count === 0) return null for (let i = 0; i <= count; i++) { const { col, row } = boundarySample(field, i % count) @@ -329,6 +363,7 @@ export function updateTerrainSkirt(field: TerrainField, buffers: TerrainSkirtBuf writeSkirtVertex(buffers, topIndex, x, Math.max(h, HORIZON_PLANE_Y), z, nx, nz) writeSkirtVertex(buffers, bottomIndex, x, Math.min(h, HORIZON_PLANE_Y) - SKIRT_DROP, z, nx, nz) } + return whole } /** @@ -340,14 +375,23 @@ function updateRingSkirt( field: TerrainField, buffers: TerrainSkirtBuffers, ring: Float32Array, -): void { + bounds?: { minX: number; minZ: number; maxX: number; maxZ: number }, +): { start: number; count: number } | null { const count = ring.length / 2 - if (count < 3) return + if (count < 3) return null const base = terrainBlockBase(field) + // Every bottom vertex stands on the block's one base: a stroke that moves it moves them all. + const within = bounds && buffers.positions[4] === Math.fround(base) ? bounds : undefined + let start = buffers.positions.length + let end = 0 for (let i = 0; i <= count; i++) { const at = i % count const x = ring[at * 2] ?? 0 const z = ring[at * 2 + 1] ?? 0 + if (within && (x < within.minX || x > within.maxX || z < within.minZ || z > within.maxZ)) + continue + start = Math.min(start, i * 6) + end = i * 6 + 6 const prev = (at - 1 + count) % count const next = (at + 1) % count const tx = (ring[next * 2] ?? 0) - (ring[prev * 2] ?? 0) @@ -358,6 +402,7 @@ function updateRingSkirt( writeSkirtVertex(buffers, i * 2, x, heightAt(field, x, z), z, nx, nz) writeSkirtVertex(buffers, i * 2 + 1, x, base, z, nx, nz) } + return end > start ? { start, count: end - start } : null } function writeSkirtVertex( diff --git a/packages/nodes/src/site/terrain-ground-renderer.tsx b/packages/nodes/src/site/terrain-ground-renderer.tsx new file mode 100644 index 0000000000..8b7f94e258 --- /dev/null +++ b/packages/nodes/src/site/terrain-ground-renderer.tsx @@ -0,0 +1,116 @@ +'use client' + +import { + type SiteNode, + type TerrainTileNode, + terrainPreviewField, + useLiveTerrain, +} from '@pascal-app/core' +import { SITE_GROUND } from '@pascal-app/viewer' +import { useEffect, useMemo } from 'react' +import type { BufferAttribute } from 'three' +import { GroundVeil } from './ground-veil' +import { buildTerrainSkirt, skirtRing, updateTerrainSkirt } from './terrain-geometry' +import { + buildTerrainGroundMesh, + type TerrainGroundBounds, + terrainGroundPatches, +} from './terrain-ground' +import { + TerrainGroundSurface, + terrainBufferGeometry, + useTerrainGround, +} from './terrain-ground-surface' + +export function TerrainGroundRenderer({ + site, + tiles, +}: { + site: SiteNode + tiles: readonly TerrainTileNode[] +}) { + const ground = useTerrainGround() + const meshes = useMemo(() => { + if (!ground) return [] + return terrainGroundPatches(site, tiles).map(({ key, grid, holes }) => ({ + key, + buffers: buildTerrainGroundMesh(grid, ground.field, [...ground.holes, ...holes], ground.cuts), + })) + }, [site.terrain, site.polygon, tiles, ground?.field, ground?.holes, ground?.cuts]) + return ( + <> + {meshes.map(({ key, buffers }) => ( + + ))} + {ground?.showSkirt && } + + ) +} + +function TerrainGroundSkirt() { + const ground = useTerrainGround() + const target = useMemo(() => { + if (!ground) return null + const buffers = buildTerrainSkirt(ground.field, skirtRing(ground.field, ground.polygon)) + const geometry = terrainBufferGeometry({ + ...buffers, + uvs: new Float32Array((buffers.positions.length / 3) * 2), + }) + return { buffers, geometry } + }, [ground?.field, ground?.polygon]) + useEffect(() => () => target?.geometry.dispose(), [target]) + useEffect(() => { + if (!ground || !target) return + const refresh = (bounds?: TerrainGroundBounds) => { + const live = useLiveTerrain.getState().fieldOf(ground.siteId) + const field = live ? terrainPreviewField(live, ground.field) : ground.field + const range = updateTerrainSkirt(field, target.buffers, bounds) + if (!range) return + // A dab moves heights only: the points it reached are uploaded, and no normal. + const position = target.geometry.getAttribute('position') as BufferAttribute + let start = bounds ? range.start : 0 + let end = bounds ? range.start + range.count : position.array.length + for (const pending of position.updateRanges) { + start = Math.min(start, pending.start) + end = Math.max(end, pending.start + pending.count) + } + position.clearUpdateRanges() + position.addUpdateRange(start, end - start) + position.needsUpdate = true + if (!bounds) (target.geometry.getAttribute('normal') as BufferAttribute).needsUpdate = true + target.geometry.computeBoundingSphere() + } + refresh() + let previous = useLiveTerrain.getState().fieldOf(ground.siteId) + return useLiveTerrain.subscribe((state) => { + const field = state.fieldOf(ground.siteId) + if (field === previous) return + previous = field + const stroke = state.strokes.get(ground.siteId) ?? state.remoteStrokes.get(ground.siteId) + const patch = stroke?.lastPatch + if (!field || !patch) { + refresh() + return + } + const halo = ground.field.spacing + refresh({ + minX: field.origin[0] + patch.col0 * field.spacing - halo, + minZ: field.origin[1] + patch.row0 * field.spacing - halo, + maxX: field.origin[0] + (patch.col0 + patch.cols - 1) * field.spacing + halo, + maxZ: field.origin[1] + (patch.row0 + patch.rows - 1) * field.spacing + halo, + }) + }) + }, [ground?.siteId, ground?.field, target]) + if (!ground || !target || !ground.visible) return null + return ( + <> + + + + ) +} diff --git a/packages/nodes/src/site/terrain-ground-surface.tsx b/packages/nodes/src/site/terrain-ground-surface.tsx new file mode 100644 index 0000000000..4c86b66f34 --- /dev/null +++ b/packages/nodes/src/site/terrain-ground-surface.tsx @@ -0,0 +1,156 @@ +'use client' + +import { + type Ring, + type TerrainField, + type TerrainTileNode, + terrainPreviewField, + useLiveTerrain, +} from '@pascal-app/core' +import { SITE_GROUND } from '@pascal-app/viewer' +import { createContext, useContext, useEffect, useMemo } from 'react' +import { BufferAttribute, BufferGeometry, DynamicDrawUsage, type Material } from 'three' +import { GroundVeil } from './ground-veil' +import { lotMaskedMaterial } from './lot-mask' +import type { RampGroundCut } from './ramp-ground-holes' +import type { TerrainMeshBuffers } from './terrain-geometry' +import { + groundMeshInReach, + type TerrainGroundBounds, + terrainFieldBounds, + updateTerrainGroundMesh, +} from './terrain-ground' + +export type TerrainGroundPresentation = { + siteId: string + field: TerrainField + material: Material + veil: Material + holes: Ring[] + /** The graded ramps' footprints on the ground, with what stands at their edge. */ + cuts: readonly RampGroundCut[] + polygon: ReadonlyArray + visible: boolean + showSkirt: boolean + tiles: readonly TerrainTileNode[] +} + +export const TerrainGroundContext = createContext(null) +export const useTerrainGround = () => useContext(TerrainGroundContext) + +export function terrainBufferGeometry(buffers: TerrainMeshBuffers): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute( + 'position', + new BufferAttribute(buffers.positions, 3).setUsage(DynamicDrawUsage), + ) + geometry.setAttribute( + 'normal', + new BufferAttribute(buffers.normals, 3).setUsage(DynamicDrawUsage), + ) + geometry.setAttribute('uv', new BufferAttribute(buffers.uvs, 2)) + geometry.setIndex(new BufferAttribute(buffers.indices, 1)) + geometry.computeBoundingSphere() + return geometry +} + +function useLiveGroundGeometry( + ground: TerrainGroundPresentation | null, + buffers: TerrainMeshBuffers, + geometry: BufferGeometry, +) { + useEffect(() => { + if (!ground) return + // A faceted break ground is read whole whatever the rectangle (`updateTerrainGroundMesh`). + const bounded = !buffers.terrainBreakSides || buffers.terrainBreakGround === 'smooth' + // Past the plain ground's one spacing, a height beside a break reads a few cells farther. + const reach = ground.field.spacing * 5 + const refresh = (field: TerrainField, bounds?: TerrainGroundBounds) => { + if (bounded && bounds && !groundMeshInReach(geometry.boundingSphere, bounds, reach)) return + const range = updateTerrainGroundMesh( + buffers, + terrainPreviewField(field, ground.field), + bounds, + ) + if (!range) return + for (const name of ['position', 'normal']) { + const attribute = geometry.getAttribute(name) as BufferAttribute + let start = range.start + let end = start + range.count + for (const pending of attribute.updateRanges) { + start = Math.min(start, pending.start) + end = Math.max(end, pending.start + pending.count) + } + attribute.clearUpdateRanges() + attribute.addUpdateRange(start, end - start) + attribute.needsUpdate = true + } + geometry.computeBoundingSphere() + } + const halo = ground.field.spacing + const live = useLiveTerrain.getState().fieldOf(ground.siteId) + // A stroke that begins or ends changes the ground inside its edit field's rectangle alone. + if (live) refresh(live, terrainFieldBounds(live, halo)) + let previous = live + return useLiveTerrain.subscribe((state) => { + const field = state.fieldOf(ground.siteId) + if (field === previous) return + const edit = field ?? previous + previous = field + const stroke = state.strokes.get(ground.siteId) ?? state.remoteStrokes.get(ground.siteId) + const patch = stroke?.lastPatch + if (!field || !patch) { + refresh(field ?? ground.field, edit ? terrainFieldBounds(edit, halo) : undefined) + return + } + refresh(field, { + minX: field.origin[0] + patch.col0 * field.spacing - halo, + minZ: field.origin[1] + patch.row0 * field.spacing - halo, + maxX: field.origin[0] + (patch.col0 + patch.cols - 1) * field.spacing + halo, + maxZ: field.origin[1] + (patch.row0 + patch.rows - 1) * field.spacing + halo, + }) + }) + }, [ground?.siteId, ground?.field, buffers, geometry]) +} + +export function TerrainGroundSurface({ + buffers, + drawn = true, +}: { + buffers: TerrainMeshBuffers + /** False for a mesh no part of which is inside the property line: kept, and not drawn. */ + drawn?: boolean +}) { + const ground = useTerrainGround() + const geometry = useMemo(() => terrainBufferGeometry(buffers), [buffers]) + useEffect(() => () => geometry.dispose(), [geometry]) + const materials = useMemo(() => { + if (!ground) return null + return { + surface: lotMaskedMaterial(ground.material, ground.polygon), + veil: lotMaskedMaterial(ground.veil, ground.polygon), + } + }, [ground?.material, ground?.veil, ground?.polygon]) + useEffect( + () => () => { + materials?.surface.dispose() + materials?.veil.dispose() + }, + [materials], + ) + useLiveGroundGeometry(ground, buffers, geometry) + if (!ground || !materials || !ground.visible) return null + return ( + <> + + {drawn && } + + ) +} diff --git a/packages/nodes/src/site/terrain-ground.ts b/packages/nodes/src/site/terrain-ground.ts new file mode 100644 index 0000000000..607ae58146 --- /dev/null +++ b/packages/nodes/src/site/terrain-ground.ts @@ -0,0 +1,224 @@ +import { + createTerrainField, + decodeTerrainField, + heightAt, + normalAt, + type Ring, + type SiteNode, + TERRAIN_TILE_SIZE, + type TerrainField, + type TerrainTileNode, + tileFieldOf, +} from '@pascal-app/core' +import { rampCutFaces } from './ramp-cut-faces' +import type { RampGroundCut } from './ramp-ground-holes' +import { + splitTerrainBreaks, + updateSmoothTerrainBreakSurface, + updateTerrainBreakSurface, +} from './terrain-break-split' +import { buildTerrainMesh, type TerrainMeshBuffers } from './terrain-geometry' +import { cutTerrainHoles } from './terrain-holes' + +export type TerrainGroundPatch = { key: string; grid: TerrainField; holes: Ring[] } +export type TerrainGroundBounds = { minX: number; minZ: number; maxX: number; maxZ: number } + +const MAX_CONTINUATION_PATCHES = 256 + +export function terrainGridBoundary(field: TerrainField): Ring { + const [x, z] = field.origin + const maxX = x + (field.cols - 1) * field.spacing + const maxZ = z + (field.rows - 1) * field.spacing + return [ + [x, z], + [maxX, z], + [maxX, maxZ], + [x, maxZ], + ] +} + +export function needsTerrainContinuation(site: SiteNode): boolean { + const base = decodeTerrainField(site.terrain) + if (!base) return false + const [x, z] = base.origin + const maxX = x + (base.cols - 1) * base.spacing + const maxZ = z + (base.rows - 1) * base.spacing + return site.polygon.points.some(([px, pz]) => px < x || px > maxX || pz < z || pz > maxZ) +} + +/** Legacy keeps its own triangulation; only the land beyond it gets a new grid. */ +export function terrainGroundPatches( + site: SiteNode, + tiles: readonly TerrainTileNode[], +): TerrainGroundPatch[] { + const base = decodeTerrainField(site.terrain) + const tileGrids = tiles.flatMap((tile) => { + const grid = tileFieldOf(tile) + return grid ? [grid] : [] + }) + const tileHoles = tileGrids.map(terrainGridBoundary) + const patches: TerrainGroundPatch[] = base + ? [{ key: 'legacy', grid: base, holes: tileHoles }] + : [] + const points = site.polygon.points + if (!points.length) return patches + const minX = Math.min(...points.map(([x]) => x)) + const maxX = Math.max(...points.map(([x]) => x)) + const minZ = Math.min(...points.map(([, z]) => z)) + const maxZ = Math.max(...points.map(([, z]) => z)) + const holes = base ? [terrainGridBoundary(base), ...tileHoles] : tileHoles + const firstX = Math.floor(minX / TERRAIN_TILE_SIZE) + const firstZ = Math.floor(minZ / TERRAIN_TILE_SIZE) + const lastX = Math.ceil(maxX / TERRAIN_TILE_SIZE) + const lastZ = Math.ceil(maxZ / TERRAIN_TILE_SIZE) + if ((lastX - firstX) * (lastZ - firstZ) > MAX_CONTINUATION_PATCHES) { + // Render-only fallback: authored geometry stays exact; huge empty context + // must not allocate a dense half-metre mesh merely because the lot grew. + const grid = createTerrainField({ + origin: [minX, minZ], + spacing: Math.max(0.5, (maxX - minX) / 64, (maxZ - minZ) / 64), + }) + return [...patches, { key: 'continuation:coarse', grid, holes }] + } + for (let iz = firstZ; iz < lastZ; iz++) { + for (let ix = firstX; ix < lastX; ix++) { + if (tiles.some((tile) => tile.ix === ix && tile.iz === iz)) continue + const grid = createTerrainField({ origin: [ix * TERRAIN_TILE_SIZE, iz * TERRAIN_TILE_SIZE] }) + if (base && gridInside(grid, base)) continue + patches.push({ key: `continuation:${ix}:${iz}`, grid, holes }) + } + } + return patches +} + +function gridInside(grid: TerrainField, outer: TerrainField): boolean { + return grid.origin.every((value, axis) => { + const origin = outer.origin[axis] ?? 0 + const count = axis === 0 ? outer.cols : outer.rows + const size = axis === 0 ? grid.cols : grid.rows + return ( + value >= origin && value + (size - 1) * grid.spacing <= origin + (count - 1) * outer.spacing + ) + }) +} + +/** + * The rectangle a live edit field covers, `halo` wider. Outside it a preview is the persisted + * ground itself, so the start and the end of a stroke change nothing there. + */ +export function terrainFieldBounds(field: TerrainField, halo: number): TerrainGroundBounds { + return { + minX: field.origin[0] - halo, + minZ: field.origin[1] - halo, + maxX: field.origin[0] + (field.cols - 1) * field.spacing + halo, + maxZ: field.origin[1] + (field.rows - 1) * field.spacing + halo, + } +} + +/** + * Whether a mesh can hold a vertex within `reach` of the rectangle: its bounding sphere, in plan. + * A site of 256 tiles asks every one of them on every dab; all but one or two answer from here. + */ +export function groundMeshInReach( + sphere: { center: { x: number; z: number }; radius: number } | null, + bounds: TerrainGroundBounds, + reach: number, +): boolean { + if (!sphere || !Number.isFinite(sphere.radius)) return true + const dx = Math.max(bounds.minX - sphere.center.x, 0, sphere.center.x - bounds.maxX) + const dz = Math.max(bounds.minZ - sphere.center.z, 0, sphere.center.z - bounds.maxZ) + return Math.hypot(dx, dz) <= sphere.radius + reach +} + +/** All patches read the same world-space authority, including their shared rim. */ +export function updateTerrainGroundMesh( + buffers: TerrainMeshBuffers, + field: TerrainField, + bounds?: TerrainGroundBounds, +): { start: number; count: number } | null { + if (buffers.terrainBreakSides) { + if (buffers.terrainBreakGround === 'smooth') + return updateSmoothTerrainBreakSurface(buffers, field, bounds) + updateTerrainBreakSurface(buffers, field) + return { start: 0, count: buffers.positions.length } + } + let start = buffers.positions.length + let end = 0 + // Closing faces stand on heights of their own; a live stroke reads the ground, not them. + const limit = buffers.fixedFrom === undefined ? buffers.positions.length : buffers.fixedFrom * 3 + for (let i = 0; i < limit; i += 3) { + const x = buffers.positions[i] ?? 0 + const z = buffers.positions[i + 2] ?? 0 + if (bounds && (x < bounds.minX || x > bounds.maxX || z < bounds.minZ || z > bounds.maxZ)) { + continue + } + buffers.positions[i + 1] = heightAt(field, x, z) + buffers.normals.set(normalAt(field, x, z), i) + start = Math.min(start, i) + end = i + 3 + } + return end > start ? { start, count: end - start } : null +} + +/** Fold cut-edge vertices into the surface so each tile is one CPU mesh. */ +export function buildTerrainGroundMesh( + grid: TerrainField, + field: TerrainField, + holes: Ring[] = [], + cuts: readonly RampGroundCut[] = [], +): TerrainMeshBuffers { + const buffers = buildTerrainMesh(grid) + const boundary = cutTerrainHoles(buffers, holes) + if (boundary) { + const offset = buffers.positions.length / 3 + for (const [key, name] of [ + ['positions', 'position'], + ['normals', 'normal'], + ['uvs', 'uv'], + ] as const) { + const extra = boundary.geometry.getAttribute(name).array + const merged = new Float32Array(buffers[key].length + extra.length) + merged.set(buffers[key]) + merged.set(extra, buffers[key].length) + buffers[key] = merged + } + const extra = boundary.geometry.index?.array ?? [] + const indices = new Uint32Array(buffers.indices.length + extra.length) + indices.set(buffers.indices) + for (let i = 0; i < extra.length; i++) { + indices[buffers.indices.length + i] = offset + (extra[i] ?? 0) + } + buffers.indices = indices + boundary.geometry.dispose() + } + const split = splitTerrainBreaks(buffers, field) + if (split === buffers) updateTerrainGroundMesh(buffers, field) + const faces = boundary && cuts.length ? rampCutFaces(boundary, cuts, field) : null + return faces ? withFaces(split, faces) : split +} + +/** The cut faces after the ground's own vertices, which a live stroke leaves alone. */ +function withFaces( + ground: TerrainMeshBuffers, + faces: ReturnType & object, +): TerrainMeshBuffers { + const offset = ground.positions.length / 3 + const join = (a: T, b: Float32Array) => { + const joined = new Float32Array(a.length + b.length) + joined.set(a) + joined.set(b, a.length) + return joined + } + const indices = new Uint32Array(ground.indices.length + faces.indices.length) + indices.set(ground.indices) + for (let i = 0; i < faces.indices.length; i++) + indices[ground.indices.length + i] = offset + (faces.indices[i] ?? 0) + return { + ...ground, + positions: join(ground.positions, faces.positions), + normals: join(ground.normals, faces.normals), + uvs: join(ground.uvs, faces.uvs), + indices, + fixedFrom: offset, + } +} diff --git a/packages/nodes/src/site/terrain-holes.ts b/packages/nodes/src/site/terrain-holes.ts index 1c5ffe2f46..7e7ebcfcf0 100644 --- a/packages/nodes/src/site/terrain-holes.ts +++ b/packages/nodes/src/site/terrain-holes.ts @@ -3,7 +3,32 @@ import { BufferAttribute, BufferGeometry, DynamicDrawUsage, ShapeUtils, Vector2 import type { TerrainMeshBuffers } from './terrain-geometry' type Sample = { indices: number[]; weights: number[] } -export type TerrainHoleBoundary = { geometry: BufferGeometry; samples: Sample[] } +/** An edge of the kept ground that runs along a hole's edge, the kept ground on its left. */ +export type TerrainHoleRim = { a: number; b: number } +export type TerrainHoleBoundary = { + geometry: BufferGeometry + samples: Sample[] + /** The plan position of each sample as clipped, before the geometry's single precision. */ + points: [number, number][] + /** Indices into `samples`: the ground's cut edge, vertex for vertex. */ + rim: TerrainHoleRim[] +} + +/** + * How near a hole's edge a clipped edge's midpoint must lie to be the ground's cut edge: the + * polygon clipper works on a 0.1 mm lattice, so a clipped vertex is up to 0.06 mm off the ring. + */ +const ON_EDGE_M = 2e-4 + +function signedArea(ring: readonly (readonly [number, number])[]): number { + let area = 0 + for (let i = 0; i < ring.length; i++) { + const [x0, z0] = ring[i] as readonly [number, number] + const [x1, z1] = ring[(i + 1) % ring.length] as readonly [number, number] + area += x0 * z1 - x1 * z0 + } + return area / 2 +} // Keep the regular grid's vertex layout for partial brush uploads. Only triangles // crossing an excavation rim need additional vertices, interpolated on that grid. @@ -21,7 +46,26 @@ export function cutTerrainHoles( })) const kept: number[] = [], indices: number[] = [], - samples: Sample[] = [] + samples: Sample[] = [], + points: [number, number][] = [], + rim: TerrainHoleRim[] = [] + const edges: [number, number, number, number][] = cutouts.flatMap(({ outer, holes: inner }) => + [outer, ...inner].flatMap((ring) => + ring.map(([x, z], i) => { + const [nx, nz] = ring[(i + 1) % ring.length] as [number, number] + return [x, z, nx, nz] as [number, number, number, number] + }), + ), + ) + const onCutout = (x: number, z: number) => + edges.some(([x0, z0, x1, z1]) => { + const dx = x1 - x0 + const dz = z1 - z0 + const length2 = dx * dx + dz * dz + const t = + length2 === 0 ? 0 : Math.max(0, Math.min(1, ((x - x0) * dx + (z - z0) * dz) / length2)) + return Math.hypot(x - x0 - t * dx, z - z0 - t * dz) <= ON_EDGE_M + }) for (let i = 0; i < buffers.indices.length; i += 3) { const source = Array.from(buffers.indices.subarray(i, i + 3)) const triangle: Ring = source.map((id) => [ @@ -30,13 +74,14 @@ export function cutTerrainHoles( ]) const xs = triangle.map(([x]) => x), zs = triangle.map(([, z]) => z) + // A triangle only touching a hole is clipped too: its edge on the hole's is the cut edge. if ( !bounds.some( (box) => - box.maxX > Math.min(...xs) && - box.minX < Math.max(...xs) && - box.maxZ > Math.min(...zs) && - box.minZ < Math.max(...zs), + box.maxX >= Math.min(...xs) - ON_EDGE_M && + box.minX <= Math.max(...xs) + ON_EDGE_M && + box.maxZ >= Math.min(...zs) - ON_EDGE_M && + box.minZ <= Math.max(...zs) + ON_EDGE_M, ) ) { kept.push(...source) @@ -52,9 +97,25 @@ export function cutTerrainHoles( const wa = ((b[1] - c[1]) * (x - c[0]) + (c[0] - b[0]) * (z - c[1])) / determinant const wb = ((c[1] - a[1]) * (x - c[0]) + (a[0] - c[0]) * (z - c[1])) / determinant samples.push({ indices: source, weights: [wa, wb, 1 - wa - wb] }) + points.push([x, z]) } for (const [a, b, c] of ShapeUtils.triangulateShape(contour, voids)) indices.push(offset + c!, offset + b!, offset + a!) + let first = offset + for (const [ringIndex, ring] of [polygon.outer, ...polygon.holes].entries()) { + const area = signedArea(ring) + // The kept ground is inside an outer ring and outside a void. + const keptLeft = ringIndex === 0 ? area > 0 : area < 0 + for (let j = 0; j < ring.length; j++) { + const next = (j + 1) % ring.length + const [x0, z0] = ring[j] as [number, number] + const [x1, z1] = ring[next] as [number, number] + if (Math.hypot(x1 - x0, z1 - z0) < ON_EDGE_M || !onCutout((x0 + x1) / 2, (z0 + z1) / 2)) + continue + rim.push(keptLeft ? { a: first + j, b: first + next } : { a: first + next, b: first + j }) + } + first += ring.length + } } } buffers.indices = new Uint32Array(kept) @@ -73,7 +134,7 @@ export function cutTerrainHoles( ) geometry.setAttribute('uv', new BufferAttribute(uv, 2)) geometry.setIndex(indices) - const boundary = { geometry, samples } + const boundary = { geometry, samples, points, rim } updateTerrainHoleBoundary(boundary, buffers) return boundary } diff --git a/packages/nodes/src/site/terrain-lag-mesh.test.ts b/packages/nodes/src/site/terrain-lag-mesh.test.ts new file mode 100644 index 0000000000..3433b0bcfd --- /dev/null +++ b/packages/nodes/src/site/terrain-lag-mesh.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, test } from 'bun:test' +import { createHash } from 'node:crypto' +import { persistedTerrainFieldOf, terrainTilesOf, tileFieldOf } from '@pascal-app/core' +import { terrainLagScenes } from '../../../core/src/lib/__fixtures__/terrain-lag-scenes' +import golden from './__fixtures__/terrain-lag-mesh-golden.json' +import { buildTerrainGroundMesh } from './terrain-ground' + +/* + * Failure modes this file pins (the terrain lag, 15 Oct): a tile mesh was built in seconds because + * every vertex read the break-aware authority the slow way. The golden hashes are the buffers the + * build before the speed-up produced, byte for byte, on scenes with closed and open breaks. + */ + +const hash = (array: ArrayBufferView) => + createHash('sha256') + .update(Buffer.from(array.buffer, array.byteOffset, array.byteLength)) + .digest('hex') + .slice(0, 24) + +type Mesh = { + id: string + positions: string + normals: string + indices: string + verts: number + tris: number +} + +describe('a tile mesh is the same buffers as before the speed-up', () => { + for (const scene of terrainLagScenes()) { + const expected = (golden as unknown as Record)[scene.name] + if (!expected?.length) continue + test(`${scene.name}: positions, normals and indices, byte for byte`, () => { + const field = persistedTerrainFieldOf(scene.site, scene.nodes)! + const tiles = terrainTilesOf(scene.site, scene.nodes) + const picked = tiles.filter((_, index) => [0, 4, 7].includes(index)) + expect(picked.map((tile) => tile.id)).toEqual(expected.map((mesh) => mesh.id)) + picked.forEach((tile, index) => { + const buffers = buildTerrainGroundMesh(tileFieldOf(tile)!, field, []) + const want = expected[index]! + expect({ + positions: hash(buffers.positions), + normals: hash(buffers.normals), + indices: hash(buffers.indices), + verts: buffers.positions.length / 3, + tris: buffers.indices.length / 3, + }).toEqual({ + positions: want.positions, + normals: want.normals, + indices: want.indices, + verts: want.verts, + tris: want.tris, + }) + }) + }) + } +}) diff --git a/packages/nodes/src/site/terrain-renderer.tsx b/packages/nodes/src/site/terrain-renderer.tsx index eb8daa732e..45b26975f2 100644 --- a/packages/nodes/src/site/terrain-renderer.tsx +++ b/packages/nodes/src/site/terrain-renderer.tsx @@ -1,38 +1,19 @@ 'use client' -import { type Ring, type SiteNode, terrainFieldOf, useLiveTerrain } from '@pascal-app/core' +import { decodeTerrainField, type Ring, type SiteNode } from '@pascal-app/core' import { SITE_GROUND } from '@pascal-app/viewer' -import { useEffect, useMemo, useRef } from 'react' +import { useEffect, useMemo } from 'react' import type { Material } from 'three' import { GroundVeil } from './ground-veil' import { lotMaskedMaterial } from './lot-mask' import { skirtRing } from './terrain-geometry' -import { - applyTerrainPatch, - createTerrainGeometry, - disposeTerrainGeometry, - needsRebuild, - type TerrainGeometry, -} from './terrain-mesh' +import { createTerrainGeometry, disposeTerrainGeometry } from './terrain-mesh' /** - * Renders the site's sculpted ground. + * The unchanged legacy grid, when neither tiles nor lot growth need composition. * - * Mounted by `SiteRenderer` only when the site has terrain (or a stroke is in - * flight), so a scene that never touched terrain mounts nothing at all and pays - * nothing. - * - * Two things here are load-bearing and easy to get wrong: - * - * - **The geometry is a ref, not React state.** A sculpt stroke pushes dozens of - * patches a second; routing each through a re-render would rebuild the - * `BufferGeometry` object identity every dab and throw away the partial-upload - * win entirely. The component subscribes to the *patch*, mutates the buffers in - * place, and never re-renders during a stroke. - * - **It stays on the default `SCENE_LAYER`.** This is real, visible, - * shadow-receiving geometry — not an overlay. Overlay/hit-area meshes must use - * the editor layer, but moving actual scene geometry there would exclude it from - * the MRT depth/normal pass and break the screen-space ink against it. + * Live strokes use TerrainGroundRenderer's global authority instead. Keeping the + * original lattice here avoids resampling old scenes merely by loading them. */ export const TerrainRenderer = ({ material, @@ -40,6 +21,7 @@ export const TerrainRenderer = ({ site, holes, polygon, + showSkirt = true, }: { /** Owned by `SiteRenderer` so the ground material stays defined in one place. */ material: Material @@ -53,22 +35,16 @@ export const TerrainRenderer = ({ * base — rather than the field's padded box. */ polygon?: ReadonlyArray | null + showSkirt?: boolean }) => { - const targetRef = useRef(null) - - // Persisted terrain only — the live stroke is applied imperatively below, so a - // dab never triggers a React render. - const persistedField = useMemo( - () => terrainFieldOf({ id: site.id, terrain: site.terrain }), - [site.id, site.terrain], - ) + const persistedField = useMemo(() => decodeTerrainField(site.terrain), [site.terrain]) const target = useMemo(() => { - const field = useLiveTerrain.getState().fieldOf(site.id) ?? persistedField + const field = persistedField if (!field) return null const ring = polygon && polygon.length >= 3 ? skirtRing(field, polygon) : null return createTerrainGeometry(field, holes, ring && ring.length >= 6 ? ring : null) - }, [persistedField, site.id, holes, polygon]) + }, [persistedField, holes, polygon]) // The surface (and the cut edges round recessed slabs) stop at the property // line; the skirt keeps the plain material — it *is* the line. @@ -93,7 +69,6 @@ export const TerrainRenderer = ({ [surfaceVeil, veil], ) - targetRef.current = target useEffect( () => () => { if (target) disposeTerrainGeometry(target) @@ -101,29 +76,6 @@ export const TerrainRenderer = ({ [target], ) - // Imperative subscription rather than a selector hook: the point is to react to - // a dab *without* re-rendering. Zustand's subscribe gives the previous state - // too, so a patch is only uploaded once even if an unrelated store update - // notifies. - useEffect(() => { - let lastPatch = useLiveTerrain.getState().strokeOf(site.id)?.lastPatch ?? null - return useLiveTerrain.subscribe((state) => { - const stroke = state.strokes.get(site.id) - const current = targetRef.current - if (!(stroke && current)) { - lastPatch = null - return - } - if (!stroke.lastPatch || stroke.lastPatch === lastPatch) return - lastPatch = stroke.lastPatch - // A resized field cannot be patched — the vertex count changed. That only - // happens on import, never mid-stroke, so bail and let the persisted-field - // rebuild handle it rather than silently corrupting the buffers. - if (needsRebuild(current, stroke.field)) return - applyTerrainPatch(current, stroke.field, stroke.lastPatch) - }) - }, [site.id]) - if (!target) return null return ( @@ -155,13 +107,17 @@ export const TerrainRenderer = ({ round the lot. `receiveShadow` for the same reason the surface has it — a raised edge is lit ground that a building next to it should darken. */} - - + {showSkirt && ( + <> + + + + )} ) } diff --git a/packages/nodes/src/site/terrain-reveal.test.ts b/packages/nodes/src/site/terrain-reveal.test.ts new file mode 100644 index 0000000000..57eed086d4 --- /dev/null +++ b/packages/nodes/src/site/terrain-reveal.test.ts @@ -0,0 +1,100 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { + type AnyNode, + type AnyNodeId, + nodeRegistry, + registerNode, + runAsSceneCommitAuthor, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { startConstructionReveal } from '@pascal-app/viewer' +import { Group, Mesh, MeshBasicMaterial, PlaneGeometry } from 'three' +import { builtinPlugin } from '../index' + +// What replaying graded terrain costs a frame: a large graded scene (24 tiles, 5 breaks), +// every tile graded by the agent at once. Skipped unless SCENE_JSON= is set. +const path = process.env.SCENE_JSON +const scene = path ? JSON.parse(readFileSync(path, 'utf8')) : null + +const tick = (frames: number[]) => ({ + mean: frames.reduce((sum, ms) => sum + ms, 0) / Math.max(1, frames.length), + p95: [...frames].sort((a, b) => a - b)[Math.floor(frames.length * 0.95)] ?? 0, + max: Math.max(0, ...frames), +}) + +test.skipIf(!scene)('grading every tile replays them at a cost no frame feels', () => { + nodeRegistry._reset() + for (const definition of builtinPlugin.nodes ?? []) registerNode(definition) + globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame ??= () => {} + useScene.getState().setScene(scene.nodes, scene.rootNodeIds) + const tiles = Object.values(useScene.getState().nodes as Record).filter( + (node) => node.type === 'terrain-tile', + ) + // Each tile's mesh is what the renderer builds: 65 x 65 samples. + const roots = tiles.map((tile) => { + const root = new Group() + root.add(new Mesh(new PlaneGeometry(32, 32, 64, 64), new MeshBasicMaterial())) + sceneRegistry.nodes.set(tile.id, root) + return root + }) + const driver = startConstructionReveal({ + reveals: (commit) => commit.author === 'agent', + prefersReducedMotion: () => false, + level: () => 'full', + }) + let now = 0 + const frames: number[] = [] + const ticks: number[] = [] + const step = () => { + now += 16 + const began = performance.now() + driver.tick(now) + const tickMs = performance.now() - began + ticks.push(tickMs) + for (const root of roots) { + root.updateMatrix() + root.updateMatrixWorld(true) + } + frames.push(performance.now() - began) + } + for (let index = 0; index < 60; index += 1) step() + const idle = tick(frames) + frames.length = 0 + + const runs: unknown[] = [] + for (let run = 0; run < 3; run += 1) { + frames.length = 0 + const began = performance.now() + runAsSceneCommitAuthor('agent', () => + useScene.getState().updateNodes( + tiles.map((tile) => ({ + id: tile.id as AnyNodeId, + data: { + heights: `${(tile as unknown as { heights: string }).heights}${'A'.repeat(run + 1)}`, + } as never, + })), + ), + ) + const commitMs = performance.now() - began + for (let index = 0; index < 400; index += 1) step() + const playing = tick(frames) + const slowest = frames + .map((ms, index) => ({ index, ms })) + .sort((a, b) => b.ms - a.ms) + .slice(0, 3) + + runs.push({ commitMs, playing, slowest }) + } + console.log(JSON.stringify({ tiles: tiles.length, idleFrameMs: idle, runs })) + for (const run of runs as { commitMs: number; playing: { p95: number } }[]) { + expect(run.commitMs).toBeLessThan(100) + expect(run.playing.p95).toBeLessThan(4) + } + driver.stop() +}) diff --git a/packages/nodes/src/site/terrain-tiles.test.ts b/packages/nodes/src/site/terrain-tiles.test.ts new file mode 100644 index 0000000000..0917e5e4b2 --- /dev/null +++ b/packages/nodes/src/site/terrain-tiles.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, test } from 'bun:test' +import { createTerrainField, encodeTerrainField, persistedTerrainFieldOf } from '@pascal-app/core' +import { SiteNode, TerrainTileNode } from '@pascal-app/core/schema' +import { + buildTerrainGroundMesh, + buildTerrainTileMesh, + terrainGroundPatches, +} from '@pascal-app/nodes' + +function slopedTile(ix: number) { + const field = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + // y = x/5 has exact centimetre samples on the half-metre lattice. + for (let row = 0; row < 65; row++) + for (let col = 0; col < 65; col++) field.heights[row * 65 + col] = ix * 640 + col * 10 + return TerrainTileNode.parse({ + id: `terrain-tile_${ix}`, + parentId: 'site_mesh', + ix, + iz: 0, + level: 0, + step: 0.01, + heights: encodeTerrainField(field).heights, + }) +} + +// CPU rendering contract: shared world positions/normals, plus disjoint base +// and tile coverage. Material/GPU lot clipping is a separate integration check. +describe('tiled terrain meshes', () => { + test('a 10 km lot uses bounded continuation geometry without losing coverage or tile masking', () => { + const base = createTerrainField({ cols: 65, rows: 65, spacing: 0.5 }) + const tile = slopedTile(1) + const site = SiteNode.parse({ + id: 'site_mesh', + terrain: encodeTerrainField(base), + polygon: { + type: 'polygon', + points: [ + [0, 0], + [10_000, 0], + [10_000, 10_000], + [0, 10_000], + ], + }, + }) + const field = persistedTerrainFieldOf(site, { [site.id]: site, [tile.id]: tile }) + if (!field) throw new Error('Missing ground') + const NativeInt16Array = globalThis.Int16Array + let allocations = 0 + // Stop the unbounded old path safely rather than allocating 98,000 tile grids. + globalThis.Int16Array = new Proxy(NativeInt16Array, { + construct(target, args, newTarget) { + allocations++ + if (allocations > 16) throw new Error('Unbounded continuation grid allocation') + return Reflect.construct(target, args, newTarget) + }, + }) + let patches: ReturnType + try { + patches = terrainGroundPatches(site, [tile]) + } finally { + globalThis.Int16Array = NativeInt16Array + } + expect(patches.length).toBeLessThanOrEqual(2) + let area = 0 + for (const patch of patches) { + expect(patch.grid.cols * patch.grid.rows).toBeLessThanOrEqual(65 * 65) + const mesh = buildTerrainGroundMesh(patch.grid, field, patch.holes) + for (let i = 0; i < mesh.indices.length; i += 3) { + const a = (mesh.indices[i] ?? 0) * 3 + const b = (mesh.indices[i + 1] ?? 0) * 3 + const c = (mesh.indices[i + 2] ?? 0) * 3 + const ax = mesh.positions[a] ?? 0, + az = mesh.positions[a + 2] ?? 0 + const bx = mesh.positions[b] ?? 0, + bz = mesh.positions[b + 2] ?? 0 + const cx = mesh.positions[c] ?? 0, + cz = mesh.positions[c + 2] ?? 0 + const x = (ax + bx + cx) / 3, + z = (az + bz + cz) / 3 + expect(x > 32 && x < 64 && z > 0 && z < 32).toBe(false) + area += Math.abs((bx - ax) * (cz - az) - (cx - ax) * (bz - az)) / 2 + } + } + // Whole lot less one independently rendered 32 m tile. Half a square metre + // tolerance accommodates Float32 vertex storage over a 100,000,000 m² domain. + expect(area).toBeCloseTo(100_000_000 - 32 * 32, 0) + }) + + test('adjacent meshes have identical heights and analytic normals along the shared edge', () => { + const site = SiteNode.parse({ id: 'site_mesh' }) + const left = slopedTile(0) + const right = slopedTile(1) + const field = persistedTerrainFieldOf(site, { + [site.id]: site, + [left.id]: left, + [right.id]: right, + }) + if (!field) throw new Error('Missing virtual terrain') + const a = buildTerrainTileMesh(left, field) + const b = buildTerrainTileMesh(right, field) + expect(a.positions).toHaveLength(65 * 65 * 3) + expect(b.positions).toHaveLength(65 * 65 * 3) + // Stay one sample inside the exterior Z borders: only the internal seam is at issue. + for (let row = 1; row < 64; row++) { + const ai = (row * 65 + 64) * 3 + const bi = row * 65 * 3 + for (let axis = 0; axis < 3; axis++) { + expect(a.positions[ai + axis]).toBe(b.positions[bi + axis]) + expect(a.normals[ai + axis]).toBe(b.normals[bi + axis]) + } + expect(a.positions[ai]).toBe(32) + expect(a.positions[ai + 1]).toBeCloseTo(6.4, 5) + expect(a.normals[ai]).toBeCloseTo(-1 / Math.sqrt(26), 6) + expect(a.normals[ai + 1]).toBeCloseTo(5 / Math.sqrt(26), 6) + expect(a.normals[ai + 2]).toBeCloseTo(0, 6) + } + }) + + test('authored tiles remove covered legacy triangles without losing the uncovered legacy ground', () => { + const legacy = createTerrainField({ cols: 129, rows: 65, spacing: 0.5 }) + legacy.heights.fill(100) + const tile = slopedTile(0) + const site = SiteNode.parse({ + id: 'site_mesh', + terrain: encodeTerrainField(legacy), + polygon: { + type: 'polygon', + points: [ + [0, 0], + [64, 0], + [64, 32], + [0, 32], + ], + }, + }) + const frozen = JSON.stringify(site.terrain) + const field = persistedTerrainFieldOf(site, { [site.id]: site, [tile.id]: tile }) + if (!field) throw new Error('Missing virtual terrain') + let uncoveredArea = 0 + for (const patch of terrainGroundPatches(site, [tile])) { + const mesh = buildTerrainGroundMesh(patch.grid, field, patch.holes) + for (let i = 0; i < mesh.indices.length; i += 3) { + const a = (mesh.indices[i] ?? 0) * 3 + const b = (mesh.indices[i + 1] ?? 0) * 3 + const c = (mesh.indices[i + 2] ?? 0) * 3 + const ax = mesh.positions[a] ?? 0, + az = mesh.positions[a + 2] ?? 0 + const bx = mesh.positions[b] ?? 0, + bz = mesh.positions[b + 2] ?? 0 + const cx = mesh.positions[c] ?? 0, + cz = mesh.positions[c + 2] ?? 0 + const x = (ax + bx + cx) / 3, + z = (az + bz + cz) / 3 + expect(x > 0 && x < 32 && z > 0 && z < 32).toBe(false) + if (x > 32 && x < 64 && z > 0 && z < 32) + uncoveredArea += Math.abs((bx - ax) * (cz - az) - (cx - ax) * (bz - az)) / 2 + } + } + expect(uncoveredArea).toBeCloseTo(32 * 32, 6) + expect(JSON.stringify(site.terrain)).toBe(frozen) + }) +}) diff --git a/packages/nodes/src/slab/__tests__/terrain-draped.test.ts b/packages/nodes/src/slab/__tests__/terrain-draped.test.ts new file mode 100644 index 0000000000..7f8ecd3a53 --- /dev/null +++ b/packages/nodes/src/slab/__tests__/terrain-draped.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + createTerrainField, + encodeTerrainField, + type GeometryContext, + LevelNode, + SiteNode, + SlabNode, + surfaceHeightAt, + type TerrainField, +} from '@pascal-app/core' +import { Mesh } from 'three' +import { buildSlabGeometry } from '../geometry' + +const polygon: [number, number][] = [ + [0, 0], + [2, 0], + [2, 2], + [0, 2], +] + +function contextFor(field: TerrainField, position: [number, number, number] = [0, 0, 0], yaw = 0) { + const site = SiteNode.parse({ terrain: encodeTerrainField(field) }) + const building = BuildingNode.parse({ parentId: site.id, position, rotation: [0, yaw, 0] }) + const level = LevelNode.parse({ parentId: building.id, level: 0 }) + building.children = [level.id] + const nodes: Record = { + [site.id]: site, + [building.id]: building, + [level.id]: level, + } + const context: GeometryContext = { + resolve: (id) => nodes[id] as never, + parent: level, + children: [], + siblings: [], + } + return { context, level } +} + +function topTriangles(slab: SlabNode, context: GeometryContext) { + const group = buildSlabGeometry(slab, context, 'solid', false) + const mesh = group.children.find( + (child) => child instanceof Mesh && child.userData.slotId === 'surface', + ) + if (!(mesh instanceof Mesh)) throw new Error('The slab has no top surface') + const positions = mesh.geometry.getAttribute('position') + const indices = mesh.geometry.getIndex() + const points: [number, number, number][] = [] + for (let index = 0; index < (indices?.count ?? positions.count); index++) { + const vertex = indices ? indices.getX(index) : index + points.push([positions.getX(vertex), positions.getY(vertex), positions.getZ(vertex)]) + } + group.traverse((child) => { + if (child instanceof Mesh) child.geometry.dispose() + }) + return points +} + +function hillField() { + const field = createTerrainField({ origin: [0, 0], cols: 3, rows: 3, spacing: 1 }) + // A one-metre peak at the interior sample, absent from the four boundary corners. + field.heights[4] = Math.round(1 / field.step) + return field +} + +describe('terrain-draped manual slab', () => { + test('follows interior heightfield creases rather than spanning a hill with one flat cap', () => { + const field = hillField() + const { context, level } = contextFor(field) + const slab = SlabNode.parse({ + parentId: level.id, + polygon, + terrainMode: 'draped', + elevation: 0.03, + }) + const triangles = topTriangles(slab, context) + expect(Math.max(...triangles.map((point) => point[1]))).toBeCloseTo(1.03) + for (let index = 0; index < triangles.length; index += 3) { + const triangle = triangles.slice(index, index + 3) + const centre = triangle.reduce( + (sum, point) => sum.map((value, axis) => value + (point[axis] ?? 0) / 3), + [0, 0, 0], + ) + expect(centre[1]).toBeCloseTo( + surfaceHeightAt(field, centre[0] ?? 0, centre[2] ?? 0) + 0.03, + 5, + ) + } + }) + + test('samples ground in Site coordinates under a translated and rotated building', () => { + const field = createTerrainField({ origin: [-5, -5], cols: 21, rows: 21, spacing: 1 }) + for (let row = 0; row < field.rows; row++) + for (let col = 0; col < field.cols; col++) { + const siteX = field.origin[0] + col * field.spacing + field.heights[row * field.cols + col] = Math.round((siteX * 0.1) / field.step) + } + const { context, level } = contextFor(field, [3, 2, 4], Math.PI / 2) + const slab = SlabNode.parse({ + parentId: level.id, + polygon, + terrainMode: 'draped', + elevation: 0.03, + }) + for (const [x, y, z] of topTriangles(slab, context)) { + expect(y + 2).toBeCloseTo(surfaceHeightAt(field, 3 + z, 4 - x) + 0.03, 5) + } + }) + + test('keeps existing and explicitly flat slabs at their authored elevation on sloping ground', () => { + const { context, level } = contextFor(hillField()) + for (const terrainMode of [undefined, 'flat'] as const) { + const slab = SlabNode.parse({ parentId: level.id, polygon, terrainMode, elevation: 0.3 }) + for (const point of topTriangles(slab, context)) expect(point[1]).toBeCloseTo(0.3) + } + }) +}) diff --git a/packages/nodes/src/slab/definition.edit.ts b/packages/nodes/src/slab/definition.edit.ts index 8ff3c8829b..a33d9b098d 100644 --- a/packages/nodes/src/slab/definition.edit.ts +++ b/packages/nodes/src/slab/definition.edit.ts @@ -248,7 +248,7 @@ function slabHandles(node: SlabNodeType): HandleDescriptor[] { // A footprint's floor (base plate) has one control, its height above the // ground, drawn by the editor's footprint height handle; room plates are // reached through their room. Only user-drawn slabs keep these handles. - if (node.plateRole) return [] + if (node.plateRole || node.terrainMode === 'draped') return [] return node.recessed ? [slabRecessedDepthHandle()] : [slabThicknessHandle(), slabBaseElevationHandle()] diff --git a/packages/nodes/src/slab/definition.render.ts b/packages/nodes/src/slab/definition.render.ts index 1155570b98..c13c553026 100644 --- a/packages/nodes/src/slab/definition.render.ts +++ b/packages/nodes/src/slab/definition.render.ts @@ -3,6 +3,7 @@ import { pointInPolygon2D, type SlabNode as SlabNodeType, slabSlots, + slabTerrainHeightAt, } from '@pascal-app/core' import type { NodeRenderDefinition } from '../definition-contributions' import { surfaceBatchable } from '../shared/node-batch/batchable' @@ -57,7 +58,13 @@ export const slabRenderDefinition: NodeRenderDefinition & { kin ) ) return null - return liftedManualSlab(context.nodes, slab).elevation + return slabTerrainHeightAt( + liftedManualSlab(context.nodes, slab), + context.nodes, + x, + z, + 'live', + ) }, }, }, diff --git a/packages/nodes/src/slab/dependency-tracker.ts b/packages/nodes/src/slab/dependency-tracker.ts index 16c0405353..38e1942b2b 100644 --- a/packages/nodes/src/slab/dependency-tracker.ts +++ b/packages/nodes/src/slab/dependency-tracker.ts @@ -11,6 +11,8 @@ import { scopeSlabPolygonContext, slabPolygonContextChanges, slabPolygonContextForLevel, + slabTerrainFrameOf, + type TerrainField, type ZoneNode, } from '@pascal-app/core' @@ -18,6 +20,7 @@ type LevelContext = { slabs: SlabNode[] } type CachedLevel = { prepared: ReturnType transform: string + drape: { field: TerrainField | null; baseY: number | null; revision: number } partitionRevision: number slabs: Map references: { @@ -64,6 +67,7 @@ export function createSlabDependencyTracker(initialNodes: Record = null + for (const slab of context.slabs) { + terrainFrame = slabTerrainFrameOf(slab, nodes) + if (terrainFrame) break + } + const field = terrainFrame?.field ?? null + const baseY = terrainFrame?.baseY ?? null + const sameDrape = cached?.drape.field === field && cached?.drape.baseY === baseY + const drape = { + field, + baseY, + revision: (cached?.drape.revision ?? 0) + (sameDrape ? 0 : 1), + } // Plates carry room finishes, so a zone edit changes what they draw even // when nothing about their own polygon moved. const { zones, openings = [] } = plateLevelContext(level ?? null, (id) => nodes[id]) @@ -130,6 +147,7 @@ export function createSlabDependencyTracker(initialNodes: Record(left: T[], right: T[]) => left.length === right.length && left.every((node, index) => node === right[index] || sign(node) === sign(right[index]!)) if ( cached && + sameDrape && cached.transform === transformSignature && sameValues(cached.references.context.walls, polygonContext.walls) && sameValues(cached.references.slabs, context.slabs) && @@ -169,12 +190,14 @@ export function createSlabDependencyTracker(initialNodes: Record { + for (const courtyard of [false, true]) { + for (const terrainMode of ['draped', 'flat'] as const) { + test(`${terrainMode} top with courtyard=${courtyard}`, async () => { + const site = SiteNode.parse({ + id: 'site_foundation', + children: ['building_foundation'], + terrain: encodeTerrainField(createTerrainField({ cols: 9, rows: 9, spacing: 1 })), + }) + const building = BuildingNode.parse({ + id: 'building_foundation', + parentId: site.id, + children: ['level_foundation'], + }) + const level = LevelNode.parse({ + id: 'level_foundation', + parentId: building.id, + level: 0, + height: 3, + children: ['slab_base', 'slab_path'], + }) + const base = SlabNode.parse({ + id: 'slab_base', + parentId: level.id, + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + holes: courtyard + ? [ + [ + [0.5, 0.5], + [3.5, 0.5], + [3.5, 3.5], + [0.5, 3.5], + ], + ] + : [], + plateRole: 'base', + floorHeight: 1.05, + referenceFloorElevation: 0.05, + elevation: 1.05, + }) + const path = SlabNode.parse({ + id: 'slab_path', + parentId: level.id, + polygon: [ + [1, 1], + [3, 1], + [3, 3], + [1, 3], + ], + terrainMode, + elevation: 0.03, + thickness: 0.05, + autoFromWalls: false, + metadata: { flatwork: 'walk' }, + }) + const nodes: Record = Object.fromEntries( + [site, building, level, base, path].map((node) => [node.id, node]), + ) + const context = { + resolve: (id: string) => nodes[id] as N | undefined, + parent: level, + children: [], + siblings: [base], + } satisfies GeometryContext + const build = slabDefinition.geometry + if (!build) throw new Error('The slab definition has no geometry builder') + const geometry = await build(path, context, 'solid', false) + if (!(geometry instanceof Object3D)) throw new Error('The slab has no rendered geometry') + try { + geometry.updateMatrixWorld(true) + const ray = new Raycaster(new Vector3(2, 10, 2), new Vector3(0, -1, 0)) + const top = ray.intersectObject(geometry, true)[0] + if (!top) throw new Error('The path has no rendered top at its centre') + expect(top.point.y).toBeCloseTo(terrainMode === 'draped' ? 0.03 : 1.03, 5) + expect(path.elevation).toBe(0.03) + } finally { + geometry.traverse((object) => { + if (!(object instanceof Mesh)) return + object.geometry.dispose() + for (const material of Array.isArray(object.material) + ? object.material + : [object.material]) { + material.dispose() + } + }) + } + }) + } + } +}) diff --git a/packages/nodes/src/slab/geometry.ts b/packages/nodes/src/slab/geometry.ts index f01391cc35..d3116693f8 100644 --- a/packages/nodes/src/slab/geometry.ts +++ b/packages/nodes/src/slab/geometry.ts @@ -34,6 +34,7 @@ import { type SlabNode, type SlabSlotId, slabPolygonContextFromGeometry, + slabTerrainFrameOf, surfaceHeightAt, terrainFieldOf, useScene, @@ -57,6 +58,31 @@ import { generateFenceSlotGeometries } from '../fence/geometry-parts' import { creaseCrossings } from '../site/terrain-drape' import { buildDeckGeometry } from './deck-geometry' import { clipPlateTerrainFill, splitPlateFaces, splitSlabFacesByFacing } from './surface-split' +import { drapeSlabGeometry } from './terrain-draped' + +function drapedSlabFrame(node: SlabNode, ctx: GeometryContext | undefined) { + if (node.terrainMode !== 'draped' || !ctx) return null + if (ctx.sceneNodes) return slabTerrainFrameOf(node, ctx.sceneNodes, 'live') + const nodes: Record = {} + let ancestor = ctx.parent + while (ancestor && !nodes[ancestor.id]) { + nodes[ancestor.id] = ancestor + if ('children' in ancestor) + for (const id of ancestor.children) { + const child = ctx.resolve(id as AnyNodeId) + if (child?.type !== 'level') continue + nodes[child.id] = child + for (const childId of child.children) { + const member = ctx.resolve(childId as AnyNodeId) + if (member) nodes[member.id] = member + } + } + ancestor = ancestor.parentId + ? (ctx.resolve(ancestor.parentId as AnyNodeId) ?? null) + : null + } + return slabTerrainFrameOf(node, nodes, 'live') +} /** * Stage B builder for slab. Reuses `generateSlabGeometry` (pure @@ -360,7 +386,9 @@ export function buildSlabGeometry( ctx?.levelBaseAt ?? ((x: number, z: number) => node.parentId ? levelBaseElevationAt(baseNodes, node.parentId, x, z) : 0) + const terrainFrame = drapedSlabFrame(node, ctx) const platform = + !terrainFrame && isFloorPlate(node) && node.support !== 'open' && !node.plateRole && @@ -441,6 +469,11 @@ export function buildSlabGeometry( geometry.dispose() return } + if (terrainFrame) { + const source = geometry + geometry = drapeSlabGeometry(source, terrainFrame) + source.dispose() + } const mesh = new Mesh(geometry, material) mesh.castShadow = true mesh.receiveShadow = true @@ -553,6 +586,7 @@ export function buildSlabGeometry( if ( (foundation || outdoor || (!node.plateRole && node.fillToTerrain)) && !node.recessed && + !terrainFrame && !platform && group.children.length > 0 ) { diff --git a/packages/nodes/src/slab/terrain-draped.ts b/packages/nodes/src/slab/terrain-draped.ts new file mode 100644 index 0000000000..e5f205c23e --- /dev/null +++ b/packages/nodes/src/slab/terrain-draped.ts @@ -0,0 +1,130 @@ +import { type SlabTerrainFrame, surfaceHeightAt, type TerrainField } from '@pascal-app/core' +import { BufferGeometry, Float32BufferAttribute } from 'three' + +type Vertex = { + x: number + y: number + z: number + u: number + v: number + siteX: number + siteZ: number +} +const EPSILON = 1e-9 + +function interpolate(from: Vertex, to: Vertex, fraction: number): Vertex { + const mix = (key: keyof Vertex) => from[key] + (to[key] - from[key]) * fraction + return { + x: mix('x'), + y: mix('y'), + z: mix('z'), + u: mix('u'), + v: mix('v'), + siteX: mix('siteX'), + siteZ: mix('siteZ'), + } +} + +function clipHalf(polygon: Vertex[], distance: (vertex: Vertex) => number, sign: number): Vertex[] { + const result: Vertex[] = [] + for (const [index, from] of polygon.entries()) { + const to = polygon[(index + 1) % polygon.length] + if (!to) continue + const fromDistance = distance(from) * sign + const toDistance = distance(to) * sign + if (fromDistance >= -EPSILON) result.push(from) + if ( + (fromDistance > EPSILON && toDistance < -EPSILON) || + (fromDistance < -EPSILON && toDistance > EPSILON) + ) { + result.push(interpolate(from, to, fromDistance / (fromDistance - toDistance))) + } + } + return result +} + +function splitFamily( + polygons: Vertex[][], + coordinate: (vertex: Vertex) => number, + maximum: number, +): Vertex[][] { + const result: Vertex[][] = [] + for (const polygon of polygons) { + const coordinates = polygon.map(coordinate) + const first = Math.max(0, Math.ceil(Math.min(...coordinates))) + const last = Math.min(maximum, Math.floor(Math.max(...coordinates))) + let parts = [polygon] + for (let crease = first; crease <= last; crease++) { + parts = parts.flatMap((part) => { + const distances = part.map((vertex) => coordinate(vertex) - crease) + if ( + !distances.some((distance) => distance < -EPSILON) || + !distances.some((distance) => distance > EPSILON) + ) + return [part] + const distance = (vertex: Vertex) => coordinate(vertex) - crease + return [clipHalf(part, distance, 1), clipHalf(part, distance, -1)].filter( + (half) => half.length >= 3, + ) + }) + } + result.push(...parts) + } + return result +} + +function terrainPieces(triangle: Vertex[], field: TerrainField | null): Vertex[][] { + if (!field) return [triangle] + const column = (vertex: Vertex) => (vertex.siteX - field.origin[0]) / field.spacing + const row = (vertex: Vertex) => (vertex.siteZ - field.origin[1]) / field.spacing + const columns = splitFamily([triangle], column, field.cols - 1) + const rows = splitFamily(columns, row, field.rows - 1) + return splitFamily(rows, (vertex) => column(vertex) + row(vertex), field.cols + field.rows - 2) +} + +/** Split at every terrain crease before lifting, so interior hills cannot pass through a cap. */ +export function drapeSlabGeometry(source: BufferGeometry, frame: SlabTerrainFrame): BufferGeometry { + const position = source.getAttribute('position') + const uv = source.getAttribute('uv') + const index = source.getIndex() + const positions: number[] = [] + const uvs: number[] = [] + const vertexAt = (offset: number): Vertex => { + const vertex = index ? index.getX(offset) : offset + const x = position.getX(vertex) + const z = position.getZ(vertex) + const [siteX, siteZ] = frame.toSite(x, z) + return { + x, + y: position.getY(vertex), + z, + u: uv?.getX(vertex) ?? x, + v: uv?.getY(vertex) ?? -z, + siteX, + siteZ, + } + } + for (let offset = 0; offset < (index?.count ?? position.count); offset += 3) { + const triangle = [vertexAt(offset), vertexAt(offset + 1), vertexAt(offset + 2)] + for (const polygon of terrainPieces(triangle, frame.field)) { + const first = polygon[0] + if (!first) continue + for (let corner = 1; corner < polygon.length - 1; corner++) { + const second = polygon[corner] + const third = polygon[corner + 1] + if (!(second && third)) continue + for (const vertex of [first, second, third]) { + const ground = frame.field ? surfaceHeightAt(frame.field, vertex.siteX, vertex.siteZ) : 0 + positions.push(vertex.x, vertex.y + ground - frame.baseY, vertex.z) + uvs.push(vertex.u, vertex.v) + } + } + } + } + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)) + geometry.setAttribute('uv2', new Float32BufferAttribute(uvs, 2)) + geometry.computeVertexNormals() + return geometry +} diff --git a/packages/nodes/src/terrain-break/__fixtures__/terrain-lag-break-golden.json b/packages/nodes/src/terrain-break/__fixtures__/terrain-lag-break-golden.json new file mode 100644 index 0000000000..3fa5e77f66 --- /dev/null +++ b/packages/nodes/src/terrain-break/__fixtures__/terrain-lag-break-golden.json @@ -0,0 +1 @@ +{"three rings, ground outside":[{"id":"terrain-break_1","key":"terrain-tile_0_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_1","key":"terrain-tile_0_1","positions":"a1b2c14c72be5efb0030358e","normals":"4f4223b5e2feec04c0ae1763","uvs":"37ce878e3374f180875c1d0a","indices":"445bb8657b17984b5c63fe83","sides":"8beb5f737f262937d7bd1203","quads":42},{"id":"terrain-break_1","key":"terrain-tile_0_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_1","key":"terrain-tile_1_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_1","key":"terrain-tile_1_1","positions":"6b7affb88220f96a2720d340","normals":"f73d5da26d166201f62bbec8","uvs":"caa9c6cc11af6b31f63e00eb","indices":"1de6b017a36e98f5df4b19d1","sides":"24c85def0fb4bed95792cca0","quads":62},{"id":"terrain-break_1","key":"terrain-tile_1_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_1","key":"terrain-tile_2_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_1","key":"terrain-tile_2_1","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_1","key":"terrain-tile_2_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_0_0","positions":"dff2304b9bccb6a79a50c3d5","normals":"7d601253e058a32d88ba5da6","uvs":"632d573477afa6a9136093c3","indices":"806f63f3463b6e0bf8c126a3","sides":"f93db62c08d1bf0df875a0e0","quads":60},{"id":"terrain-break_0","key":"terrain-tile_0_1","positions":"7ceead69b13bbedd9c048626","normals":"6d7b24c0559793f3794b2341","uvs":"c8b162606e987fc06b1cc815","indices":"8def3c9de8bb2a0b12518d88","sides":"00edc44f5c28779b6382ed95","quads":66},{"id":"terrain-break_0","key":"terrain-tile_0_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_1_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_1_1","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_1_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_2_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_2_1","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_2_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_0_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_0_1","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_0_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_1_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_1_1","positions":"7d1e27bff95cdc45e66a54b8","normals":"e25afa076ee025349f8ecfb3","uvs":"1408ad14f4ee9f86c2272baa","indices":"b5d710afc419ada71f350d3e","sides":"aea67787f9169b7589643d0c","quads":54},{"id":"terrain-break_2","key":"terrain-tile_1_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_2_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_2_1","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_2","key":"terrain-tile_2_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0}],"one ring, numeric both sides":[{"id":"terrain-break_0","key":"terrain-tile_0_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_0_1","positions":"cb677def84d0a5cb634b1766","normals":"a6cc1bb4d3701a0957364890","uvs":"422b52f4dc41f776bfee5ade","indices":"90d40589edd4aa9ef47cbc55","sides":"3807b8a3e4907e387cd33b75","quads":40},{"id":"terrain-break_0","key":"terrain-tile_0_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_1_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_1_1","positions":"cebd62cc124a524ca9f87ceb","normals":"5319f753938230724f2d2fd0","uvs":"8f0bde0de2098dd7cc93eb55","indices":"806f63f3463b6e0bf8c126a3","sides":"85b986471c80a69359ae0abd","quads":60},{"id":"terrain-break_0","key":"terrain-tile_1_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_2_0","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_2_1","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0},{"id":"terrain-break_0","key":"terrain-tile_2_2","positions":"e3b0c44298fc1c149afbf4c8","normals":"e3b0c44298fc1c149afbf4c8","uvs":"e3b0c44298fc1c149afbf4c8","indices":"e3b0c44298fc1c149afbf4c8","sides":"4f53cda18c2baa0c0354bb5f","quads":0}]} \ No newline at end of file diff --git a/packages/nodes/src/terrain-break/definition.edit.ts b/packages/nodes/src/terrain-break/definition.edit.ts new file mode 100644 index 0000000000..121b7619da --- /dev/null +++ b/packages/nodes/src/terrain-break/definition.edit.ts @@ -0,0 +1,18 @@ +import type { TerrainBreakNode } from '@pascal-app/core' +import type { FloorplanNodeExtension } from '@pascal-app/editor' +import type { NodeEditContribution } from '../definition-contributions' + +export const terrainBreakEditContribution: NodeEditContribution = { + tool: () => import('./tool'), + extensions: { + 'pascal:editor/floorplan': { + tool: () => import('./floorplan-tool'), + } satisfies FloorplanNodeExtension, + }, + parametrics: { groups: [], customPanel: () => import('./panel') }, + toolHints: [ + { key: 'Left click', label: 'Start terrain boundary' }, + { key: 'Left click', label: 'Finish boundary across the lot' }, + { key: 'Esc', label: 'Cancel' }, + ], +} diff --git a/packages/nodes/src/terrain-break/definition.render.ts b/packages/nodes/src/terrain-break/definition.render.ts new file mode 100644 index 0000000000..b77085569d --- /dev/null +++ b/packages/nodes/src/terrain-break/definition.render.ts @@ -0,0 +1,58 @@ +import { TerrainBreakNode } from '@pascal-app/core' +import type { NodeRenderDefinition } from '../definition-contributions' +import { buildTerrainBreakFloorplan } from './floorplan' +import { buildTerrainBreakGeometry } from './geometry' + +export const terrainBreakRenderDefinition: NodeRenderDefinition & { + kind: 'terrain-break' +} = { + kind: 'terrain-break', + schemaVersion: 1, + schema: TerrainBreakNode, + category: 'site', + defaults: () => { + const { + id: _id, + type: _type, + ...defaults + } = TerrainBreakNode.parse({ + id: 'terrain-break_default', + line: [ + [0, 0], + [10, 0], + ], + kind: 'cliff', + left: 1, + right: 'ground', + }) + return defaults + }, + capabilities: { + revealOnEdit: ['line', 'kind', 'left', 'right'], + drawTool: true, + selectable: { hitVolume: 'mesh' }, + deletable: true, + duplicable: false, + presettable: false, + hostable: { parents: ['site'] }, + surfaces: { hosting: false }, + }, + dirtyTracking: false, + rendersChildren: false, + renderer: { kind: 'parametric', module: () => import('./renderer') }, + bakeGeometry: buildTerrainBreakGeometry, + floorplan: buildTerrainBreakFloorplan, + floorplanScope: 'site', + presentation: { + label: 'Terrain break', + description: + 'An exact vertical cliff, retaining or soil boundary between two ground elevations.', + icon: { kind: 'iconify', name: 'lucide:mountain' }, + paletteSection: 'structure', + paletteOrder: 78, + }, + mcp: { + description: + 'Site-owned directed terrain boundary with exact side heights and a vertical face.', + }, +} diff --git a/packages/nodes/src/terrain-break/definition.ts b/packages/nodes/src/terrain-break/definition.ts new file mode 100644 index 0000000000..cccd526c08 --- /dev/null +++ b/packages/nodes/src/terrain-break/definition.ts @@ -0,0 +1,8 @@ +import { composeNodeDefinition } from '../definition-contributions' +import { terrainBreakEditContribution } from './definition.edit' +import { terrainBreakRenderDefinition } from './definition.render' + +export const terrainBreakDefinition = composeNodeDefinition( + terrainBreakRenderDefinition, + terrainBreakEditContribution, +) diff --git a/packages/nodes/src/terrain-break/draft.tsx b/packages/nodes/src/terrain-break/draft.tsx new file mode 100644 index 0000000000..20d148e0c0 --- /dev/null +++ b/packages/nodes/src/terrain-break/draft.tsx @@ -0,0 +1,147 @@ +'use client' + +import type { AnyNodeId, SceneApi, TerrainBreakNode } from '@pascal-app/core' +import { + isTypingTarget, + markToolCancelConsumed, + useEditor, + useInteractionScope, + visibleScene, +} from '@pascal-app/editor' +import { Html } from '@react-three/drei' +import { useCallback, useEffect } from 'react' +import { createPortal } from 'react-dom' +import { create } from 'zustand' +import { rampSiteFrame } from '../ramp/edit' +import { commitTerrainBreakCreation, terrainBreakLotLine } from './edit' +import { TerrainBreakOptions } from './options' + +type Point = [number, number] +type Options = Pick +type Draft = { + start: Point | null + hover: Point | null + options: Options + error: string | null +} +export const useTerrainBreakDraft = create(() => ({ + start: null, + hover: null, + options: { kind: 'cliff', left: 1, right: 'ground' }, + error: null, +})) +let owners = 0 +const resetDraft = () => useTerrainBreakDraft.setState({ start: null, hover: null, error: null }) + +export function useTerrainBreakDraftController({ + sceneApi, + activeLevelId, + selectNode, + finishTool, + view, +}: { + sceneApi: SceneApi + activeLevelId: AnyNodeId | null + selectNode: (id: AnyNodeId) => void + finishTool: () => void + view: '2d' | '3d' +}) { + const draft = useTerrainBreakDraft() + const frame = rampSiteFrame(sceneApi, activeLevelId) + const addPoint = useCallback( + (point: Point) => { + const current = useTerrainBreakDraft.getState() + if (!current.start) { + useTerrainBreakDraft.setState({ start: point, hover: point, error: null }) + return + } + try { + const resolved = rampSiteFrame(sceneApi, activeLevelId) + if (!resolved) throw new Error('Choose a Site before drawing a terrain break.') + const line = terrainBreakLotLine(resolved.site, current.start, point) + const id = commitTerrainBreakCreation(sceneApi, { ...current.options, line }) + resetDraft() + selectNode(id) + finishTool() + } catch (error) { + useTerrainBreakDraft.setState({ + error: error instanceof Error ? error.message : String(error), + }) + } + }, + [sceneApi, activeLevelId, selectNode, finishTool], + ) + useEffect(() => { + if (owners++ === 0) + useInteractionScope.getState().begin({ kind: 'drafting', tool: 'terrain-break' }) + return () => { + if (--owners === 0) { + resetDraft() + useInteractionScope + .getState() + .endIf((scope) => scope.kind === 'drafting' && scope.tool === 'terrain-break') + } + } + }, []) + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if ( + isTypingTarget(event.target) || + (visibleScene(useEditor.getState()) === '2d' ? '2d' : '3d') !== view + ) + return + if (event.key === 'Escape') { + event.preventDefault() + event.stopImmediatePropagation() + markToolCancelConsumed() + resetDraft() + finishTool() + } + } + window.addEventListener('keydown', onKey, true) + return () => window.removeEventListener('keydown', onKey, true) + }, [view, finishTool]) + let line: Point[] = draft.start && draft.hover ? [draft.start, draft.hover] : [] + if (frame && draft.start && draft.hover) { + try { + line = terrainBreakLotLine(frame.site, draft.start, draft.hover) + } catch {} + } + return { draft, frame, addPoint, line } +} + +export function TerrainBreakDraftControls({ view }: { view: '2d' | '3d' }) { + const primary = useEditor((state) => (visibleScene(state) === '2d' ? '2d' : '3d')) + const draft = useTerrainBreakDraft() + if (primary !== view || typeof document === 'undefined') return null + const setOptions = (patch: Partial) => + useTerrainBreakDraft.setState((state) => ({ options: { ...state.options, ...patch } })) + const controls = ( +
+

Draw terrain break

+

+ Click two points to set the direction. The straight boundary extends across the lot. Left + and right follow that direction. +

+ +

Elevations are absolute Site metres.

+ {draft.error && ( +

+ {draft.error} +

+ )} +
+ ) + return view === '3d' ? ( + [size.width / 2, size.height / 2]} + fullscreen + style={{ pointerEvents: 'none' }} + zIndexRange={[80, 0]} + > + {controls} + + ) : ( + createPortal(controls, document.body) + ) +} diff --git a/packages/nodes/src/terrain-break/edit.test.ts b/packages/nodes/src/terrain-break/edit.test.ts new file mode 100644 index 0000000000..befe23c8a6 --- /dev/null +++ b/packages/nodes/src/terrain-break/edit.test.ts @@ -0,0 +1,170 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { + clearSceneHistory, + createSceneApi, + createTerrainField, + encodeTerrainField, + heightAt, + persistedTerrainFieldOf, + terrainBreakFacts, + useScene, +} from '@pascal-app/core' +import { type AnyNodeId, SiteNode } from '@pascal-app/core/schema' +import { + buildTerrainBreakMesh, + commitTerrainBreakCreation, + commitTerrainBreakEdit, +} from '@pascal-app/nodes' + +const ground = createTerrainField({ cols: 9, rows: 9, spacing: 1 }) +const input = { + line: [ + [4, 0], + [4, 8], + ] as [number, number][], + kind: 'cliff' as const, + left: 5, + right: 2, +} +let previous: ReturnType +let previousRaf: typeof requestAnimationFrame +let previousCancelRaf: typeof cancelAnimationFrame + +beforeEach(() => { + previous = useScene.getState() + previousRaf = globalThis.requestAnimationFrame + previousCancelRaf = globalThis.cancelAnimationFrame + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} + const site = SiteNode.parse({ + id: 'site_ui', + terrain: encodeTerrainField(ground), + polygon: { + type: 'polygon', + points: [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ], + }, + }) + useScene.setState({ + nodes: { [site.id]: site }, + rootNodeIds: [site.id], + dirtyNodes: new Set(), + readOnly: false, + }) + clearSceneHistory() +}) + +afterEach(() => { + useScene.setState(previous) + clearSceneHistory() + globalThis.requestAnimationFrame = previousRaf + globalThis.cancelAnimationFrame = previousCancelRaf +}) + +function authored(id: AnyNodeId) { + const nodes = useScene.getState().nodes + const edge = nodes[id] + const site = nodes.site_ui + if (!edge || edge.type !== 'terrain-break' || !site || site.type !== 'site') + throw new Error('Expected the committed terrain break and site') + const field = persistedTerrainFieldOf(site, nodes) + if (!field) throw new Error('Expected committed terrain authority') + return { edge, field } +} + +function faceHeights(id: AnyNodeId) { + const { edge, field } = authored(id) + const mesh = buildTerrainBreakMesh(edge, field, [ground]) + expect(mesh.indices.length).toBeGreaterThan(0) + const heights = new Set() + for (let i = 1; i < mesh.positions.length; i += 3) { + const height = mesh.positions[i] + if (height === undefined) throw new Error('Expected face vertex height') + heights.add(height) + } + return [...heights].sort((a, b) => a - b) +} + +describe('terrain-break UI commit path', () => { + test('creation updates authoritative geometry and is undone as one scene gesture', () => { + const before = JSON.stringify(useScene.getState().nodes) + const id = commitTerrainBreakCreation(createSceneApi(useScene), input) + const { edge, field } = authored(id) + expect(heightAt(field, 3, 3)).toBe(5) + expect(heightAt(field, 5, 3)).toBe(2) + expect(terrainBreakFacts(edge, field)).toMatchObject({ lengthM: 8, faceAreaM2: 24 }) + expect(faceHeights(id)).toEqual([2, 5]) + const created = JSON.stringify(useScene.getState().nodes) + useScene.temporal.getState().undo() + expect(JSON.stringify(useScene.getState().nodes)).toBe(before) + useScene.temporal.getState().redo() + expect(JSON.stringify(useScene.getState().nodes)).toBe(created) + }) + + test('an edited height changes faces and measured facts in one undo step', () => { + const sceneApi = createSceneApi(useScene) + const id = commitTerrainBreakCreation(sceneApi, input) + const before = JSON.stringify(useScene.getState().nodes) + clearSceneHistory() + const { edge } = authored(id) + commitTerrainBreakEdit(sceneApi, edge.id, { left: 7 }) + const changed = authored(id) + expect(heightAt(changed.field, 3, 3)).toBe(7) + expect(terrainBreakFacts(changed.edge, changed.field)).toMatchObject({ + left: { minM: 7, maxM: 7 }, + dropMinM: 5, + dropMaxM: 5, + faceAreaM2: 40, + }) + expect(faceHeights(id)).toEqual([2, 7]) + useScene.temporal.getState().undo() + expect(JSON.stringify(useScene.getState().nodes)).toBe(before) + expect(faceHeights(id)).toEqual([2, 5]) + }) + + test('collapsed and crossing edits do not change the scene or create undo entries', () => { + const sceneApi = createSceneApi(useScene) + const cliffId = commitTerrainBreakCreation(sceneApi, input) + const padId = commitTerrainBreakCreation(sceneApi, { + line: [ + [1, 2], + [3, 2], + [3, 6], + [1, 6], + [1, 2], + ], + kind: 'retaining', + left: 7, + right: 'ground', + }) + clearSceneHistory() + const before = JSON.stringify(useScene.getState().nodes) + const cliff = authored(cliffId).edge + const pad = authored(padId).edge + expect(() => + commitTerrainBreakEdit(sceneApi, cliff.id, { + line: [ + [4, 0], + [4, 0], + ], + }), + ).toThrow() + expect(() => + commitTerrainBreakEdit(sceneApi, pad.id, { + line: [ + [3, 2], + [5, 2], + [5, 6], + [3, 6], + [3, 2], + ], + }), + ).toThrow() + expect(JSON.stringify(useScene.getState().nodes)).toBe(before) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + }) +}) diff --git a/packages/nodes/src/terrain-break/edit.ts b/packages/nodes/src/terrain-break/edit.ts new file mode 100644 index 0000000000..03ba43b8c8 --- /dev/null +++ b/packages/nodes/src/terrain-break/edit.ts @@ -0,0 +1,67 @@ +import { + type AnyNodeId, + persistedTerrainFieldOf, + type SceneApi, + type SiteNode, + TerrainBreakNode, + terrainBreakFacts, +} from '@pascal-app/core' +import { addTerrainBreak, validateTerrainBreakPlacement } from '@pascal-app/core/agent-operations' + +type Point = [number, number] + +export function terrainBreakLotLine(site: SiteNode, start: Point, end: Point): Point[] { + const dx = end[0] - start[0] + const dz = end[1] - start[1] + if (Math.hypot(dx, dz) < 0.01) throw new Error('Choose two distinct points for the boundary.') + const cuts: number[] = [] + const ring = site.polygon.points + for (let i = 0; i < ring.length; i++) { + const a = ring[i] as Point + const b = ring[(i + 1) % ring.length] as Point + const ex = b[0] - a[0] + const ez = b[1] - a[1] + const determinant = dx * ez - dz * ex + if (Math.abs(determinant) < 1e-10) continue + const ax = a[0] - start[0] + const az = a[1] - start[1] + const u = (ax * dz - az * dx) / determinant + if (u >= 0 && u <= 1) cuts.push((ax * ez - az * ex) / determinant) + } + if (cuts.length < 2) throw new Error('Draw a boundary that crosses the lot.') + const at = (t: number): Point => [start[0] + dx * t, start[1] + dz * t] + return [at(Math.min(...cuts)), at(Math.max(...cuts))] +} + +export function commitTerrainBreakCreation( + sceneApi: SceneApi, + input: Pick, +): AnyNodeId { + if (!sceneApi.applyChanges) + throw new Error('Terrain break creation requires atomic scene changes.') + const { result, changes } = addTerrainBreak(sceneApi.nodes(), input, { activeLevelId: null }) + sceneApi.applyChanges({ + create: changes?.create?.map(({ node, parentId }) => ({ + node: TerrainBreakNode.parse(node), + parentId: parentId as AnyNodeId | undefined, + })), + }) + return result.breakId as AnyNodeId +} + +export function commitTerrainBreakEdit( + sceneApi: SceneApi, + id: TerrainBreakNode['id'], + patch: Partial, +): void { + const current = sceneApi.get(id) + if (current?.type !== 'terrain-break') throw new Error('The terrain break no longer exists.') + const candidate = TerrainBreakNode.parse({ ...current, ...patch }) + const site = candidate.parentId ? sceneApi.get(candidate.parentId as AnyNodeId) : null + if (site?.type !== 'site') throw new Error('The terrain break needs a Site.') + validateTerrainBreakPlacement(sceneApi.nodes(), site, candidate, 'context') + const field = persistedTerrainFieldOf(site, { ...sceneApi.nodes(), [id]: candidate }) + if (!field) throw new Error('The terrain break needs readable ground.') + terrainBreakFacts(candidate, field) + sceneApi.update(id, patch) +} diff --git a/packages/nodes/src/terrain-break/floorplan-tool.tsx b/packages/nodes/src/terrain-break/floorplan-tool.tsx new file mode 100644 index 0000000000..dddbf614d1 --- /dev/null +++ b/packages/nodes/src/terrain-break/floorplan-tool.tsx @@ -0,0 +1,71 @@ +'use client' + +import type { FloorplanToolContext } from '@pascal-app/editor' +import { useEffect, useRef } from 'react' +import { rampFloorplanFrame, rampPlanToSite, rampSiteToPlan } from '../ramp/edit' +import { + TerrainBreakDraftControls, + useTerrainBreakDraft, + useTerrainBreakDraftController, +} from './draft' + +export default function FloorplanTerrainBreakTool(context: FloorplanToolContext) { + const groupRef = useRef(null) + const { frame, line, addPoint } = useTerrainBreakDraftController({ ...context, view: '2d' }) + const { building } = rampFloorplanFrame( + frame?.building ?? null, + context.activeLevelId, + 'floor-plan', + ) + useEffect(() => { + const group = groupRef.current + const svg = group?.ownerSVGElement + if (!group || !svg) return + const consume = (event: Event) => { + event.preventDefault() + event.stopPropagation() + event.stopImmediatePropagation() + } + const resolve = (event: MouseEvent | PointerEvent) => { + const matrix = group.getScreenCTM() + if (!matrix) return null + const point = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix.inverse()) + return rampPlanToSite(building, [point.x, point.y]) + } + const down = (event: PointerEvent) => { + if (event.button === 0) consume(event) + } + const move = (event: PointerEvent) => { + if (event.buttons & 0b110) return + consume(event) + useTerrainBreakDraft.setState({ hover: resolve(event) }) + } + const click = (event: MouseEvent) => { + if (event.button !== 0) return + consume(event) + const point = resolve(event) + if (point) addPoint(point) + } + svg.addEventListener('pointerdown', down, true) + svg.addEventListener('pointermove', move, true) + svg.addEventListener('click', click, true) + return () => { + svg.removeEventListener('pointerdown', down, true) + svg.removeEventListener('pointermove', move, true) + svg.removeEventListener('click', click, true) + } + }, [addPoint, building]) + return ( + + rampSiteToPlan(building, point).join(',')).join(' ')} + stroke="#0284c7" + strokeWidth={2} + vectorEffect="non-scaling-stroke" + /> + + + ) +} diff --git a/packages/nodes/src/terrain-break/floorplan.ts b/packages/nodes/src/terrain-break/floorplan.ts new file mode 100644 index 0000000000..1a7e65dffb --- /dev/null +++ b/packages/nodes/src/terrain-break/floorplan.ts @@ -0,0 +1,17 @@ +import type { FloorplanGeometry, GeometryContext, TerrainBreakNode } from '@pascal-app/core' + +export function buildTerrainBreakFloorplan( + node: TerrainBreakNode, + ctx: GeometryContext, +): FloorplanGeometry { + const marked = ctx.viewState?.selected || ctx.viewState?.highlighted + return { + kind: 'polyline', + points: node.line, + fill: 'none', + stroke: marked ? (ctx.viewState?.palette?.selectedStroke ?? '#0ea5e9') : '#6f6a62', + strokeWidth: node.kind === 'retaining' ? 2.5 : 1.5, + strokeLinejoin: 'miter', + vectorEffect: 'non-scaling-stroke', + } +} diff --git a/packages/nodes/src/terrain-break/geometry.ts b/packages/nodes/src/terrain-break/geometry.ts new file mode 100644 index 0000000000..d846a31503 --- /dev/null +++ b/packages/nodes/src/terrain-break/geometry.ts @@ -0,0 +1,393 @@ +import { + type AnyNode, + type AnyNodeId, + createTerrainField, + type GeometryContext, + persistedTerrainFieldOf, + pointInPolygon2D, + type Ring, + type SiteNode, + type TerrainBreakNode, + type TerrainField, + terrainBreakSideAt, + terrainBreaksOf, + terrainTilesOf, + tileFieldOf, +} from '@pascal-app/core' +import { BufferAttribute, BufferGeometry, Group, Mesh } from 'three' +import { terrainRegionHeight } from '../site/terrain-break-split' +import type { TerrainMeshBuffers } from '../site/terrain-geometry' +import { buildTerrainGroundMesh, terrainGroundPatches } from '../site/terrain-ground' +import { terrainBreakMaterial } from './material' + +type Point = [number, number] +type Side = 'left' | 'right' + +function onEdge(point: Point, a: Point, b: Point, finite: boolean): boolean { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const length = Math.hypot(dx, dz) + if (Math.abs(dx * (point[1] - a[1]) - dz * (point[0] - a[0])) > length * 1e-5) return false + const dot = (point[0] - a[0]) * dx + (point[1] - a[1]) * dz + return !finite || (dot >= -length * 1e-5 && dot <= length * length + length * 1e-5) +} + +function authoredRightNormal(edge: TerrainBreakNode, a: Point, b: Point): Point { + for (let i = 1; i < edge.line.length; i++) { + const p = edge.line[i - 1] as Point + const q = edge.line[i] as Point + if (!onEdge(a, p, q, false) || !onEdge(b, p, q, false)) continue + const dx = q[0] - p[0] + const dz = q[1] - p[1] + const length = Math.hypot(dx, dz) + return [dz / length, -dx / length] + } + throw new Error('Terrain face segment does not lie on its authored boundary.') +} + +function clipToLot(a: Point, b: Point, polygon?: Ring): [Point, Point][] { + if (!polygon?.length) return [[a, b]] + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const cuts = [0, 1] + for (let i = 0; i < polygon.length; i++) { + const p = polygon[i] as Point + const q = polygon[(i + 1) % polygon.length] as Point + const ex = q[0] - p[0] + const ez = q[1] - p[1] + const denominator = dx * ez - dz * ex + if (Math.abs(denominator) < 1e-12) continue + const t = ((p[0] - a[0]) * ez - (p[1] - a[1]) * ex) / denominator + const u = ((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / denominator + if (t > 0 && t < 1 && u >= 0 && u <= 1) cuts.push(t) + } + cuts.sort((p, q) => p - q) + const at = (t: number): Point => [a[0] + dx * t, a[1] + dz * t] + const result: [Point, Point][] = [] + for (let i = 1; i < cuts.length; i++) { + const lo = cuts[i - 1] ?? 0 + const hi = cuts[i] ?? 1 + if (hi - lo > 1e-9 && pointInPolygon2D(at((lo + hi) / 2), polygon, { includeBoundary: true })) + result.push([at(lo), at(hi)]) + } + return result +} + +export function updateTerrainBreakMesh(buffers: TerrainMeshBuffers, field: TerrainField): void { + const breaks = buffers.terrainBreaks ?? [] + const regions = buffers.terrainBreakSides ?? [] + const order = [0, 1, 2, 2, 1, 3] + for (let i = 0; i < regions.length; i++) + buffers.positions[i * 3 + 1] = terrainRegionHeight( + field, + breaks, + regions[i] as readonly Side[], + buffers.positions[i * 3] ?? 0, + buffers.positions[i * 3 + 2] ?? 0, + ) + for (let vertex = 0; vertex < regions.length; vertex += 4) { + const a = vertex * 3 + const b = a + 3 + const dx = (buffers.positions[b] ?? 0) - (buffers.positions[a] ?? 0) + const dz = (buffers.positions[b + 2] ?? 0) - (buffers.positions[a + 2] ?? 0) + const sign = + (buffers.positions[a + 1] ?? 0) + (buffers.positions[b + 1] ?? 0) >= + (buffers.positions[a + 7] ?? 0) + (buffers.positions[a + 10] ?? 0) + ? 1 + : -1 + const nx = buffers.normals[a] ?? 0 + const nz = buffers.normals[a + 2] ?? 0 + // Preserve the authored plane direction; short Float32 edges magnify subtraction error. + const flip = sign * (nx * dz - nz * dx) < 0 ? -1 : 1 + for (let i = 0; i < 4; i++) buffers.normals.set([nx * flip, 0, nz * flip], a + i * 3) + const offset = (vertex / 4) * 6 + for (let i = 0; i < 6; i++) buffers.indices[offset + i] = vertex + (order[i] ?? 0) + } +} + +function breakAuthority(edge: TerrainBreakNode, field: TerrainField): TerrainField { + const existing = field.terrainBreaks ?? [] + const breaks = existing.some((other) => other.id === edge.id) + ? existing.map((other) => (other.id === edge.id ? edge : other)) + : terrainBreaksOf( + { id: 'site_terrain-break-mesh' }, + Object.fromEntries( + [...existing, edge].map((other) => [ + other.id, + { ...other, parentId: 'site_terrain-break-mesh' }, + ]), + ), + ) + return { ...field, terrainBreaks: breaks } +} + +/** Whether `grid`'s rectangle can hold a point of the break's line (the whole line when open). */ +function gridMeetsLine(grid: TerrainField, line: readonly Point[], closed: boolean): boolean { + const minX = grid.origin[0] + const minZ = grid.origin[1] + const maxX = minX + (grid.cols - 1) * grid.spacing + const maxZ = minZ + (grid.rows - 1) * grid.spacing + // `onEdge` takes a point within 1e-5 of its line; a millimetre is the margin. + const pad = 1e-3 + if (closed) { + let lineMinX = Number.POSITIVE_INFINITY + let lineMaxX = Number.NEGATIVE_INFINITY + let lineMinZ = Number.POSITIVE_INFINITY + let lineMaxZ = Number.NEGATIVE_INFINITY + for (const [x, z] of line) { + lineMinX = Math.min(lineMinX, x) + lineMaxX = Math.max(lineMaxX, x) + lineMinZ = Math.min(lineMinZ, z) + lineMaxZ = Math.max(lineMaxZ, z) + } + return !( + lineMaxX < minX - pad || + lineMinX > maxX + pad || + lineMaxZ < minZ - pad || + lineMinZ > maxZ + pad + ) + } + // An open break is read as an infinite line: it meets the rectangle when its corners straddle it. + const a = line[0] as Point + const b = line.at(-1) as Point + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const length = Math.hypot(dx, dz) || 1 + const side = (x: number, z: number) => (dx * (z - a[1]) - dz * (x - a[0])) / length + const corners = [side(minX, minZ), side(maxX, minZ), side(minX, maxZ), side(maxX, maxZ)] + return Math.min(...corners) <= pad && Math.max(...corners) >= -pad +} + +type SurfaceRun = { + lines: readonly (readonly Point[])[] + holes: readonly Ring[] + /** Per break, the mesh edges that lie on its line, keyed so a shared vertex pair counts once. */ + byLine: Map +} +const surfaceRuns = new WeakMap() + +const sameRefs = (a: readonly T[], b: readonly T[]) => + a.length === b.length && a.every((value, index) => value === b[index]) + +const segmentsOf = (line: readonly Point[], closed: boolean): [Point, Point][] => + closed + ? line.slice(0, -1).map((a, i) => [a, line[i + 1] as Point] as [Point, Point]) + : [[line[0] as Point, line.at(-1) as Point]] + +const isClosed = (line: readonly Point[]) => { + const first = line[0] as Point + const last = line.at(-1) as Point + return first[0] === last[0] && first[1] === last[1] +} + +/** + * The edges of a grid's ground mesh that lie on each of the field's breaks. Where the mesh's edges + * lie on a line depends on the grid, the holes and the breaks' lines, not on any height, and the + * mesh is the same for every break of the field: it is built once, however many breaks there are. + */ +function surfaceRunOf( + grid: TerrainField, + field: TerrainField, + holes: Ring[], + breakLines: readonly (readonly Point[])[], +): SurfaceRun { + const runs = surfaceRuns.get(grid) ?? [] + surfaceRuns.set(grid, runs) + const found = runs.find( + (entry) => sameRefs(entry.lines, breakLines) && sameRefs(entry.holes, holes), + ) + if (found) return found + const byLine = new Map() + // `onEdge` takes a point within 1e-5 of its line; a millimetre is the margin of the box. + const margin = 1e-3 + const candidates = breakLines + .filter((line) => gridMeetsLine(grid, line, isClosed(line))) + .map((line) => { + const closed = isClosed(line) + let minX = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let minZ = Number.POSITIVE_INFINITY + let maxZ = Number.NEGATIVE_INFINITY + // An open break is an infinite line: no box. + for (const [x, z] of line) { + minX = Math.min(minX, x) + maxX = Math.max(maxX, x) + minZ = Math.min(minZ, z) + maxZ = Math.max(maxZ, z) + } + const entries: [string, [Point, Point]][] = [] + byLine.set(line, entries) + return { line, closed, lines: segmentsOf(line, closed), minX, maxX, minZ, maxZ, entries } + }) + if (candidates.length) { + const surface = buildTerrainGroundMesh(grid, field, holes) + for (let i = 0; i < surface.indices.length; i += 3) { + for (let j = 0; j < 3; j++) { + const ai = (surface.indices[i + j] ?? 0) * 3 + const bi = (surface.indices[i + ((j + 1) % 3)] ?? 0) * 3 + let a: Point = [surface.positions[ai] ?? 0, surface.positions[ai + 2] ?? 0] + let b: Point = [surface.positions[bi] ?? 0, surface.positions[bi + 2] ?? 0] + if (Math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-7) continue + for (const candidate of candidates) { + if ( + candidate.closed && + (Math.max(a[0], b[0]) < candidate.minX - margin || + Math.min(a[0], b[0]) > candidate.maxX + margin || + Math.max(a[1], b[1]) < candidate.minZ - margin || + Math.min(a[1], b[1]) > candidate.maxZ + margin) + ) + continue + const line = candidate.lines.find( + ([p, q]) => onEdge(a, p, q, candidate.closed) && onEdge(b, p, q, candidate.closed), + ) + if (!line) continue + const [p, q] = line + if ((b[0] - a[0]) * (q[0] - p[0]) + (b[1] - a[1]) * (q[1] - p[1]) < 0) [a, b] = [b, a] + const key = [...a, ...b].map((value) => Math.round(value * 1e6)).join(':') + candidate.entries.push([key, [a, b]]) + break + } + } + } + } + const run: SurfaceRun = { lines: breakLines, holes: [...holes], byLine } + runs.push(run) + if (runs.length > 8) runs.shift() + return run +} + +function collectBreakSegments( + edge: TerrainBreakNode, + field: TerrainField, + grids: readonly TerrainField[], + holes: Ring[], +): [Point, Point][] { + const closed = isClosed(edge.line) + const segments = new Map() + const breakLines = (field.terrainBreaks ?? []).map((boundary) => boundary.line) + for (const grid of grids) { + // A grid away from the break has no edge of its mesh on it: its mesh need not be built. + if (!gridMeetsLine(grid, edge.line, closed)) continue + const run = surfaceRunOf(grid, field, holes, breakLines) + for (const [key, segment] of run.byLine.get(edge.line) ?? []) segments.set(key, segment) + } + return [...segments.values()] +} + +function emitBreakQuads( + edge: TerrainBreakNode, + field: TerrainField, + segments: readonly [Point, Point][], + polygon?: Ring, +): TerrainMeshBuffers { + const breaks = field.terrainBreaks ?? [] + const positions: number[] = [] + const normals: number[] = [] + const uvs: number[] = [] + const regions: Side[][] = [] + const targetIndex = breaks.findIndex((other) => other.id === edge.id) + for (const segment of segments) { + for (const [a, b] of clipToLot(...segment, polygon)) { + const [nx, nz] = authoredRightNormal(edge, a, b) + const mid: Point = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2] + const left = breaks.map((other) => terrainBreakSideAt(other, ...mid)) + const right = [...left] + left[targetIndex] = 'left' + right[targetIndex] = 'right' + const height = (point: Point, sides: Side[]) => + terrainRegionHeight(field, breaks, sides, ...point) + const da = height(a, left) - height(a, right) + const db = height(b, left) - height(b, right) + const cuts = da * db < 0 ? [0, da / (da - db), 1] : [0, 1] + for (let i = 1; i < cuts.length; i++) { + const at = (t: number): Point => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t] + const p = at(cuts[i - 1] ?? 0) + const q = at(cuts[i] ?? 1) + const length = Math.hypot(q[0] - p[0], q[1] - p[1]) + for (const [point, sides, u] of [ + [p, left, 0], + [q, left, length], + [p, right, 0], + [q, right, length], + ] as const) { + positions.push(point[0], 0, point[1]) + normals.push(nx, 0, nz) + uvs.push(u, height(point, sides)) + regions.push(sides) + } + } + } + } + return { + positions: Float32Array.from(positions), + normals: Float32Array.from(normals), + uvs: Float32Array.from(uvs), + indices: new Uint32Array((regions.length / 4) * 6), + terrainBreaks: breaks, + terrainBreakSides: regions, + } +} + +export function buildTerrainBreakMesh( + edge: TerrainBreakNode, + field: TerrainField, + grids: readonly TerrainField[] = [field], + holes: Ring[] = [], + polygon?: Ring, +): TerrainMeshBuffers { + const authority = breakAuthority(edge, field) + const segments = collectBreakSegments(edge, authority, grids, holes) + const buffers = emitBreakQuads(edge, authority, segments, polygon) + updateTerrainBreakMesh(buffers, authority) + return buffers +} + +export function terrainBreakSources(site: SiteNode, nodes: Readonly>) { + const tiles = terrainTilesOf(site, nodes) + return [ + ...terrainGroundPatches(site, tiles), + ...tiles.flatMap((tile) => { + const grid = tileFieldOf(tile) + return grid ? [{ key: tile.id, grid, holes: [] as Ring[] }] : [] + }), + ] +} + +export function buildTerrainBreakGeometry(edge: TerrainBreakNode, ctx?: GeometryContext): Group { + const group = new Group() + const site = ctx?.parent?.type === 'site' ? ctx.parent : null + const nodes: Record = { [edge.id]: edge } + if (site) { + nodes[site.id] = site + for (const id of site.children ?? []) { + const child = ctx?.resolve(id as AnyNodeId) + if (child) nodes[id] = child + } + } + const field = site ? persistedTerrainFieldOf(site, nodes) : createTerrainField() + if (!field) return group + const sources = site ? terrainBreakSources(site, nodes) : [{ grid: field, holes: [] }] + let material: ReturnType | undefined + for (const source of sources) { + const buffers = buildTerrainBreakMesh( + edge, + field, + [source.grid], + source.holes, + site?.polygon.points, + ) + if (!buffers.indices.length) continue + material ??= terrainBreakMaterial(edge.kind) + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(buffers.positions, 3)) + geometry.setAttribute('normal', new BufferAttribute(buffers.normals, 3)) + geometry.setAttribute('uv', new BufferAttribute(buffers.uvs, 2)) + geometry.setIndex(new BufferAttribute(buffers.indices, 1)) + const mesh = new Mesh(geometry, material) + mesh.name = 'terrain-break-face' + mesh.castShadow = true + mesh.receiveShadow = true + group.add(mesh) + } + return group +} diff --git a/packages/nodes/src/terrain-break/material.ts b/packages/nodes/src/terrain-break/material.ts new file mode 100644 index 0000000000..66461420d4 --- /dev/null +++ b/packages/nodes/src/terrain-break/material.ts @@ -0,0 +1,16 @@ +import { DoubleSide } from 'three' +import { MeshStandardNodeMaterial } from 'three/webgpu' +import { rockColorNode } from '../rock/material' + +const FACE_COLOR = { cliff: '#a49d90', retaining: '#939089', soil: '#7a6248' } as const + +export function terrainBreakMaterial(kind: 'cliff' | 'retaining' | 'soil') { + const material = new MeshStandardNodeMaterial({ + color: FACE_COLOR[kind], + roughness: kind === 'soil' ? 0.98 : 0.92, + metalness: 0, + side: DoubleSide, + }) + if (kind === 'cliff') material.colorNode = rockColorNode({ strata: true, lichen: 0 }) + return material +} diff --git a/packages/nodes/src/terrain-break/options.tsx b/packages/nodes/src/terrain-break/options.tsx new file mode 100644 index 0000000000..437adee8f3 --- /dev/null +++ b/packages/nodes/src/terrain-break/options.tsx @@ -0,0 +1,57 @@ +'use client' + +import type { TerrainBreakNode } from '@pascal-app/core' +import { RampNumberField } from '../ramp/number-field' + +type Options = Pick + +export function TerrainBreakOptions({ + value, + onChange, +}: { + value: Options + onChange: (patch: Partial) => void +}) { + return ( +
+ + {(['left', 'right'] as const).map((side) => ( +
+ + {typeof value[side] === 'number' && ( + onChange({ [side]: height })} + value={value[side] as number} + /> + )} +
+ ))} +
+ ) +} diff --git a/packages/nodes/src/terrain-break/panel.tsx b/packages/nodes/src/terrain-break/panel.tsx new file mode 100644 index 0000000000..9972c98bd3 --- /dev/null +++ b/packages/nodes/src/terrain-break/panel.tsx @@ -0,0 +1,87 @@ +'use client' + +import { + createSceneApi, + persistedTerrainFieldOf, + type TerrainBreakNode, + terrainBreakFacts, + useScene, +} from '@pascal-app/core' +import { PanelSection, PanelWrapper } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { useCallback, useEffect, useMemo, useState } from 'react' +import { commitTerrainBreakEdit } from './edit' +import { TerrainBreakOptions } from './options' + +export default function TerrainBreakPanel({ node }: { node: TerrainBreakNode }) { + const sceneApi = useMemo(() => createSceneApi(useScene), []) + const [error, setError] = useState(null) + const [line, setLine] = useState(JSON.stringify(node.line)) + useEffect(() => setLine(JSON.stringify(node.line)), [node.line]) + const nodes = useScene((state) => state.nodes) + const site = node.parentId ? nodes[node.parentId as keyof typeof nodes] : null + const field = site?.type === 'site' ? persistedTerrainFieldOf(site, nodes) : null + const facts = field ? terrainBreakFacts(node, field) : null + const commit = useCallback( + (patch: Partial) => { + try { + commitTerrainBreakEdit(sceneApi, node.id, patch) + setError(null) + } catch (error) { + setError(error instanceof Error ? error.message : String(error)) + } + }, + [sceneApi, node.id], + ) + return ( + useViewer.getState().setSelection({ selectedIds: [] })} + title="Terrain break" + width={320} + > + {error && ( +

+ {error} +

+ )} + + +

+ Absolute Site elevations in metres. Looking along the line, left is to your left. A closed + counterclockwise ring has its inside on the left. Keep ground never blends across the + boundary. +

+
+ +