Fix pass: walkthrough, deck-coupled wall items, live-preview elevation, room snap modes, import validation (#537)

* fix(core): elect wall slab support from the carrying profile, not face coverage

An elevated deck drawn against a house wall covers the wall's outer face
line end-to-end (boundary contact counts), so the max-across-polylines
election handed the wall origin to the deck: every wall-hosted window/door
rode along whenever the deck height changed, and placement local-Y was
clamped above the deck top. Elect from the carrying profile instead (per
arc segment: highest support per face, min across supported faces), with
the pointer cap applied inside the profile so a capped-away deck still
falls back to the floor that carries the wall. Also pass curveOffset/
thickness/supportSlabId at the window/door tool query sites so their
cursor agrees with the rendered wall frame.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(core): honor live node overrides in spatial-grid support queries

Group drags publish translated slab polygons and wall endpoints to
useLiveNodeOverrides only; the committed spatial index made floor items
and walls re-elect support against the pre-drag slab footprint, so
multi-selection moves and room-preset placement jumped vertically until
the validating click committed the batch. Support queries now read
live-effective slab/wall records and bypass the rendered-polygon cache
while a slab or wall on the level has an override; the committed cached
path stays the fast path otherwise.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): give the room-preset stamp tool a polygon snap context

The host app's room stamp drives placement with tool='room', which has no
registry entry, so snapContextOf resolved null: Shift never cycled the
snapping mode and the HUD chip stayed hidden during room preset placement.
A tool-level context map hands the stamp the no-angle polygon set.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): only synthesize walkthrough fallback floors for ground levels

Every slab-less visible level got a >=30x30m opening-free fallback floor
box at its elevation, so a walkthrough spawned on an upper level (the
no-spawn-node fallback ray picks the highest surface) stood on a phantom
plane it could never descend from. Match the baked-GLB viewer policy:
only the lowest level of each building (derived baseY === 0) gets the
fallback; upper levels rely on their real slabs, whose stair openings
are cut into the geometry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(core): fold useLiveTransforms slab deltas into support queries

The slab move tool and the room-preset stamp publish a translation DELTA
to useLiveTransforms (no polygon override), so the spatial index still
elected support against the slab's committed footprint: furniture riding
a room-preset preview (or sitting on a dragged deck) dropped to ground
under the visually-moved deck until the validating click. Effective slab
records now apply the live delta to polygon/holes/elevation, mapped
exactly once at each query's loop entry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(viewer): reapply floor lift every frame for nodes with live previews

FloorElevationSystem only wrote mesh Y for dirty nodes, but the React
commit that rebinds a dragged node's base-Y group position can land
between frames, after priority-2 systems consumed the dirty mark — the
lift then vanished until the next pointer tick re-dirtied the node,
blinking the Y of items dragged over elevated slabs. Nodes holding a
live override or transform now get the lift reapplied every frame.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): stop the entry camera swap from insta-cancelling walkthrough

Entering walkthrough with a persisted orthographic camera swaps it to
perspective, which recreates the interaction callbacks and re-ran the
pointer-lock effect: its cleanup called exitPointerLock, and the unlock
handler read that as "user left walkthrough" — instantly cancelling the
fresh entry and arming the browser's ~1.25s re-lock cooldown (hence
needing multiple button presses). The effect is now mount-stable (the
changing callback rides a ref, deps down to [gl]), and the entry lock
request swallows async cooldown rejections like the P-resume path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(core): don't block build-JSON import over plugin-node children

Exports from projects with plugins carry nodes like trees:tree whose ids
sit in level.children; the import validator parsed parents against the
static children id union, so one tree id hard-failed the level schema and
blocked the whole import — while the same data loads fine from the DB
(setScene never runs this gate). Parents are now validated against a copy
with non-static-schema child ids filtered out; those nodes keep surfacing
through the unknown-types warning and the imported payload is unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(core): treat registered plugin kinds as first-class in import validation

Nodes of runtime-registered plugin kinds (trees:tree, trees:grass) were
lumped into the unknown-types warning even when the plugin is loaded.
The validator now consults the node registry: registered kinds validate
against their own registered schema (corrupt plugin nodes still block),
count under stats.pluginTypes, and raise no warning — only genuinely
unregistered types do, which stays correct for hosts without the plugin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: appease biome (format + forEach block body)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Wassim SAMAD
2026-07-23 14:31:09 -04:00
committed by GitHub
co-authored by Claude Fable 5
parent c3659acdf8
commit f6d28f6794
19 changed files with 688 additions and 87 deletions
@@ -0,0 +1,150 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import type { AnyNode, SlabNode } from '../../schema'
import useLiveNodeOverrides from '../../store/use-live-node-overrides'
import useLiveTransforms from '../../store/use-live-transforms'
import useScene from '../../store/use-scene'
import { spatialGridManager } from './spatial-grid-manager'
// Group drags publish translated slab polygons/elevations to
// `useLiveNodeOverrides` only — the scene store (and thus the manager's
// committed index) doesn't change until the validating click. Support
// queries must honor those live records, otherwise items and walls
// re-elect against the pre-drag footprint and jump to ground mid-preview.
const LEVEL_ID = 'level_test'
const SQUARE: Array<[number, number]> = [
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
]
function makeLevel(children: string[] = []): AnyNode {
return {
id: LEVEL_ID,
type: 'level',
object: 'node',
parentId: null,
visible: true,
metadata: {},
children,
level: 0,
} as AnyNode
}
function makeSlab(
id: string,
polygon: Array<[number, number]>,
elevation: number,
overrides: Partial<SlabNode> = {},
): SlabNode {
return {
id,
type: 'slab',
object: 'node',
parentId: LEVEL_ID,
visible: true,
metadata: {},
children: [],
polygon,
holes: [],
holeMetadata: [],
elevation,
autoFromWalls: false,
...overrides,
} as SlabNode
}
const ITEM_DIMENSIONS: [number, number, number] = [0.5, 0.5, 0.5]
const NO_ROTATION: [number, number, number] = [0, 0, 0]
const itemSupportAt = (x: number, z: number) =>
spatialGridManager.getSlabSupportForItem(LEVEL_ID, [x, 0, z], ITEM_DIMENSIONS, NO_ROTATION)
describe('support queries honor live node overrides', () => {
beforeEach(() => {
spatialGridManager.clear()
useLiveNodeOverrides.getState().clearAll()
useLiveTransforms.getState().clearAll()
const deck = makeSlab('slab_deck', SQUARE, 0.5)
useScene.setState({ nodes: { [LEVEL_ID]: makeLevel([deck.id]), [deck.id]: deck } as never })
spatialGridManager.handleNodeCreated(deck as AnyNode, LEVEL_ID)
})
afterEach(() => {
useLiveNodeOverrides.getState().clearAll()
useLiveTransforms.getState().clearAll()
useScene.setState({ nodes: {} })
spatialGridManager.clear()
})
test('an item over a live-translated deck keeps electing it at the moved footprint', () => {
// Prime the committed rendered-polygon cache before the drag starts.
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
const translated = SQUARE.map(([x, z]) => [x + 10, z]) as Array<[number, number]>
useLiveNodeOverrides.getState().set('slab_deck', { polygon: translated })
// The moved footprint elects the deck; the vacated one no longer does.
expect(itemSupportAt(10, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0, slabId: null })
// Release/cancel: committed data wins again (cached fast path).
useLiveNodeOverrides.getState().clearAll()
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
expect(itemSupportAt(10, 0)).toEqual({ elevation: 0, slabId: null })
})
test('a live elevation change is visible to item and host queries', () => {
useLiveNodeOverrides.getState().set('slab_deck', { elevation: 1.2 })
expect(itemSupportAt(0, 0)).toEqual({ elevation: 1.2, slabId: 'slab_deck' })
expect(
spatialGridManager.getHostSlabElevationForFootprint(
LEVEL_ID,
'slab_deck',
[0, 0, 0],
ITEM_DIMENSIONS,
NO_ROTATION,
),
).toBeCloseTo(1.2)
useLiveNodeOverrides.getState().clearAll()
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
})
test('a deck translated via a useLiveTransforms delta supports items at the moved spot', () => {
// The slab move tool and the room-preset stamp publish a translation
// DELTA to useLiveTransforms (no polygon override) — the mesh moves but
// the committed polygon stays put, so furniture riding the preview used
// to elect ground and render under the deck until the validating click.
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
useLiveTransforms.getState().set('slab_deck', { position: [10, 0, 0], rotation: 0 })
expect(itemSupportAt(10, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0, slabId: null })
expect(
spatialGridManager.getSlabSupportForWall(LEVEL_ID, [9.5, 0], [10.5, 0]).elevation,
).toBeCloseTo(0.5)
useLiveTransforms.getState().clearAll()
expect(itemSupportAt(0, 0)).toEqual({ elevation: 0.5, slabId: 'slab_deck' })
expect(itemSupportAt(10, 0)).toEqual({ elevation: 0, slabId: null })
})
test('wall support follows a live-translated deck', () => {
const committed = spatialGridManager.getSlabSupportForWall(LEVEL_ID, [-0.5, 0], [0.5, 0])
expect(committed.elevation).toBeCloseTo(0.5)
const translated = SQUARE.map(([x, z]) => [x + 10, z]) as Array<[number, number]>
useLiveNodeOverrides.getState().set('slab_deck', { polygon: translated })
const moved = spatialGridManager.getSlabSupportForWall(LEVEL_ID, [9.5, 0], [10.5, 0])
expect(moved.elevation).toBeCloseTo(0.5)
expect(moved.electedSlabId).toBe('slab_deck')
const vacated = spatialGridManager.getSlabSupportForWall(LEVEL_ID, [-0.5, 0], [0.5, 0])
expect(vacated.elevation).toBe(0)
})
})
@@ -1,8 +1,10 @@
import { getRenderableSlabPolygon } from '../../lib/slab-polygon'
import { nodeRegistry } from '../../registry'
import type { AnyNode, CeilingNode, ItemNode, SlabNode, WallNode } from '../../schema'
import type { AnyNode, AnyNodeId, CeilingNode, ItemNode, SlabNode, WallNode } from '../../schema'
import { getScaledDimensions, isLowProfileItemSurface } from '../../schema'
import { getWallPlaneTop } from '../../services/storey'
import useLiveNodeOverrides, { getEffectiveNode } from '../../store/use-live-node-overrides'
import useLiveTransforms from '../../store/use-live-transforms'
import useScene from '../../store/use-scene'
import {
computeWallSlabSupport,
@@ -407,19 +409,79 @@ export class SpatialGridManager {
for (const slabId of slabMap.keys()) this.renderedSlabPolygons.delete(slabId)
}
/**
* True while a slab or wall on `levelId` has a live preview: group drags
* publish translated slab polygons and wall endpoints to
* `useLiveNodeOverrides`, and the slab move tool / room-preset stamp
* publish a translation DELTA to `useLiveTransforms` — either way the
* scene store commits only on release, so the committed cache and index
* would elect support against pre-drag footprints (items and walls
* visibly drop to ground mid-preview). Support queries then read
* live-effective records and skip the rendered-polygon cache.
*/
private levelHasLivePreview(levelId: string): boolean {
const nodes = useScene.getState().nodes
const structuralOnLevel = (id: string) => {
const node = nodes[id as AnyNodeId]
if (!node || (node.type !== 'slab' && node.type !== 'wall')) return false
return resolveNodeLevelId(node, nodes) === levelId
}
const overrides = useLiveNodeOverrides.getState().overrides
for (const id of overrides.keys()) {
if (structuralOnLevel(id)) return true
}
const transforms = useLiveTransforms.getState().transforms
for (const id of transforms.keys()) {
if (structuralOnLevel(id)) return true
}
return false
}
/**
* The live-effective slab record: field overrides merged, then the
* `useLiveTransforms` DELTA (slab publishers — move tool, room-preset
* stamp — store a translation, not an absolute position) applied to the
* polygon, holes, and elevation. Mapping happens exactly ONCE at each
* public query's loop entry: `slabSupportsFootprint` /
* `getRenderedSlabPolygon` take the already-effective record and must
* never re-map, or the delta would apply twice.
*/
private effectiveSlabRecord(slab: SlabNode): SlabNode {
let effective = getEffectiveNode(slab)
const live = useLiveTransforms.getState().get(slab.id)
if (live) {
const [dx, dy, dz] = live.position
if (dx !== 0 || dy !== 0 || dz !== 0) {
effective = {
...effective,
polygon: effective.polygon.map(([x, z]) => [x + dx, z + dz] as [number, number]),
holes: (effective.holes || []).map((hole) =>
hole.map(([x, z]) => [x + dx, z + dz] as [number, number]),
),
elevation: (effective.elevation ?? 0.05) + dy,
}
}
}
return effective
}
private getRenderedSlabPolygon(levelId: string, slab: SlabNode): Array<[number, number]> {
const cached = this.renderedSlabPolygons.get(slab.id)
if (cached) return cached
const live = this.levelHasLivePreview(levelId)
if (!live) {
const cached = this.renderedSlabPolygons.get(slab.id)
if (cached) return cached
}
const siblingSlabs: SlabNode[] = []
for (const other of this.getSlabMap(levelId).values()) {
if (other.id !== slab.id) siblingSlabs.push(other)
if (other.id !== slab.id) siblingSlabs.push(live ? this.effectiveSlabRecord(other) : other)
}
const walls = this.getLevelWallNodes(levelId)
const polygon = getRenderableSlabPolygon(slab, {
walls: this.getLevelWallNodes(levelId),
walls: live ? walls.map((wall) => getEffectiveNode(wall)) : walls,
siblingSlabs,
})
this.renderedSlabPolygons.set(slab.id, polygon)
if (!live) this.renderedSlabPolygons.set(slab.id, polygon)
return polygon
}
@@ -774,7 +836,8 @@ export class SpatialGridManager {
if (!slabMap) return 0
let maxElevation = 0
for (const slab of slabMap.values()) {
for (const stored of slabMap.values()) {
const slab = this.effectiveSlabRecord(stored)
if (slab.polygon.length >= 3 && pointInPolygon(x, z, slab.polygon)) {
// Check if point is in any hole
let inHole = false
@@ -836,7 +899,8 @@ export class SpatialGridManager {
let winningElevation = Number.NEGATIVE_INFINITY
let winnerId: string | null = null
for (const slab of slabMap.values()) {
for (const stored of slabMap.values()) {
const slab = this.effectiveSlabRecord(stored)
const elevation = slab.elevation ?? 0.05
if (maxElevation != null && elevation > maxElevation + SUPPORT_ELEVATION_EPSILON) continue
if (!this.slabSupportsFootprint(levelId, slab, position, dimensions, rotation)) continue
@@ -873,7 +937,8 @@ export class SpatialGridManager {
let best: { t: number; elevation: number; slabId: string } | null = null
if (slabMap) {
for (const slab of slabMap.values()) {
for (const stored of slabMap.values()) {
const slab = this.effectiveSlabRecord(stored)
if (slab.polygon.length < 3) continue
const elevation = slab.elevation ?? 0.05
const t = (elevation - oy) / dy
@@ -925,7 +990,8 @@ export class SpatialGridManager {
if (!slabMap) return []
const candidates: SlabSupportCandidate[] = []
for (const slab of slabMap.values()) {
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 })
}
@@ -951,8 +1017,9 @@ export class SpatialGridManager {
dimensions: [number, number, number],
rotation: [number, number, number],
): number | null {
const slab = this.slabsByLevel.get(levelId)?.get(slabId)
if (!slab) return 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
}
@@ -997,8 +1064,8 @@ export class SpatialGridManager {
return computeWallSlabSupport(
{ start, end, curveOffset, thickness },
[...slabMap.values()],
this.getLevelWallNodes(levelId),
[...slabMap.values()].map((slab) => this.effectiveSlabRecord(slab)),
this.getLevelWallNodes(levelId).map((wall) => getEffectiveNode(wall)),
preferredSlabId,
maxElevation,
)
@@ -133,6 +133,46 @@ describe('computeWallSlabElevation', () => {
expect(computeWallSlabElevation(wallLike, [grounded], [bandWall])).toBeCloseTo(0.1)
})
it('keeps a house wall on its floor when an elevated deck abuts the outer face', () => {
// Regression: a deck drawn against the wall covers the outer face line
// end-to-end (boundary contact counts), so the old max-across-polylines
// election handed the wall origin to the deck — every wall-hosted
// window/door rode along whenever the deck height changed. The carrying
// profile (min across supported faces) must stay on the interior floor.
const walls = [
parseWall([0, 0], [4, 0]),
parseWall([4, 0], [4, 4]),
parseWall([4, 4], [0, 4]),
parseWall([0, 4], [0, 0]),
]
const floor = SlabNode.parse({ polygon: SLAB, elevation: 0.05, thickness: 0.05 })
const houseWall = walls[0]!
const wallLike = {
start: houseWall.start,
end: houseWall.end,
thickness: houseWall.thickness,
}
for (const deckElevation of [1, 2]) {
const deck = SlabNode.parse({
polygon: [
[0, 0],
[4, 0],
[4, -3],
[0, -3],
],
elevation: deckElevation,
})
const support = computeWallSlabSupport(wallLike, [floor, deck], walls)
expect(support.elevation).toBeCloseTo(0.05)
expect(support.electedSlabId).toBe(floor.id)
expect(support.baseElevation).toBeCloseTo(0.05)
for (const segment of support.baseSegments) {
expect(segment.elevation).toBeCloseTo(0.05)
}
}
})
it('lifts a wall whose body a legacy stored polygon falls short of', () => {
// Legacy hand-adjusted slab: edges 6cm inside the wall centerlines —
// 1cm short of even the inner faces, so the STORED polygon never
+102 -58
View File
@@ -448,10 +448,14 @@ const WALL_SLAB_ELEVATION_POOL_EPSILON = 1e-4
* than `WALL_SLAB_MIN_OVERLAP` of the wall is ignored entirely (point
* contact, endpoint grazes).
*
* Same-elevation slabs pool their coverage. `elevation` preserves the
* existing wall-relative origin: the highest elevation covering at
* least `WALL_SLAB_SUPPORT_MAJORITY` of the wall, or the best-covered
* elevation when none reaches majority. `baseElevation` only fills down
* Same-elevation slabs pool their coverage. `elevation` is elected from
* the wall's carrying profile: per arc segment, the highest support on
* each face, then the min across supported faces — so a slab that only
* brushes one face (e.g. an elevated deck adjacent along the outer face)
* never lifts the wall origin. The highest carrying elevation covering
* at least `WALL_SLAB_SUPPORT_MAJORITY` of the wall wins, or the
* best-covered carrying elevation when none reaches majority.
* `baseElevation` only fills down
* where a lower support remains exposed on a wall face after higher,
* overlapping support is accounted for. Coincident floor/platform slabs
* therefore keep the wall on the platform, while slabs on opposite wall
@@ -560,58 +564,13 @@ export function computeWallSlabSupport(
}
type EvaluatedGroup = ElevationGroup & {
coverage: number
mergedPerPolyline: LengthInterval[][]
}
const evaluatedGroups: EvaluatedGroup[] = groups.map((group) => {
let coverage = 0
const mergedPerPolyline = group.perPolyline.map(mergeIntervals)
for (let i = 0; i < group.perPolyline.length; i++) {
const lineLength = polylineLengths[i]!
if (lineLength < 1e-9) continue
coverage = Math.max(coverage, intervalsLength(mergedPerPolyline[i]!) / lineLength)
}
return { ...group, coverage, mergedPerPolyline }
})
const evaluatedGroups: EvaluatedGroup[] = groups.map((group) => ({
...group,
mergedPerPolyline: group.perPolyline.map(mergeIntervals),
}))
const electableGroups =
maxElevation == null
? evaluatedGroups
: evaluatedGroups.filter(
(group) => group.elevation <= maxElevation + SUPPORT_ELEVATION_EPSILON,
)
let majorityElevation = Number.NEGATIVE_INFINITY
let bestElevation = Number.NEGATIVE_INFINITY
let bestCoverage = -1
for (const group of electableGroups) {
if (group.coverage >= WALL_SLAB_SUPPORT_MAJORITY - 1e-6) {
majorityElevation = Math.max(majorityElevation, group.elevation)
}
if (
group.coverage > bestCoverage + 1e-6 ||
(Math.abs(group.coverage - bestCoverage) <= 1e-6 && group.elevation > bestElevation)
) {
bestCoverage = group.coverage
bestElevation = group.elevation
}
}
const elevation =
preferredElevation !== null
? preferredElevation
: majorityElevation !== Number.NEGATIVE_INFINITY
? majorityElevation
: bestElevation === Number.NEGATIVE_INFINITY
? 0
: bestElevation
const electedSlabId =
preferredElectedSlabId ??
electableGroups
.find((group) => Math.abs(group.elevation - elevation) <= WALL_SLAB_ELEVATION_POOL_EPSILON)
?.slabIds.slice()
.sort()[0] ??
null
const normalizedIntervals = (group: EvaluatedGroup, polylineIndex: number) => {
const lineLength = polylineLengths[polylineIndex]!
if (lineLength < 1e-9) return []
@@ -638,9 +597,9 @@ export function computeWallSlabSupport(
(value, index) => index === 0 || value - breakpoints[index - 1]! > 1e-7,
)
const highestAt = (polylineIndex: number, t: number) => {
const highestAt = (groupList: typeof normalizedByGroup, polylineIndex: number, t: number) => {
let highest = Number.NEGATIVE_INFINITY
for (const group of normalizedByGroup) {
for (const group of groupList) {
if (
group.perPolyline[polylineIndex]?.some(
([intervalStart, intervalEnd]) => t >= intervalStart - 1e-7 && t <= intervalEnd + 1e-7,
@@ -652,17 +611,66 @@ export function computeWallSlabSupport(
return highest
}
// The pointer cap filters the ELECTION's carrying profile, not the base
// profile: with a deck capped away, the floor that also carries the wall
// must still win (geometry fill-down stays uncapped).
const electableNormalizedGroups =
maxElevation == null
? normalizedByGroup
: normalizedByGroup.filter(
(group) => group.elevation <= maxElevation + SUPPORT_ELEVATION_EPSILON,
)
const baseSegments: WallSlabSupportSegment[] = []
type CarryCandidate = { elevation: number; length: number }
const carryCandidates: CarryCandidate[] = []
const accumulateCarry = (elevation: number, length: number) => {
let candidate = carryCandidates.find(
(existing) => Math.abs(existing.elevation - elevation) <= WALL_SLAB_ELEVATION_POOL_EPSILON,
)
if (!candidate) {
candidate = { elevation, length: 0 }
carryCandidates.push(candidate)
}
candidate.length += length
}
for (let index = 1; index < uniqueBreakpoints.length; index++) {
const start = uniqueBreakpoints[index - 1]!
const end = uniqueBreakpoints[index]!
if (end - start < 1e-7) continue
const midpoint = (start + end) / 2
const leftElevation = polylines.length >= 3 ? highestAt(1, midpoint) : Number.NEGATIVE_INFINITY
const rightElevation = polylines.length >= 3 ? highestAt(2, midpoint) : Number.NEGATIVE_INFINITY
const centerElevation = highestAt(normalizedByGroup, 0, midpoint)
const leftElevation =
polylines.length >= 3 ? highestAt(normalizedByGroup, 1, midpoint) : Number.NEGATIVE_INFINITY
const rightElevation =
polylines.length >= 3 ? highestAt(normalizedByGroup, 2, midpoint) : Number.NEGATIVE_INFINITY
const faceElevations = [leftElevation, rightElevation].filter(Number.isFinite)
const segmentElevation =
faceElevations.length > 0 ? Math.min(...faceElevations) : Math.max(highestAt(0, midpoint), 0)
faceElevations.length > 0 ? Math.min(...faceElevations) : Math.max(centerElevation, 0)
if (electableNormalizedGroups === normalizedByGroup) {
if (faceElevations.length > 0 || Number.isFinite(centerElevation)) {
accumulateCarry(segmentElevation, end - start)
}
} else {
const electCenter = highestAt(electableNormalizedGroups, 0, midpoint)
const electLeft =
polylines.length >= 3
? highestAt(electableNormalizedGroups, 1, midpoint)
: Number.NEGATIVE_INFINITY
const electRight =
polylines.length >= 3
? highestAt(electableNormalizedGroups, 2, midpoint)
: Number.NEGATIVE_INFINITY
const electFaces = [electLeft, electRight].filter(Number.isFinite)
if (electFaces.length > 0 || Number.isFinite(electCenter)) {
accumulateCarry(
electFaces.length > 0 ? Math.min(...electFaces) : Math.max(electCenter, 0),
end - start,
)
}
}
const previous = baseSegments[baseSegments.length - 1]
if (
previous &&
@@ -674,6 +682,42 @@ export function computeWallSlabSupport(
}
}
let majorityElevation = Number.NEGATIVE_INFINITY
let bestElevation = Number.NEGATIVE_INFINITY
let bestCoverage = -1
for (const candidate of carryCandidates) {
if (candidate.length >= WALL_SLAB_SUPPORT_MAJORITY - 1e-6) {
majorityElevation = Math.max(majorityElevation, candidate.elevation)
}
if (
candidate.length > bestCoverage + 1e-6 ||
(Math.abs(candidate.length - bestCoverage) <= 1e-6 && candidate.elevation > bestElevation)
) {
bestCoverage = candidate.length
bestElevation = candidate.elevation
}
}
const elevation =
preferredElevation !== null
? preferredElevation
: majorityElevation !== Number.NEGATIVE_INFINITY
? majorityElevation
: bestElevation === Number.NEGATIVE_INFINITY
? 0
: bestElevation
const electedSlabId =
preferredElectedSlabId ??
evaluatedGroups
.filter(
(group) =>
maxElevation == null || group.elevation <= maxElevation + SUPPORT_ELEVATION_EPSILON,
)
.find((group) => Math.abs(group.elevation - elevation) <= WALL_SLAB_ELEVATION_POOL_EPSILON)
?.slabIds.slice()
.sort()[0] ??
null
if (baseSegments.length === 0) baseSegments.push({ start: 0, end: 1, elevation })
const baseElevation = Math.min(...baseSegments.map((segment) => segment.elevation))
return { elevation, electedSlabId, baseElevation, baseSegments }
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { z } from 'zod'
import { nodeRegistry, registerNode } from '../registry'
import type { AnyNodeDefinition } from '../registry/types'
import { LevelNode, WallNode } from '../schema'
import { validateBuildJson } from './validate-build-json'
function makeScene() {
const wall = WallNode.parse({
id: 'wall_test1',
parentId: 'level_test',
start: [0, 0],
end: [4, 0],
thickness: 0.1,
})
const level = LevelNode.parse({
id: 'level_test',
level: 0,
children: [wall.id],
})
return {
nodes: { [level.id]: level, [wall.id]: wall } as Record<string, unknown>,
rootNodeIds: [level.id],
}
}
describe('validateBuildJson', () => {
test('accepts a minimal valid scene', () => {
const result = validateBuildJson(makeScene())
expect(result.ok).toBe(true)
expect(result.schemaIssueCount).toBe(0)
})
test('plugin-typed children do not hard-fail their parent level', () => {
// Exports from projects with plugins carry nodes like `trees:tree`
// whose ids sit in level.children. The static children id union would
// reject them, but the scene store loads them fine (same data
// round-trips through the DB) — they must only surface as the
// unknown-types warning, never as an import-blocking schema error.
const scene = makeScene()
const level = scene.nodes.level_test as { children: string[] }
scene.nodes.tree_plugin1 = {
id: 'tree_plugin1',
type: 'trees:tree',
object: 'node',
parentId: 'level_test',
visible: true,
metadata: {},
children: [],
position: [1, 0, 1],
}
level.children = [...level.children, 'tree_plugin1']
const result = validateBuildJson(scene)
expect(result.ok).toBe(true)
expect(result.schemaIssueCount).toBe(0)
expect(result.warnings.some((w) => w.code === 'unknown_types')).toBe(true)
// The parsed payload keeps the plugin child — only validation filters it.
const parsedLevel = result.parsed?.nodes.level_test as { children: string[] }
expect(parsedLevel.children).toContain('tree_plugin1')
})
test('a genuinely malformed known-type node still blocks import', () => {
const scene = makeScene()
;(scene.nodes.wall_test1 as { start: unknown }).start = 'not-a-point'
const result = validateBuildJson(scene)
expect(result.ok).toBe(false)
expect(result.schemaIssueCount).toBe(1)
expect(result.schemaIssues[0]?.nodeId).toBe('wall_test1')
})
})
describe('validateBuildJson with registered plugin kinds', () => {
const sceneWithTree = (position: unknown) => {
const scene = makeScene()
const level = scene.nodes.level_test as { children: string[] }
scene.nodes.tree_plugin1 = {
id: 'tree_plugin1',
type: 'trees:tree',
object: 'node',
parentId: 'level_test',
visible: true,
metadata: {},
children: [],
position,
}
level.children = [...level.children, 'tree_plugin1']
return scene
}
beforeEach(() => {
nodeRegistry._reset()
registerNode({
kind: 'trees:tree',
schemaVersion: 1,
schema: z.looseObject({
id: z.string(),
type: z.literal('trees:tree'),
position: z.tuple([z.number(), z.number(), z.number()]),
}),
category: 'utility',
defaults: () => ({}),
capabilities: {},
} as unknown as AnyNodeDefinition)
})
afterEach(() => {
nodeRegistry._reset()
})
test('a registered plugin kind is first-class: no unknown-types warning', () => {
const result = validateBuildJson(sceneWithTree([1, 0, 1]))
expect(result.ok).toBe(true)
expect(result.schemaIssueCount).toBe(0)
expect(result.warnings.some((w) => w.code === 'unknown_types')).toBe(false)
expect(result.stats.pluginTypes['trees:tree']).toBe(1)
expect(result.stats.unknownTypes).toEqual({})
})
test('a corrupt registered plugin node is caught by its own schema', () => {
const result = validateBuildJson(sceneWithTree('not-a-position'))
expect(result.ok).toBe(false)
expect(result.schemaIssueCount).toBe(1)
expect(result.schemaIssues[0]?.nodeId).toBe('tree_plugin1')
expect(result.schemaIssues[0]?.nodeType).toBe('trees:tree')
})
})
@@ -1,3 +1,4 @@
import { nodeRegistry } from '../registry'
import { AnyNode, type AnyNodeType } from '../schema/types'
import { healSceneNodes } from '../utils/heal-scene-graph'
@@ -13,6 +14,8 @@ export type ValidationIssue = {
export type BuildStats = {
total: number
byType: Partial<Record<AnyNodeType, number>>
/** Kinds outside the static schema union but registered at runtime (plugins). */
pluginTypes: Record<string, number>
unknownTypes: Record<string, number>
floorAreaM2: number
}
@@ -80,7 +83,13 @@ export function validateBuildJson(input: unknown): ValidateBuildJsonResult {
const errors: ValidationIssue[] = []
const warnings: ValidationIssue[] = []
const schemaIssues: SchemaIssue[] = []
const stats: BuildStats = { total: 0, byType: {}, unknownTypes: {}, floorAreaM2: 0 }
const stats: BuildStats = {
total: 0,
byType: {},
pluginTypes: {},
unknownTypes: {},
floorAreaM2: 0,
}
if (!isPlainObject(input)) {
errors.push({
@@ -167,6 +176,33 @@ export function validateBuildJson(input: unknown): ValidateBuildJsonResult {
})
}
// Ids of nodes whose type falls outside the static schema union — plugin
// kinds (`trees:tree`) or genuinely unknown types. The scene store accepts
// them on load (they already round-trip through the DB fine) and they're
// surfaced by the unknown-types warning, but a parent's strict `children`
// id union would hard-fail over them: validate parents against a copy with
// those ids filtered out. The imported data itself keeps them.
const nonSchemaNodeIds = new Set<string>()
for (const [key, value] of Object.entries(nodes)) {
if (!isPlainObject(value)) continue
const type = typeof value.type === 'string' ? value.type : null
if (type && KNOWN_TYPES.has(type)) continue
nonSchemaNodeIds.add(typeof value.id === 'string' ? value.id : key)
}
const withoutNonSchemaChildren = (value: Record<string, unknown>): Record<string, unknown> => {
const children = value.children
if (!Array.isArray(children)) return value
if (!children.some((child) => typeof child === 'string' && nonSchemaNodeIds.has(child))) {
return value
}
return {
...value,
children: children.filter(
(child) => !(typeof child === 'string' && nonSchemaNodeIds.has(child)),
),
}
}
let validRootCount = 0
let mismatchedKeyCount = 0
let schemaFailureCount = 0
@@ -206,7 +242,7 @@ export function validateBuildJson(input: unknown): ValidateBuildJsonResult {
const t = type as AnyNodeType
stats.byType[t] = (stats.byType[t] ?? 0) + 1
const parseResult = AnyNode.safeParse(value)
const parseResult = AnyNode.safeParse(withoutNonSchemaChildren(value))
if (!parseResult.success) {
schemaFailureCount += 1
const issue = parseResult.error.issues[0]
@@ -232,7 +268,28 @@ export function validateBuildJson(input: unknown): ValidateBuildJsonResult {
}
}
} else {
stats.unknownTypes[type] = (stats.unknownTypes[type] ?? 0) + 1
const registered = nodeRegistry.get(type)
if (registered) {
// A runtime-registered plugin kind (e.g. `trees:tree`) is a
// first-class citizen: validate it with its own registered schema
// instead of flagging it unknown. Files from projects whose plugin
// is NOT loaded here still fall through to the unknown-types
// warning below.
stats.pluginTypes[type] = (stats.pluginTypes[type] ?? 0) + 1
const parseResult = registered.schema.safeParse(value)
if (!parseResult.success) {
schemaFailureCount += 1
const issue = parseResult.error.issues[0]
schemaIssues.push({
nodeId: key,
nodeType: type,
path: issue ? issue.path.join('.') : '',
message: issue ? issue.message : 'schema mismatch',
})
}
} else {
stats.unknownTypes[type] = (stats.unknownTypes[type] ?? 0) + 1
}
}
if (parentId && !(parentId in nodes)) {