diff --git a/packages/core/src/agent-operations/door-clearance.ts b/packages/core/src/agent-operations/door-clearance.ts index d1c068e453..e823c61362 100644 --- a/packages/core/src/agent-operations/door-clearance.ts +++ b/packages/core/src/agent-operations/door-clearance.ts @@ -10,7 +10,7 @@ import { getDoorOpeningSize } from '../lib/door-opening' import { isVehicleDoorType } from '../lib/door-operation' import { area, intersection } from '../lib/polygon-boolean' -import type { Vec3 } from '../procedural-items/recipe' +import { evaluateRecipe, type Vec3 } from '../procedural-items/recipe' import { boxCorners, rotateVector } from '../procedural-items/spatial' import { type AnyNode, getScaledDimensions } from '../schema' import { DEFAULT_WALL_THICKNESS } from '../systems/wall/wall-footprint' @@ -220,7 +220,7 @@ export function itemNodePlanCorners(node: Extract): V node.position[0] + lx * Math.cos(yaw) + lz * Math.sin(yaw), node.position[2] - lx * Math.sin(yaw) + lz * Math.cos(yaw), ] - const bounds = node.source?.manifest.bounds + const bounds = node.source?.manifest?.bounds if (!bounds) { const [width, , depth] = node.asset.dimensions return [-width / 2, width / 2].flatMap((x) => @@ -240,16 +240,23 @@ export function itemNodePlanCorners(node: Extract): V }) } +export const PLANAR_ROTATION_EPSILON = 1e-6 + +export function hasNonFloorItemAttachment(node: Extract): boolean { + const attach = node.asset?.attachTo + return ( + attach === 'wall' || + attach === 'wall-side' || + attach === 'ceiling' || + Boolean(node.roofSegmentId || node.roofFace || node.blockFaceId) + ) +} + export function inspectItemPlanFootprint( node: Extract, options?: { floorOnly?: boolean }, ): ItemFootprintInspection { - if ( - options?.floorOnly && - (node.asset.attachTo === 'wall' || - node.asset.attachTo === 'wall-side' || - node.asset.attachTo === 'ceiling') - ) { + if (options?.floorOnly && hasNonFloorItemAttachment(node)) { return { ok: false, reason: 'unsupported_attachment' } } @@ -264,14 +271,17 @@ export function inspectItemPlanFootprint( return { ok: false, reason: 'non_finite_position' } } - const rotation = Array.isArray(node.rotation) ? node.rotation : [0, 0, 0] - const rotationX = rotation[0] ?? Number.NaN - const rotationY = rotation[1] ?? Number.NaN - const rotationZ = rotation[2] ?? Number.NaN + if (!Array.isArray(node.rotation) || node.rotation.length !== 3) { + return { ok: false, reason: 'non_finite_rotation' } + } + const [rotationX, rotationY, rotationZ] = node.rotation if (!(Number.isFinite(rotationX) && Number.isFinite(rotationY) && Number.isFinite(rotationZ))) { return { ok: false, reason: 'non_finite_rotation' } } - if (Math.abs(rotationX) > 1e-6 || Math.abs(rotationZ) > 1e-6) { + if ( + Math.abs(rotationX) > PLANAR_ROTATION_EPSILON || + Math.abs(rotationZ) > PLANAR_ROTATION_EPSILON + ) { return { ok: false, reason: 'non_planar_rotation' } } @@ -324,6 +334,134 @@ export function inspectItemPlanFootprint( } } +export function proceduralNodePlanCorners( + node: Extract, + preEvaluated?: ReturnType, +): Vec2[] | null { + if (!Array.isArray(node.recipe?.parts)) return null + if (!Array.isArray(node.position) || !Array.isArray(node.rotation)) return null + const [px, py, pz] = node.position + const [rx, yaw, rz] = node.rotation + if (![px, py, pz, rx, yaw, rz].every(Number.isFinite)) return null + let evaluated = preEvaluated + if (!evaluated) { + try { + evaluated = evaluateRecipe(node.recipe, node.parameters) + } catch { + return null + } + } + const extent = evaluated.reach ?? evaluated + const [width, height, depth] = evaluated.dimensions + if ( + ![width, height, depth, ...extent.min, ...extent.max].every(Number.isFinite) || + width <= 0 || + depth <= 0 + ) { + return null + } + const cos = Math.cos(yaw) + const sin = Math.sin(yaw) + const place = (lx: number, lz: number): Vec2 => [ + px + lx * cos + lz * sin, + pz - lx * sin + lz * cos, + ] + return [ + place(extent.min[0], extent.min[2]), + place(extent.max[0], extent.min[2]), + place(extent.max[0], extent.max[2]), + place(extent.min[0], extent.max[2]), + ] +} + +export function proceduralNodePlanAabb( + node: AnyNode, + preEvaluated?: ReturnType, +): PlanAabb | null { + if (node.type !== 'procedural-item') return null + const corners = proceduralNodePlanCorners(node, preEvaluated) + if (!corners?.every((corner) => corner.every(Number.isFinite))) return null + return { + minX: Math.min(...corners.map(([x]) => x)), + maxX: Math.max(...corners.map(([x]) => x)), + minZ: Math.min(...corners.map(([, z]) => z)), + maxZ: Math.max(...corners.map(([, z]) => z)), + } +} + +export function inspectProceduralItemPlanFootprint( + node: Extract, + _options?: { floorOnly?: boolean }, +): ItemFootprintInspection { + const attach = node.recipe?.mounting?.attachTo + if (node.wallId || (attach != null && (attach as string) !== 'floor')) { + return { ok: false, reason: 'unsupported_attachment' } + } + + const position = node.position + if (!Array.isArray(position)) { + return { ok: false, reason: 'non_finite_position' } + } + const [x, y, z] = position + if (!(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))) { + return { ok: false, reason: 'non_finite_position' } + } + + if (!Array.isArray(node.rotation) || node.rotation.length !== 3) { + return { ok: false, reason: 'non_finite_rotation' } + } + const [rotationX, rotationY, rotationZ] = node.rotation + if (!(Number.isFinite(rotationX) && Number.isFinite(rotationY) && Number.isFinite(rotationZ))) { + return { ok: false, reason: 'non_finite_rotation' } + } + if ( + Math.abs(rotationX) > PLANAR_ROTATION_EPSILON || + Math.abs(rotationZ) > PLANAR_ROTATION_EPSILON + ) { + return { ok: false, reason: 'non_planar_rotation' } + } + + if (!Array.isArray(node.recipe?.parts)) { + return { ok: false, reason: 'missing_dimensions' } + } + let evaluated: ReturnType + try { + evaluated = evaluateRecipe(node.recipe, node.parameters) + } catch { + return { ok: false, reason: 'missing_dimensions' } + } + + const [width, height, depth] = evaluated.dimensions + if (![width, height, depth, ...evaluated.min, ...evaluated.max].every(Number.isFinite)) { + return { ok: false, reason: 'non_finite_dimensions' } + } + if (width <= 0 || depth <= 0) { + return { ok: false, reason: 'non_positive_plan_dimensions' } + } + + const aabb = proceduralNodePlanAabb(node, evaluated) + if (!aabb) return { ok: false, reason: 'non_finite_dimensions' } + const extent = evaluated.reach ?? evaluated + const effectiveDimensions: [number, number, number] = [ + extent.max[0] - extent.min[0], + extent.max[1] - extent.min[1], + extent.max[2] - extent.min[2], + ] + if (!effectiveDimensions.every(Number.isFinite)) { + return { ok: false, reason: 'non_finite_dimensions' } + } + if (effectiveDimensions[0] <= 0 || effectiveDimensions[2] <= 0) { + return { ok: false, reason: 'non_positive_plan_dimensions' } + } + return { + ok: true, + aabb, + sourceDimensions: [width, height, depth], + effectiveDimensions, + rotationY, + } +} + /** * Build a rectangular keep-out around a wall door, extruded perpendicular to the wall * on both faces so either swing side is protected. @@ -610,7 +748,7 @@ export function findBlockedDoors(args: { const aabb = itemPlanAabbInLevel(node, byId) if (!aabb) continue - const heights = args.heightsOf?.(node) ?? itemLevelHeightRange(node, byId) + const heights = args.heightsOf ? args.heightsOf(node) : itemLevelHeightRange(node, byId) const solids = args.solidsOf?.(node) ?? null const vehicle = isVehicle(node) diff --git a/packages/core/src/agent-operations/furniture-kind.ts b/packages/core/src/agent-operations/furniture-kind.ts index 247904adbc..e38bab542f 100644 --- a/packages/core/src/agent-operations/furniture-kind.ts +++ b/packages/core/src/agent-operations/furniture-kind.ts @@ -1,4 +1,6 @@ import { foldRoomName } from '../building/room-use' +import type { ProceduralItemNode } from '../procedural-items/node' +import { evaluateRecipe } from '../procedural-items/recipe' import { getScaledDimensions, type ItemNode, LOW_PROFILE_ITEM_SURFACE_MAX_HEIGHT } from '../schema' /** How a piece of furniture stands in a room, read from what the catalog calls it. */ @@ -45,31 +47,65 @@ export function isVehicle(item: ItemNode): boolean { * a rug by what it is filed under (its category: "rug", "rugs", "tapis"), else by what it is called * in English or French, and in both cases it must lie flat on the floor. */ -export function isFloorUnderlay(item: ItemNode): boolean { - const category = foldRoomName(item.asset.category ?? '') +export function isFloorUnderlay(node: ItemNode | ProceduralItemNode): boolean { + if (node.type === 'procedural-item') { + if (node.recipe?.mounting || node.wallId || !Array.isArray(node.recipe?.parts)) return false + const category = foldRoomName(node.recipe.classification?.category ?? '').replace(/[-_]+/g, ' ') + const filedAsRug = RUG_CATEGORY.test(category) + const text = foldRoomName( + read({ id: node.recipe.name ?? node.id, name: node.name ?? node.recipe.name }), + ) + if ( + !(filedAsRug || RUG_WORD.test(text)) || + (!filedAsRug && + (WALL.test(text) || CHAIR.test(text) || /table|desk|ottoman|pouf/.test(text))) || + !Array.isArray(node.position) || + !Array.isArray(node.rotation) || + ![...node.position, ...node.rotation].every(Number.isFinite) || + Math.abs(node.position[1]) > 1e-6 || + Math.abs(node.rotation[0]) > 1e-6 || + Math.abs(node.rotation[2]) > 1e-6 + ) + return false + try { + const evaluated = evaluateRecipe(node.recipe, node.parameters) + return ( + evaluated.dimensions[0] > 0 && + evaluated.dimensions[2] > 0 && + Number.isFinite(evaluated.min[1]) && + Number.isFinite(evaluated.max[1]) && + evaluated.min[1] >= -1e-6 && + evaluated.max[1] >= evaluated.min[1] && + evaluated.max[1] <= LOW_PROFILE_ITEM_SURFACE_MAX_HEIGHT + ) + } catch { + return false + } + } + const category = foldRoomName(node.asset.category ?? '').replace(/[-_]+/g, ' ') const filedAsRug = RUG_CATEGORY.test(category) - const text = foldRoomName(read(item.asset)) + const text = foldRoomName(read(node.asset)) if ( !(filedAsRug || RUG_WORD.test(text)) || (!filedAsRug && (WALL.test(text) || CHAIR.test(text) || /table|desk|ottoman|pouf/.test(text))) || - item.asset.attachTo + node.asset.attachTo ) return false - const dims = getScaledDimensions(item) + const dims = getScaledDimensions(node) if ( - ![...item.position, ...item.rotation, ...item.scale, ...dims].every(Number.isFinite) || - !item.scale.every((value) => value > 0) || + ![...node.position, ...node.rotation, ...node.scale, ...dims].every(Number.isFinite) || + !node.scale.every((value) => value > 0) || dims[0] <= 0 || dims[2] <= 0 || - Math.abs(item.position[1]) > 1e-6 || - Math.abs(item.rotation[0]) > 1e-6 || - Math.abs(item.rotation[2]) > 1e-6 + Math.abs(node.position[1]) > 1e-6 || + Math.abs(node.rotation[0]) > 1e-6 || + Math.abs(node.rotation[2]) > 1e-6 ) return false - const bounds = item.source?.manifest.bounds - const bottom = bounds ? bounds.min[1] * item.scale[1] : 0 - const top = bounds ? bounds.max[1] * item.scale[1] : dims[1] + const bounds = node.source?.manifest?.bounds + const bottom = bounds ? bounds.min[1] * node.scale[1] : 0 + const top = bounds ? bounds.max[1] * node.scale[1] : dims[1] return ( Number.isFinite(bottom) && Number.isFinite(top) && @@ -126,12 +162,20 @@ const ROLE_NOT: Partial> = { } const PAIR_ROLES: PairRole[] = ['bedside', 'bed', 'seat', 'sidetable', 'sofa', 'worktop'] -function pairRole(item: ItemNode): PairRole | null { - const category = foldRoomName(item.asset.category ?? '').replace(/[-_]+/g, ' ') +function pairRole(node: ItemNode | ProceduralItemNode): PairRole | null { + const rawCategory = + node.type === 'procedural-item' + ? (node.recipe?.classification?.category ?? '') + : (node.asset.category ?? '') + const named: Named = + node.type === 'procedural-item' + ? { id: node.recipe?.name ?? node.id, name: node.name ?? node.recipe?.name } + : node.asset + const category = foldRoomName(rawCategory).replace(/[-_]+/g, ' ') const filed = PAIR_ROLES.find((role) => ROLE_CATEGORY[role].test(category)) if (filed) return filed if (!GENERIC_CATEGORY.test(category)) return null - const text = foldRoomName(read(item.asset)) + const text = foldRoomName(read(named)) if (ARMCHAIR.test(text)) return null return ( PAIR_ROLES.find((role) => ROLE_WORDS[role].test(text) && !ROLE_NOT[role]?.test(text)) ?? null @@ -150,7 +194,10 @@ const DESIGNED_PAIRS: readonly [PairRole, PairRole][] = [ * the design, not a finding; two of them overlapping is still one. Read from what each is filed * under (its category), by its words only where the category says nothing. */ -export function designedTogether(a: ItemNode, b: ItemNode): boolean { +export function designedTogether( + a: ItemNode | ProceduralItemNode, + b: ItemNode | ProceduralItemNode, +): boolean { const roles = [pairRole(a), pairRole(b)] return DESIGNED_PAIRS.some( ([first, second]) => diff --git a/packages/core/src/agent-operations/item-space.ts b/packages/core/src/agent-operations/item-space.ts index f9e89eed6c..c7ebb18b3c 100644 --- a/packages/core/src/agent-operations/item-space.ts +++ b/packages/core/src/agent-operations/item-space.ts @@ -1,41 +1,179 @@ +import type { ProceduralItemNode } from '../procedural-items/node' +import type { evaluateRecipe } from '../procedural-items/recipe' +import type { Frame } from '../procedural-items/spatial' +import { nodeLevelFrame } from '../procedural-items/world-pose' import { type AnyNode, getScaledDimensions, type ItemNode } from '../schema' -import { itemNodePlanAabb, type PlanAabb } from './door-clearance' +import { + itemNodePlanAabb, + PLANAR_ROTATION_EPSILON, + type PlanAabb, + proceduralNodePlanAabb, + proceduralNodePlanCorners, +} from './door-clearance' +import type { Vec2 } from './plan-geometry' + +type NodesRecord = Readonly> + +function recordFromMap(byId: Map): NodesRecord { + const out: Record = Object.create(null) + for (const [id, node] of byId) out[id] = node + return out +} + +function hasDisallowedHost( + node: ItemNode | ProceduralItemNode, + byId: Map, +): boolean { + if (node.type === 'procedural-item') { + if (node.wallId) return true + const attach = node.recipe?.mounting?.attachTo + if (attach != null && (attach as string) !== 'floor' && attach !== 'ceiling') return true + if (attach === 'ceiling') { + const parent = node.parentId ? byId.get(node.parentId) : undefined + if (parent?.type !== 'ceiling' || !Array.isArray(node.recipe?.parts)) return true + } + } + const seen = new Set([node.id]) + let parent = node.parentId ? byId.get(node.parentId) : undefined + while (parent && parent.type !== 'level') { + if (seen.has(parent.id)) return true + seen.add(parent.id) + if (parent.type === 'wall') return true + if (parent.type === 'procedural-item') { + if (parent.wallId) return true + const attach = parent.recipe?.mounting?.attachTo + if (attach != null && (attach as string) !== 'floor' && attach !== 'ceiling') return true + if (attach === 'ceiling') { + const nextParent = parent.parentId ? byId.get(parent.parentId) : undefined + if (nextParent?.type !== 'ceiling' || !Array.isArray(parent.recipe?.parts)) return true + } + } + parent = parent.parentId ? byId.get(parent.parentId) : undefined + } + return false +} + +function isPlanarUpAxis(frame: Frame): boolean { + const up = frame.axes[1] + return Math.abs(up[0]) <= 1e-5 && Math.abs(up[1] - 1) <= 1e-5 && Math.abs(up[2]) <= 1e-5 +} + +function missingRootParentId(node: AnyNode, byId: Map): string | null { + const seen = new Set([node.id]) + let current: AnyNode = node + while (current.parentId) { + if (seen.has(current.parentId)) return null + const parent = byId.get(current.parentId) + if (!parent) return current.parentId + if (parent.type === 'level') return null + seen.add(parent.id) + current = parent + } + return null +} + +function resolvePlanLevelPose( + node: ItemNode | ProceduralItemNode, + byId: Map, + options?: { nodes?: NodesRecord; frameCache?: Map }, +): { position: [number, number, number]; yawDeg: number } | null { + if (!Array.isArray(node.position) || !Array.isArray(node.rotation) || node.rotation.length !== 3) + return null + if ( + node.type === 'procedural-item' && + !( + Number.isFinite(node.rotation[0]) && + Number.isFinite(node.rotation[1]) && + Number.isFinite(node.rotation[2]) && + Math.abs(node.rotation[0]) <= PLANAR_ROTATION_EPSILON && + Math.abs(node.rotation[2]) <= PLANAR_ROTATION_EPSILON + ) + ) { + return null + } + if (hasDisallowedHost(node, byId)) return null + const baseNodes = options?.nodes ?? recordFromMap(byId) + const missingRoot = missingRootParentId(node, byId) + const nonFiniteItemY = node.type === 'item' && !Number.isFinite(node.position[1]) + const needsOverride = Boolean(missingRoot) || nonFiniteItemY + let nodes = baseNodes + if (needsOverride) { + const copy: Record = Object.assign(Object.create(null), baseNodes) + if (missingRoot) { + copy[missingRoot] = { + id: missingRoot, + type: 'level', + object: 'node', + visible: true, + parentId: null, + level: 0, + children: [], + } as unknown as AnyNode + } + if (nonFiniteItemY) { + copy[node.id] = { + ...node, + position: [node.position[0], 0, node.position[2]], + } as AnyNode + } + nodes = copy + } + let resolved: Frame + try { + resolved = nodeLevelFrame(node.id, nodes, new Set(), { + planOnly: true, + cache: needsOverride ? undefined : options?.frameCache, + }) + } catch { + return null + } + if ( + (node.type === 'procedural-item' || + (Math.abs(node.rotation[0]) <= PLANAR_ROTATION_EPSILON && + Math.abs(node.rotation[2]) <= PLANAR_ROTATION_EPSILON)) && + !isPlanarUpAxis(resolved) + ) { + return null + } + const [px, rawPy, pz] = resolved.position + const py = nonFiniteItemY ? node.position[1] : rawPy + if (!(Number.isFinite(px) && Number.isFinite(pz))) return null + if (node.type === 'procedural-item' && !Number.isFinite(py)) return null + const yaw = Math.atan2(-resolved.axes[0][2], resolved.axes[0][0]) + if (!Number.isFinite(yaw)) return null + return { position: [px, py, pz], yawDeg: yaw } +} /** * Where an item stands in its level's frame when it is hosted by another item (a lamp on a * nightstand): its position is local to the host, so the plan checks read it through the host - * chain, each host's yaw turning the offset. An item hosted by a wall keeps wall-local - * coordinates and is read by the wall observations instead, so this answers nothing for it. + * chain via canonical `nodeLevelFrame`, each host's yaw turning the offset. An item hosted by a + * wall keeps wall-local coordinates and is read by the wall observations instead, so this answers + * nothing for it. */ export function itemLevelPose( node: ItemNode, byId: Map, + options?: { nodes?: NodesRecord; frameCache?: Map }, ): { position: [number, number, number]; yawDeg: number } | null { - let [x, y, z] = node.position - let yaw = node.rotation[1] - let parent = node.parentId ? byId.get(node.parentId) : undefined - while (parent && parent.type !== 'level') { - // A wall's child is wall-local: not this frame. A ceiling's or slab's child is already in plan metres. - if (parent.type === 'wall') return null - if (parent.type !== 'item') break - const turn = parent.rotation[1] - const [px, py, pz] = parent.position - const [rx, rz] = [ - x * Math.cos(turn) + z * Math.sin(turn), - -x * Math.sin(turn) + z * Math.cos(turn), - ] - x = px + rx - y = py + y - z = pz + rz - yaw += turn - parent = parent.parentId ? byId.get(parent.parentId) : undefined - } - return { position: [x, y, z], yawDeg: yaw } + return resolvePlanLevelPose(node, byId, options) +} + +export function proceduralItemLevelPose( + node: ProceduralItemNode, + byId: Map, + options?: { nodes?: NodesRecord; frameCache?: Map }, +): { position: [number, number, number]; yawDeg: number } | null { + return resolvePlanLevelPose(node, byId, options) } /** The item's plan footprint in its level's frame, or null when it is wall-hosted or malformed. */ -export function itemPlanAabbInLevel(node: ItemNode, byId: Map): PlanAabb | null { - const pose = itemLevelPose(node, byId) +export function itemPlanAabbInLevel( + node: ItemNode, + byId: Map, + options?: { nodes?: NodesRecord; frameCache?: Map }, +): PlanAabb | null { + const pose = itemLevelPose(node, byId, options) if (!pose) return null return itemNodePlanAabb({ ...node, @@ -44,17 +182,66 @@ export function itemPlanAabbInLevel(node: ItemNode, byId: Map): }) } +export function proceduralPlanCornersInLevel( + node: ProceduralItemNode, + byId: Map, + options?: { + nodes?: NodesRecord + frameCache?: Map + evaluated?: ReturnType + }, +): Vec2[] | null { + const pose = proceduralItemLevelPose(node, byId, options) + if (!pose) return null + return proceduralNodePlanCorners( + { + ...node, + position: pose.position, + rotation: [node.rotation[0], pose.yawDeg, node.rotation[2]], + }, + options?.evaluated, + ) +} + +export function proceduralPlanAabbInLevel( + node: ProceduralItemNode, + byId: Map, + options?: { + nodes?: NodesRecord + frameCache?: Map + evaluated?: ReturnType + }, +): PlanAabb | null { + const pose = proceduralItemLevelPose(node, byId, options) + if (!pose) return null + return proceduralNodePlanAabb( + { + ...node, + position: pose.position, + rotation: [node.rotation[0], pose.yawDeg, node.rotation[2]], + }, + options?.evaluated, + ) +} + /** The item's bottom and top above its level's floor, from its pose and scaled height. */ export function itemLevelHeightRange( node: ItemNode, byId: Map, + options?: { nodes?: NodesRecord; frameCache?: Map }, ): { min: number; max: number } | null { - // Only a plainly placed item answers: yaw-only, positive scales, a real height. Anything else - // keeps the conservative rule that unknown geometry cannot waive a collision. - if (node.rotation[0] !== 0 || node.rotation[2] !== 0) return null + if ( + !Array.isArray(node.rotation) || + node.rotation.length !== 3 || + !( + Math.abs(node.rotation[0]) <= PLANAR_ROTATION_EPSILON && + Math.abs(node.rotation[2]) <= PLANAR_ROTATION_EPSILON + ) + ) + return null if (node.scale.some((v) => !(v > 0)) || (node.asset.scale ?? [1, 1, 1]).some((v) => !(v > 0))) return null - const pose = itemLevelPose(node, byId) + const pose = itemLevelPose(node, byId, options) if (!pose) return null const height = getScaledDimensions(node)[1] if (!(height > 0) || !Number.isFinite(height) || !Number.isFinite(pose.position[1])) return null @@ -64,8 +251,11 @@ export function itemLevelHeightRange( /** Every item above this one in its host chain: a thing and what it rests on are stacked by design, not colliding. */ export function itemHosts(node: AnyNode, byId: Map): Set { const hosts = new Set() + const seen = new Set([node.id]) let parent = node.parentId ? byId.get(node.parentId) : undefined - while (parent?.type === 'item') { + while (parent?.type === 'item' || parent?.type === 'procedural-item') { + if (seen.has(parent.id)) break + seen.add(parent.id) hosts.add(parent.id) parent = parent.parentId ? byId.get(parent.parentId) : undefined } diff --git a/packages/core/src/agent-operations/layout-clearance.test.ts b/packages/core/src/agent-operations/layout-clearance.test.ts index e2e4709eac..2e41324013 100644 --- a/packages/core/src/agent-operations/layout-clearance.test.ts +++ b/packages/core/src/agent-operations/layout-clearance.test.ts @@ -1,4 +1,7 @@ import { describe, expect, test } from 'bun:test' +import { encodeTerrainField } from '../lib/terrain-codec' +import { applyHeightPatch, createTerrainField, flattenPatch } from '../lib/terrain-field' +import { planDesignPlacement } from '../procedural-items/design-placement' import { type AnyNode, BuildingNode, @@ -6,6 +9,7 @@ import { DoorNode, ItemNode, LevelNode, + ProceduralItemNode, SlabNode, WallNode, WindowNode, @@ -16,19 +20,28 @@ import savedWallScreen from './__fixtures__/wall-screen.json' import { aabbsOverlap, inspectItemPlanFootprint, + inspectProceduralItemPlanFootprint, itemNodePlanAabb, + itemNodePlanCorners, + proceduralNodePlanCorners, resolveNodeLevelId, } from './door-clearance' +import { isFloorUnderlay } from './furniture-kind' import { AGENT_OPERATIONS, applySceneChanges, verifyScene } from './index' +import { itemHosts, proceduralItemLevelPose } from './item-space' import { classifyPlacement, collectOccupiedFootprints, + findBlockedDoors, findItemItemCollisions, findValidPlacement, generatePlacementCandidates, + itemHeightsInLevel, itemPlanAabb, + itemSolidsInLevel, layoutIssuesFromScene, scriptItemBoundsInLevel, + scriptItemToLevel, } from './layout-clearance' function item( @@ -1098,4 +1111,2529 @@ describe('layout-clearance', () => { expect(found.candidate).toBeNull() expect(found.reason).toBe('blocks_door_clearance') }) + + describe('procedural-item collision parity (#1255)', () => { + const overlapBlockRecipe = { + version: 1, + name: 'M0 D2.5 Overlap Block', + description: 'A solid 2 m by 2 m by 0.9 m floor-standing test block.', + classification: { + category: 'test_furniture', + functionTags: ['test'], + tags: ['collision'], + }, + parameters: [ + { + id: 'width', + label: 'Width', + default: 2, + min: 2, + max: 2, + step: 0.1, + unit: 'm', + axis: 'x', + }, + { + id: 'depth', + label: 'Depth', + default: 2, + min: 2, + max: 2, + step: 0.1, + unit: 'm', + axis: 'z', + }, + { + id: 'height', + label: 'Height', + default: 0.9, + min: 0.9, + max: 0.9, + step: 0.1, + unit: 'm', + axis: 'y', + }, + ], + slots: [{ id: 'wood', label: 'Wood', color: '#8b5a2b', finish: 'wood' }], + parts: [ + { + id: 'block', + label: 'Block', + count: 1, + shapes: [ + { + id: 'body', + primitive: 'box', + slot: 'wood', + size: ['width', 'height', 'depth'], + position: [0, { op: 'div', args: ['height', 2] }, 0], + support: true, + }, + ], + }, + ], + constraints: [], + } + + function makeProcedural( + id: string, + parentId: string, + position: [number, number, number] = [0, 0, 0], + rotation: [number, number, number] = [0, 0, 0], + recipeOverride: Record = overlapBlockRecipe, + extra: Record = {}, + ) { + return ProceduralItemNode.parse({ + object: 'node', + id, + type: 'procedural-item', + name: id, + parentId, + visible: true, + metadata: {}, + recipe: recipeOverride, + parameters: {}, + slots: {}, + position, + rotation, + children: [], + attachments: {}, + ...extra, + }) + } + + test('reports exact overlap between two floor procedural-item nodes in findItemItemCollisions and verifyScene', () => { + const level = LevelNode.parse({ id: 'level_proc', name: 'G', level: 0 }) + const a = makeProcedural('procedural-item_a', level.id, [0, 0, 0]) + const b = makeProcedural('procedural-item_b', level.id, [0, 0, 0]) + const nodes = [level, a, b] + + const hits = findItemItemCollisions({ nodes, levelId: level.id, gap: 0 }) + expect(hits).toHaveLength(1) + expect(hits[0]).toMatchObject({ + aId: 'procedural-item_a', + bId: 'procedural-item_b', + kind: 'item-aabb', + violation: 'overlap', + }) + + const verified = verifyScene( + Object.fromEntries(nodes.map((node) => [node.id, node])), + {}, + { activeLevelId: level.id }, + ).result + expect(verified.hasIssues).toBe(true) + expect(verified.issues).toContainEqual( + expect.objectContaining({ + type: 'item_overlap', + nodeIds: ['procedural-item_a', 'procedural-item_b'], + }), + ) + }) + + test('detects rotated off-center procedural-item footprint overlap against an item', () => { + const level = LevelNode.parse({ id: 'level_off', name: 'G', level: 0 }) + // Local X in [-0.5, 0.5], local Z in [0, 1.0] (back-datum bench). Rotated +90 deg around Y: + // world X spans [0, 1.0], world Z spans [-0.5, 0.5]. + const offCenterRecipe = { + ...overlapBlockRecipe, + name: 'Back-datum bench', + parts: [ + { + id: 'bench', + label: 'Bench', + count: 1, + shapes: [ + { + id: 'body', + primitive: 'box', + slot: 'wood', + size: [1, 0.5, 1], + position: [0, 0.25, 0.5], + support: true, + }, + ], + }, + ], + } + const bench = makeProcedural( + 'procedural-item_bench', + level.id, + [0, 0, 0], + [0, Math.PI / 2, 0], + offCenterRecipe, + ) + const overlapChair = ItemNode.parse( + item('item_chair', [0.8, 0, 0], [0.5, 0.8, 0.5], 'Chair', 0, level.id), + ) + const clearBehind = ItemNode.parse( + item('item_clear', [-0.6, 0, 0], [0.5, 0.8, 0.5], 'Clear', 0, level.id), + ) + + expect(collectOccupiedFootprints([level, bench])[0]?.aabb).toEqual({ + minX: expect.closeTo(0, 6), + maxX: expect.closeTo(1, 6), + minZ: expect.closeTo(-0.5, 6), + maxZ: expect.closeTo(0.5, 6), + }) + const hits = findItemItemCollisions({ + nodes: [level, bench, overlapChair, clearBehind], + levelId: level.id, + gap: 0, + }) + expect(hits).toHaveLength(1) + expect([hits[0]!.aId, hits[0]!.bId].sort()).toEqual(['item_chair', 'procedural-item_bench']) + }) + + test('treats an item hosted on or resting atop a procedural-item surface as stacked, not colliding', () => { + const level = LevelNode.parse({ id: 'level_stack', name: 'G', level: 0 }) + const tableRecipe = { + ...overlapBlockRecipe, + name: 'Procedural Table', + surfaces: [ + { + id: 'top', + label: 'Tabletop', + position: [0, 0.9, 0], + size: [1.8, 1.8], + }, + ], + } + const table = makeProcedural( + 'procedural-item_table', + level.id, + [0, 0, 0], + [0, 0, 0], + tableRecipe, + { + children: ['item_hosted_lamp'], + attachments: { item_hosted_lamp: 'top' }, + }, + ) + const hostedLamp = ItemNode.parse( + item('item_hosted_lamp', [0, 0, 0], [0.3, 0.4, 0.3], 'Hosted Lamp', 0, table.id), + ) + const siblingVase = ItemNode.parse( + item('item_vase', [0.4, 0.9, 0], [0.2, 0.3, 0.2], 'Vase', 0, level.id), + ) + expect( + findItemItemCollisions({ + nodes: [level, table, hostedLamp, siblingVase], + levelId: level.id, + }), + ).toEqual([]) + }) + + test('waives clearance (but not overlap) for designedTogether procedural dining pairs', () => { + const level = LevelNode.parse({ id: 'level_dining', name: 'G', level: 0 }) + const diningTable = makeProcedural( + 'procedural-item_dining_table', + level.id, + [0, 0, 0], + [0, 0, 0], + { + ...overlapBlockRecipe, + name: 'Dining table', + classification: { category: 'dining_table', functionTags: ['dining'], tags: [] }, + }, + ) + // 0.03 m away from the 2x2 table ([1.28, 0, 0] with width 0.5 -> minX = 1.03, gap = 0.03 < 0.08) + const diningChair = makeProcedural( + 'procedural-item_dining_chair', + level.id, + [1.28, 0, 0], + [0, 0, 0], + { + ...overlapBlockRecipe, + name: 'Dining chair', + classification: { category: 'dining_chair', functionTags: ['seating'], tags: [] }, + parameters: [ + { + id: 'width', + label: 'Width', + default: 0.5, + min: 0.5, + max: 0.5, + step: 0.1, + unit: 'm', + axis: 'x', + }, + { + id: 'depth', + label: 'Depth', + default: 0.5, + min: 0.5, + max: 0.5, + step: 0.1, + unit: 'm', + axis: 'z', + }, + { + id: 'height', + label: 'Height', + default: 0.85, + min: 0.85, + max: 0.85, + step: 0.1, + unit: 'm', + axis: 'y', + }, + ], + }, + ) + const closeIssues = layoutIssuesFromScene([level, diningTable, diningChair]) + expect( + closeIssues.filter((i) => i.type === 'item_too_close' || i.type === 'item_overlap'), + ).toEqual([]) + + const overlappingChair = { + ...diningChair, + id: 'procedural-item_overlap_chair' as const, + position: [0.9, 0, 0] as [number, number, number], + } + const overlapIssues = layoutIssuesFromScene([level, diningTable, overlappingChair]) + expect(overlapIssues).toContainEqual(expect.objectContaining({ type: 'item_overlap' })) + + // Non-generic category ("lighting") named "Table lamp" must not match as a worktop pair + const floorTableLamp = makeProcedural( + 'procedural-item_table_lamp', + level.id, + [0, 0, 0], + [0, 0, 0], + { + ...overlapBlockRecipe, + name: 'Table lamp', + classification: { category: 'lighting', functionTags: ['lighting'], tags: [] }, + }, + ) + const lampChairIssues = layoutIssuesFromScene([level, floorTableLamp, diningChair]) + expect(lampChairIssues).toContainEqual(expect.objectContaining({ type: 'item_too_close' })) + + // Snake-case floor_mat procedural underlay is excluded from occupied footprints + const floorMat = makeProcedural('procedural-item_floor_mat', level.id, [0, 0, 0], [0, 0, 0], { + ...overlapBlockRecipe, + name: 'Entry cover', + classification: { category: 'floor_mat', functionTags: ['decor'], tags: [] }, + parameters: [ + { + id: 'width', + label: 'Width', + default: 2, + min: 2, + max: 2, + step: 0.1, + unit: 'm', + axis: 'x', + }, + { + id: 'depth', + label: 'Depth', + default: 2, + min: 2, + max: 2, + step: 0.1, + unit: 'm', + axis: 'z', + }, + { + id: 'height', + label: 'Height', + default: 0.01, + min: 0.01, + max: 0.01, + step: 0.005, + unit: 'm', + axis: 'y', + }, + ], + }) + expect(collectOccupiedFootprints([level, floorMat])).toEqual([]) + }) + + test('resolves mounting origin and ceiling elevation for items hosted on a hanging procedural shelf', () => { + const level = LevelNode.parse({ id: 'level_hang', name: 'G', level: 0, height: 2.8 }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_hang', + parentId: level.id, + polygon: [ + [-3, -3], + [3, -3], + [3, 3], + [-3, 3], + ], + }) + const hangingShelfRecipe = { + ...overlapBlockRecipe, + name: 'Hanging Shelf', + mounting: { attachTo: 'ceiling', reference: 'mount' }, + parts: [ + { + id: 'shelf', + label: 'Shelf', + count: 1, + shapes: [ + { + id: 'deck_board', + primitive: 'box', + slot: 'wood', + size: [1, 0.1, 0.4], + position: [0, 0.05, 0], + }, + { + id: 'left_rod', + primitive: 'box', + slot: 'wood', + size: [0.04, 0.7, 0.04], + position: [-0.48, 0.45, 0], + }, + { + id: 'right_rod', + primitive: 'box', + slot: 'wood', + size: [0.04, 0.7, 0.04], + position: [0.48, 0.45, 0], + }, + ], + }, + ], + surfaces: [ + { id: 'mount', label: 'Mount', position: [0.5, 0.8, 0], size: [0.2, 0.2] }, + { id: 'deck', label: 'Deck', position: [0, 0.1, 0], size: [0.8, 0.4] }, + ], + parameters: [ + { + id: 'width', + label: 'Width', + default: 1, + min: 1, + max: 1, + step: 0.1, + unit: 'm', + axis: 'x', + }, + { + id: 'depth', + label: 'Depth', + default: 0.4, + min: 0.4, + max: 0.4, + step: 0.1, + unit: 'm', + axis: 'z', + }, + { + id: 'height', + label: 'Height', + default: 0.8, + min: 0.8, + max: 0.8, + step: 0.1, + unit: 'm', + axis: 'y', + }, + ], + } + const shelf = makeProcedural( + 'procedural-item_hanging_shelf', + ceiling.id, + [0.5, 0, 0], + [0, 0, 0], + hangingShelfRecipe, + { + children: ['item_pot', 'procedural-item_hanging_bowl'], + attachments: { + item_pot: 'deck', + 'procedural-item_hanging_bowl': 'deck', + }, + }, + ) + const hostedPot = ItemNode.parse( + item('item_pot', [0, 0, 0], [0.2, 0.25, 0.2], 'Pot', 0, shelf.id), + ) + const hostedBowl = makeProcedural( + 'procedural-item_hanging_bowl', + shelf.id, + [0.3, 0, 0], + [0, 0, 0], + { + ...overlapBlockRecipe, + name: 'Hanging Bowl', + parameters: [ + { + id: 'width', + label: 'Width', + default: 0.2, + min: 0.2, + max: 0.2, + step: 0.1, + unit: 'm', + axis: 'x', + }, + { + id: 'depth', + label: 'Depth', + default: 0.2, + min: 0.2, + max: 0.2, + step: 0.1, + unit: 'm', + axis: 'z', + }, + { + id: 'height', + label: 'Height', + default: 0.15, + min: 0.15, + max: 0.15, + step: 0.05, + unit: 'm', + axis: 'y', + }, + ], + }, + ) + const floorTable = ItemNode.parse( + item('item_below', [0, 0, 0], [1, 0.9, 1], 'Floor Table', 0, level.id), + ) + const allNodes = [level, ceiling, shelf, hostedPot, hostedBowl, floorTable] + const footprints = collectOccupiedFootprints(allNodes) + const potFp = footprints.find((entry) => entry.id === 'item_pot') + expect(potFp?.aabb).toEqual({ + minX: expect.closeTo(-0.1, 6), + maxX: expect.closeTo(0.1, 6), + minZ: expect.closeTo(-0.1, 6), + maxZ: expect.closeTo(0.1, 6), + }) + expect( + collectOccupiedFootprints(allNodes, { levelId: level.id, floorOnly: true }).map( + (entry) => entry.id, + ), + ).toEqual([floorTable.id]) + expect( + findItemItemCollisions({ + nodes: allNodes, + levelId: level.id, + }), + ).toEqual([]) + }) + + test('resolves swept heights for non-recessed ceiling procedural items with motions', () => { + const level = LevelNode.parse({ id: 'level_fan', name: 'G', level: 0, height: 2.8 }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_fan', + parentId: level.id, + polygon: [ + [-3, -3], + [3, -3], + [3, 3], + [-3, 3], + ], + }) + const ceilingFanRecipe = { + ...overlapBlockRecipe, + version: 2, + name: 'Ceiling Fan', + description: 'Surface-mounted ceiling fan with spinning blades', + mounting: { attachTo: 'ceiling', reference: 'canopy' }, + surfaces: [{ id: 'canopy', label: 'Canopy', position: [0, 0.4, 0], size: [0.2, 0.2] }], + parts: [ + { + id: 'rod', + label: 'Downrod', + count: 1, + shapes: [ + { + id: 'shaft', + primitive: 'cylinder', + slot: 'wood', + size: [0.08, 0.4, 0.08], + position: [0, 0.2, 0], + }, + ], + }, + { + id: 'blades', + label: 'Blades', + count: 1, + motion: { + kind: 'spin', + pivot: [0, 0.05, 0], + axis: 'y', + radiansPerSecond: 4, + }, + shapes: [ + { + id: 'blade_x', + primitive: 'box', + slot: 'wood', + size: [1.2, 0.04, 0.14], + position: [0, 0.05, 0], + }, + ], + }, + ], + } + const fan = makeProcedural( + 'procedural-item_ceiling_fan', + ceiling.id, + [0, 0, 0], + [0, 0, 0], + ceilingFanRecipe, + ) + const floorTable = ItemNode.parse( + item('item_under_fan', [0, 0, 0], [1.2, 0.8, 1.2], 'Dining Table', 0, level.id), + ) + + // Fan hangs at ~2.4..2.8 m, well above the 0..0.8 m table: must not collide. + expect( + findItemItemCollisions({ + nodes: [level, ceiling, fan, floorTable], + levelId: level.id, + }), + ).toEqual([]) + expect( + layoutIssuesFromScene([level, ceiling, fan, floorTable]).filter( + (issue) => issue.type === 'item_overlap' || issue.type === 'item_too_close', + ), + ).toEqual([]) + + // A ceiling fixture whose vertical motion sweeps down into the table must still collide. + const dropFixtureRecipe = { + ...ceilingFanRecipe, + name: 'Drop Pendant', + parts: [ + ceilingFanRecipe.parts[0]!, + { + id: 'drop', + label: 'Drop Body', + count: 1, + motion: { + kind: 'slide', + axis: 'y', + distance: -2.0, + duration: 1, + }, + shapes: [ + { + id: 'pendant', + primitive: 'box', + slot: 'wood', + size: [0.5, 0.2, 0.5], + position: [0, 0.1, 0], + }, + ], + }, + ], + } + const dropFixture = makeProcedural( + 'procedural-item_drop_fixture', + ceiling.id, + [0, 0, 0], + [0, 0, 0], + dropFixtureRecipe, + ) + expect( + findItemItemCollisions({ + nodes: [level, ceiling, dropFixture, floorTable], + levelId: level.id, + }), + ).toContainEqual( + expect.objectContaining({ + aId: dropFixture.id, + bId: floorTable.id, + violation: 'overlap', + }), + ) + }) + test('named attachment waives resting contact but still flags penetration into the host surface', () => { + const level = LevelNode.parse({ id: 'level_attach_y', name: 'G', level: 0 }) + const tableRecipe = { + ...overlapBlockRecipe, + name: 'Procedural Table', + surfaces: [ + { + id: 'top', + label: 'Tabletop', + position: [0, 0.9, 0], + size: [1.8, 1.8], + }, + ], + } + const restingLamp = ItemNode.parse( + item( + 'item_lamp_rest', + [0, 0, 0], + [0.25, 0.4, 0.25], + 'Lamp', + 0, + 'procedural-item_attach_table', + ), + ) + const sunkLamp = ItemNode.parse( + item( + 'item_lamp_sunk', + [0, -0.2, 0], + [0.25, 0.4, 0.25], + 'Lamp', + 0, + 'procedural-item_attach_table', + ), + ) + + const restingTable = makeProcedural( + 'procedural-item_attach_table', + level.id, + [0, 0, 0], + [0, 0, 0], + tableRecipe, + { children: [restingLamp.id], attachments: { [restingLamp.id]: 'top' } }, + ) + expect( + findItemItemCollisions({ nodes: [level, restingTable, restingLamp], gap: 0.08 }), + ).toEqual([]) + + const sunkTable = makeProcedural( + 'procedural-item_attach_table', + level.id, + [0, 0, 0], + [0, 0, 0], + tableRecipe, + { children: [sunkLamp.id], attachments: { [sunkLamp.id]: 'top' } }, + ) + const sunkHits = findItemItemCollisions({ nodes: [level, sunkTable, sunkLamp], gap: 0.08 }) + expect(sunkHits).toHaveLength(1) + expect(sunkHits[0]?.violation).toBe('overlap') + }) + + test('projects swept reach X/Z bounds so a spinning ceiling fan collides with a tall cabinet in its sweep', () => { + const level = LevelNode.parse({ id: 'level_fan_sweep', name: 'G', level: 0, height: 2.8 }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_sweep', + parentId: level.id, + polygon: [ + [-2, -2], + [2, -2], + [2, 2], + [-2, 2], + ], + height: 2.8, + }) + const fanRecipe = { + ...overlapBlockRecipe, + version: 2, + name: 'Sweep Fan', + description: + 'Ceiling fan whose 1.2m blade extends 0.07m along Z at rest but sweeps to 0.60m', + mounting: { attachTo: 'ceiling', reference: 'canopy' }, + surfaces: [{ id: 'canopy', label: 'Canopy', position: [0, 0.4, 0], size: [0.2, 0.2] }], + parts: [ + { + id: 'rod', + label: 'Downrod', + count: 1, + shapes: [ + { + id: 'shaft', + primitive: 'cylinder', + slot: 'wood', + size: [0.08, 0.4, 0.08], + position: [0, 0.2, 0], + }, + ], + }, + { + id: 'blades', + label: 'Blades', + count: 1, + motion: { + kind: 'spin', + pivot: [0, 0.05, 0], + axis: 'y', + radiansPerSecond: 4, + }, + shapes: [ + { + id: 'blade_x', + primitive: 'box', + slot: 'wood', + size: [1.2, 0.04, 0.14], + position: [0, 0.05, 0], + }, + ], + }, + ], + } + const fan = makeProcedural( + 'procedural-item_sweep_fan', + ceiling.id, + [0, 0, 0], + [0, 0, 0], + fanRecipe, + ) + // Tall cabinet at Z = 0.50m (outside static blade Z=0.07m, inside swept radius Z=0.60m) reaching fan height ~2.44m + const tallCabinet = ItemNode.parse( + item('item_tall_cab', [0, 0, 0.5], [0.4, 2.65, 0.2], 'Cabinet', 0, level.id), + ) + const hits = findItemItemCollisions({ nodes: [level, ceiling, fan, tallCabinet], gap: 0 }) + expect( + hits.some( + (h) => [h.aId, h.bId].sort().join(',') === 'item_tall_cab,procedural-item_sweep_fan', + ), + ).toBe(true) + }) + + test('collectOccupiedFootprints skips non-planar tilted procedural items', () => { + const level = LevelNode.parse({ id: 'level_tilt', name: 'G', level: 0 }) + const tilted = makeProcedural('procedural-item_tilted', level.id, [0, 0, 0], [0.2, 0, 0]) + expect(collectOccupiedFootprints([level, tilted], { levelId: level.id })).toEqual([]) + // Near-zero Euler round-trip tilt (<= 1e-6) matches inspectProceduralItemPlanFootprint and stays checked + const nearZero = makeProcedural( + 'procedural-item_near_zero_tilt', + level.id, + [0, 0, 0], + [1e-9, 0, -1e-9], + ) + const neighbor = makeProcedural('procedural-item_near_zero_neighbor', level.id, [0, 0, 0]) + expect( + collectOccupiedFootprints([level, nearZero], { levelId: level.id }).map((f) => f.id), + ).toEqual([nearZero.id]) + expect( + findItemItemCollisions({ nodes: [level, nearZero, neighbor], levelId: level.id }), + ).toHaveLength(1) + expect(findItemItemCollisions({ nodes: [level, tilted], levelId: level.id })).toEqual([]) + }) + + test('itemHosts, collisions, heights, and scriptItemBoundsInLevel terminate cleanly on parent cycles', () => { + const a = makeProcedural('procedural-item_cyc_a', 'procedural-item_cyc_b', [0, 0, 0]) + const b = makeProcedural('procedural-item_cyc_b', 'procedural-item_cyc_a', [0, 0, 0]) + const itemA = authoredItem('item_cyc_a', 'item_cyc_b', { + name: 'Cycle Lamp A', + category: 'lighting', + size: [0.2, 0.3, 0.2], + }) + const itemB = authoredItem('item_cyc_b', 'item_cyc_a', { + name: 'Cycle Lamp B', + category: 'lighting', + size: [0.2, 0.3, 0.2], + }) + const byId = new Map([ + [a.id, a], + [b.id, b], + [itemA.id, itemA], + [itemB.id, itemB], + ]) + const nodesRecord = Object.fromEntries(byId) + expect([...itemHosts(a, byId)]).toEqual([b.id]) + expect(findItemItemCollisions({ nodes: [a, b, itemA, itemB] })).toEqual([]) + expect(itemHeightsInLevel(itemA, nodesRecord, byId)).toBeUndefined() + expect(scriptItemBoundsInLevel(itemA, nodesRecord)).toBeUndefined() + }) + + test('renaming a generic-category catalog chair preserves its dining-table clearance exemption', () => { + const level = LevelNode.parse({ id: 'level_rename_chair', name: 'G', level: 0 }) + const table = ItemNode.parse({ + id: 'item_opaque_table', + parentId: level.id, + position: [0, 0, 0], + rotation: [0, 0, 0], + name: 'T', + asset: { + id: 'opaque_tbl_01', + category: 'furniture', + name: 'Dining table', + src: '/items/t.glb', + dimensions: [1.4, 0.75, 0.9], + thumbnail: '', + }, + }) + const chair = ItemNode.parse({ + id: 'item_opaque_chair', + parentId: level.id, + position: [0, 0, 0.72], + rotation: [0, 0, 0], + name: 'A', + asset: { + id: 'opaque_chr_01', + category: 'furniture', + name: 'Dining chair', + src: '/items/c.glb', + dimensions: [0.5, 0.85, 0.5], + thumbnail: '', + }, + }) + const issues = layoutIssuesFromScene([level, table, chair]).filter( + (issue) => issue.type === 'item_too_close', + ) + expect(issues).toEqual([]) + }) + + test('proceduralNodePlanCorners returns corners in non-self-intersecting perimeter winding order', () => { + const proc = makeProcedural( + 'procedural-item_winding', + 'level_1', + [1, 0, 2], + [0, Math.PI / 4, 0], + ) + const corners = proceduralNodePlanCorners(proc) + expect(corners).not.toBeNull() + expect(corners!.length).toBe(4) + // Signed shoelace area must be strictly positive (non-bowtie rectangle), not 0! + let twiceArea = 0 + for (let i = 0; i < 4; i++) { + const [x1, z1] = corners![i]! + const [x2, z2] = corners![(i + 1) % 4]! + twiceArea += x1 * z2 - x2 * z1 + } + expect(Math.abs(twiceArea) / 2).toBeGreaterThan(0.5) + // Opposite edges must have equal lengths (a bowtie has diagonals on two edges) + const edges = corners!.map((a, i) => { + const b = corners![(i + 1) % 4]! + return Math.hypot(b[0] - a[0], b[1] - a[1]) + }) + expect(edges[0]!).toBeCloseTo(edges[2]!, 5) + expect(edges[1]!).toBeCloseTo(edges[3]!, 5) + }) + + test('inspectProceduralItemPlanFootprint rejects wallId procedural items consistently', () => { + const wallProc = makeProcedural( + 'procedural-item_wall_mounted', + 'wall_1', + [1, 1, 0], + [0, 0, 0], + overlapBlockRecipe, + { wallId: 'wall_1' }, + ) + expect(inspectProceduralItemPlanFootprint(wallProc)).toEqual({ + ok: false, + reason: 'unsupported_attachment', + }) + }) + + test('named mid-height bookcase shelf waives the supporting shelf only and flags a too-tall vase intersecting the shelf above', () => { + const level = LevelNode.parse({ id: 'level_bookcase', name: 'G', level: 0 }) + // Bookcase: width 0.80 m, depth 0.30 m, height 1.24 m. + // Middle shelf top at y = 0.42 m (named surface), upper shelf at y = [0.82, 0.84] -> 0.40 m clear bay. + // Left/right side panels at x = [-0.40, -0.38] and [0.38, 0.40], back panel at z = [-0.15, -0.13]. + const bookcaseRecipe = { + ...overlapBlockRecipe, + name: 'Bookcase', + parts: [ + { + id: 'frame', + label: 'Frame', + count: 1, + shapes: [ + { + id: 'bottom', + primitive: 'box', + slot: 'wood', + size: [0.8, 0.02, 0.3], + position: [0, 0.01, 0], + }, + { + id: 'mid', + primitive: 'box', + slot: 'wood', + size: [0.76, 0.02, 0.3], + position: [0, 0.41, 0], + }, + { + id: 'upper', + primitive: 'box', + slot: 'wood', + size: [0.76, 0.02, 0.3], + position: [0, 0.83, 0], + }, + { + id: 'top', + primitive: 'box', + slot: 'wood', + size: [0.8, 0.02, 0.3], + position: [0, 1.23, 0], + }, + { + id: 'left', + primitive: 'box', + slot: 'wood', + size: [0.02, 1.24, 0.3], + position: [-0.39, 0.62, 0], + }, + { + id: 'right', + primitive: 'box', + slot: 'wood', + size: [0.02, 1.24, 0.3], + position: [0.39, 0.62, 0], + }, + { + id: 'back', + primitive: 'box', + slot: 'wood', + size: [0.8, 1.24, 0.02], + position: [0, 0.62, -0.14], + }, + ], + }, + ], + surfaces: [ + { + id: 'mid_shelf', + label: 'Middle shelf', + position: [0, 0.42, 0.02], + size: [0.76, 0.28], + }, + ], + } + + const makeVase = (id: string, height: number, xOffset = 0) => + ItemNode.parse({ + id, + parentId: 'procedural-item_bookcase', + position: [xOffset, 0, 0], + rotation: [0, 0, 0], + name: id, + asset: { + id: `vase_${height}`, + category: 'decor', + name: 'Vase', + src: '/items/vase.glb', + dimensions: [0.16, height, 0.16], + thumbnail: '', + }, + }) + + // 1. Short 30 cm vase fits inside the 40 cm shelf opening (even within 5 cm of the back panel) + const shortVase = makeVase('item_short_vase', 0.3) + const bookcaseWithShort = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [shortVase.id], attachments: { [shortVase.id]: 'mid_shelf' } }, + ) + expect( + findItemItemCollisions({ nodes: [level, bookcaseWithShort, shortVase], levelId: level.id }), + ).toEqual([]) + + // 2. Too-tall 60 cm vase intersects the 2 cm upper shelf board (40 cm above mid_shelf) -> overlap! + const tallVase = makeVase('item_tall_vase', 0.6) + const bookcaseWithTall = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [tallVase.id], attachments: { [tallVase.id]: 'mid_shelf' } }, + ) + const tallHits = findItemItemCollisions({ + nodes: [level, bookcaseWithTall, tallVase], + levelId: level.id, + }) + expect(tallHits).toHaveLength(1) + expect(tallHits[0]).toMatchObject({ + aId: bookcaseWithTall.id, + bId: tallVase.id, + violation: 'overlap', + }) + + // 3. Short vase shifted into the left side panel -> overlap! + const sidePenetratingVase = makeVase('item_side_vase', 0.3, -0.35) + const bookcaseWithSideHit = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { + children: [sidePenetratingVase.id], + attachments: { [sidePenetratingVase.id]: 'mid_shelf' }, + }, + ) + const sideHits = findItemItemCollisions({ + nodes: [level, bookcaseWithSideHit, sidePenetratingVase], + levelId: level.id, + }) + expect(sideHits).toHaveLength(1) + expect(sideHits[0]).toMatchObject({ + aId: bookcaseWithSideHit.id, + bId: sidePenetratingVase.id, + violation: 'overlap', + }) + + // 4. Child elevated to slice the bottom 15 mm of the 20 mm upper shelf board ([0.82, 0.84]) -> overlap! + const slicingVase = ItemNode.parse({ + ...makeVase('item_slicing_vase', 0.25), + position: [0, 0.405, 0], + }) + const bookcaseWithSlicing = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 4, 0], + bookcaseRecipe, + { children: [slicingVase.id], attachments: { [slicingVase.id]: 'mid_shelf' } }, + ) + const sliceHits = findItemItemCollisions({ + nodes: [level, bookcaseWithSlicing, slicingVase], + levelId: level.id, + }) + expect(sliceHits).toHaveLength(1) + expect(sliceHits[0]).toMatchObject({ + aId: bookcaseWithSlicing.id, + bId: slicingVase.id, + violation: 'overlap', + }) + + // 5. Script-backed catalog item on a procedural host resolves manifest bounds through + // corrective asset pose, attachment frame, and host floor lift before waiving support. + const slab = SlabNode.parse({ + id: 'slab_bookcase_floor', + parentId: level.id, + polygon: [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], + ], + elevation: 0.05, + thickness: 0.05, + }) + const makeScriptLamp = (id: string) => { + const lamp = authoredItem(id, 'procedural-item_bookcase', { + name: 'Shelf Lamp', + category: 'lighting', + size: [0.16, 0.3, 0.16], + }) + lamp.position = [0, 0, 0] + lamp.rotation = [0, 0, 0] + lamp.scale = [1, 1, 1] + lamp.asset.offset = [0, 0, 0] + lamp.asset.rotation = [0, 0, 0] + lamp.asset.scale = [1, 1, 1] + lamp.source!.manifest.bounds = { + min: [-0.08, -0.2, -0.08], + max: [0.08, 0.1, 0.08], + } + return lamp + } + + // 5a. Identity asset corrections with bounds [-0.20, +0.10] at local Y=0 on mid_shelf (0.42 + 0.05 slab lift): + // occupies level Y [0.27, 0.57], piercing the 0.45..0.47 board -> must report overlap. + const piercingLamp = makeScriptLamp('item_script_lamp_piercing') + const bookcaseWithPiercingLamp = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [piercingLamp.id], attachments: { [piercingLamp.id]: 'mid_shelf' } }, + ) + const piercingNodes = { + [level.id]: level, + [slab.id]: slab, + [bookcaseWithPiercingLamp.id]: bookcaseWithPiercingLamp, + [piercingLamp.id]: piercingLamp, + } + const measuredPiercing = scriptItemBoundsInLevel(piercingLamp, piercingNodes) + expect(measuredPiercing?.levelId).toBe(level.id) + expect(measuredPiercing?.bounds.min[1]).toBeCloseTo(0.27, 6) + expect(measuredPiercing?.bounds.max[1]).toBeCloseTo(0.57, 6) + const toLevel = scriptItemToLevel(piercingLamp, piercingNodes) + expect(toLevel?.([0, -0.2, 0])[1]).toBeCloseTo(0.27, 6) + const piercingHits = findItemItemCollisions({ + nodes: [level, slab, bookcaseWithPiercingLamp, piercingLamp], + levelId: level.id, + }) + expect(piercingHits).toHaveLength(1) + expect(piercingHits[0]).toMatchObject({ + aId: bookcaseWithPiercingLamp.id, + bId: piercingLamp.id, + violation: 'overlap', + }) + + // 5b. Corrective asset.offset [0, 0.20, 0] seats the lamp cleanly on mid_shelf ([0.47, 0.77]) -> fits in 40 cm bay. + const seatedLamp = makeScriptLamp('item_script_lamp_seated') + seatedLamp.asset.offset = [0, 0.2, 0] + const bookcaseWithSeatedLamp = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [seatedLamp.id], attachments: { [seatedLamp.id]: 'mid_shelf' } }, + ) + expect( + findItemItemCollisions({ + nodes: [level, slab, bookcaseWithSeatedLamp, seatedLamp], + levelId: level.id, + }), + ).toEqual([]) + + // 5c. Corrective offset + 2x vertical node scale puts the top at 1.07 (hitting 0.87..0.89 upper board) -> overlap. + const tallScriptLamp = makeScriptLamp('item_script_lamp_tall') + tallScriptLamp.asset.offset = [0, 0.2, 0] + tallScriptLamp.scale = [1, 2, 1] + const bookcaseWithTallScriptLamp = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [tallScriptLamp.id], attachments: { [tallScriptLamp.id]: 'mid_shelf' } }, + ) + const tallScriptHits = findItemItemCollisions({ + nodes: [level, slab, bookcaseWithTallScriptLamp, tallScriptLamp], + levelId: level.id, + }) + expect(tallScriptHits).toHaveLength(1) + expect(tallScriptHits[0]).toMatchObject({ + aId: bookcaseWithTallScriptLamp.id, + bId: tallScriptLamp.id, + violation: 'overlap', + }) + + // 5d. Animated script lamp cannot fall back to catalog itemLevelHeightRange to waive the host board. + const animatedLamp = makeScriptLamp('item_script_lamp_animated') + animatedLamp.source!.manifest.bounds = { + min: [-0.08, 0, -0.08], + max: [0.08, 0.3, 0.08], + } + animatedLamp.source!.manifest.animations = [{ name: 'flicker', duration: 1 }] + const bookcaseWithAnimatedLamp = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [animatedLamp.id], attachments: { [animatedLamp.id]: 'mid_shelf' } }, + ) + expect( + findItemItemCollisions({ + nodes: [level, slab, bookcaseWithAnimatedLamp, animatedLamp], + levelId: level.id, + }), + ).toHaveLength(1) + + // 5e. Plain catalog item with near-zero Euler tilt still resolves height via PLANAR_ROTATION_EPSILON. + const microTiltedVase = ItemNode.parse({ + ...makeVase('item_micro_tilted_vase', 0.3), + rotation: [1e-9, 0, -1e-9], + }) + const bookcaseWithMicroTilt = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { children: [microTiltedVase.id], attachments: { [microTiltedVase.id]: 'mid_shelf' } }, + ) + expect( + findItemItemCollisions({ + nodes: [level, slab, bookcaseWithMicroTilt, microTiltedVase], + levelId: level.id, + }), + ).toEqual([]) + + // 6. Nested descendant (bookcase -> tray -> script lamp) on a rotated bookcase standing on + // a slab with a 0.100 m floor finish (0.050 + 0.001 + 0.100 = 0.151 m) with nonzero X/Z offsets. + const finishedSlab = SlabNode.parse({ + id: 'slab_bookcase_finished', + parentId: level.id, + polygon: [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], + ], + elevation: 0.05, + thickness: 0.05, + surfaceScript: { + kind: 'script', + script: '1'.repeat(64), + artifact: '0'.repeat(64), + params: {}, + inputs: 'finished_slab_inputs', + manifest: { + version: 1, + bounds: { min: [0, 0, 0], max: [6, 0.1, 6] }, + triangles: 12, + materials: [], + }, + }, + }) + const tray = ItemNode.parse({ + id: 'item_shelf_tray', + parentId: 'procedural-item_bookcase', + position: [0.15, 0, -0.02], + rotation: [0, Math.PI / 4, 0], + name: 'Shelf Tray', + asset: { + id: 'tray_4cm', + category: 'decor', + name: 'Tray', + src: '/items/tray.glb', + dimensions: [0.22, 0.04, 0.2], + thumbnail: '', + }, + }) + const makeNestedLamp = (id: string, height: number) => { + const lamp = authoredItem(id, tray.id, { + name: 'Nested Lamp', + category: 'lighting', + size: [0.12, height, 0.12], + }) + lamp.position = [0.04, 0.04, 0.03] + lamp.rotation = [0, 0, 0] + lamp.scale = [1, 1, 1] + lamp.asset.offset = [0, 0, 0] + lamp.asset.rotation = [0, 0, 0] + lamp.asset.scale = [1, 1, 1] + lamp.source!.manifest.bounds = { + min: [-0.06, 0, -0.06], + max: [0.06, height, 0.06], + } + return lamp + } + const shortNestedLamp = makeNestedLamp('item_nested_lamp_short', 0.2) + const bookcaseWithNestedShort = makeProcedural( + 'procedural-item_bookcase', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { + children: [tray.id], + attachments: { [tray.id]: 'mid_shelf' }, + }, + ) + const trayWithShort = { ...tray, children: [shortNestedLamp.id] } + const nestedShortNodes: AnyNode[] = [ + level, + finishedSlab, + bookcaseWithNestedShort, + trayWithShort, + shortNestedLamp, + ] + const nestedShortRecord = Object.fromEntries(nestedShortNodes.map((n) => [n.id, n])) + const nestedBounds = scriptItemBoundsInLevel(shortNestedLamp, nestedShortRecord) + // 0.151 (slab+finish) + 0.42 (mid_shelf) + 0.04 (tray) = 0.611 .. 0.811 + expect(nestedBounds?.bounds.min[1]).toBeCloseTo(0.611, 5) + expect(nestedBounds?.bounds.max[1]).toBeCloseTo(0.811, 5) + // Two-hop rotated X/Z: bookcase yaw=+pi/2 maps local (x,z) -> (2+z, 2-x) + // tray origin in bookcase local: (0.15, 0.42, 0.00); lamp local (0.04, 0.04, 0.03) turned by +pi/4: + const c45 = Math.SQRT1_2 + const localX = 0.15 + 0.04 * c45 + 0.03 * c45 + const localZ = 0.0 + (-0.04 * c45 + 0.03 * c45) + const expectedWorldX = 2 + localZ + const expectedWorldZ = 2 - localX + expect((nestedBounds!.bounds.min[0] + nestedBounds!.bounds.max[0]) / 2).toBeCloseTo( + expectedWorldX, + 5, + ) + expect((nestedBounds!.bounds.min[2] + nestedBounds!.bounds.max[2]) / 2).toBeCloseTo( + expectedWorldZ, + 5, + ) + // Both fit cleanly below the upper shelf board ([0.971, 0.991]) in findItemItemCollisions & verifyScene. + expect( + findItemItemCollisions({ nodes: nestedShortNodes, levelId: level.id, gap: 0 }), + ).toEqual([]) + const nestedLevelWithChildren = { + ...level, + children: [finishedSlab.id, bookcaseWithNestedShort.id], + } + const nestedVerify = verifyScene( + { + ...nestedShortRecord, + [level.id]: nestedLevelWithChildren, + }, + {}, + { activeLevelId: level.id }, + ).result + expect( + nestedVerify.issues.filter( + (issue) => + issue.type === 'item_overlap' && + issue.nodeIds?.includes(bookcaseWithNestedShort.id) && + issue.nodeIds?.includes(shortNestedLamp.id), + ), + ).toEqual([]) + + // 6b. Floor finish lift (0.151 vs bare 0.050) catches a ceiling obstruction hanging down to 0.750 m + // (lamp spans [0.611, 0.811], overlapping by 61 mm). + const ceiling = CeilingNode.parse({ + id: 'ceiling_finish_check', + parentId: level.id, + height: 3, + polygon: [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], + ], + }) + const ceilingObstruction = authoredItem('item_ceiling_obstruction', ceiling.id, { + name: 'Low Pendant', + category: 'lighting', + size: [0.2, 2.24, 0.2], + }) + ceilingObstruction.position = [expectedWorldX, 0, expectedWorldZ] + ceilingObstruction.asset.attachTo = 'ceiling' + ceilingObstruction.source!.manifest.bounds = { + min: [-0.1, -2.24, -0.1], + max: [0.1, 0, 0.1], + } + // ceiling underside = 3 - 0.01 = 2.99; obstruction bottom = 2.99 - 2.24 = 0.750 m + const obstructionHits = findItemItemCollisions({ + nodes: [...nestedShortNodes, ceiling, ceilingObstruction], + levelId: level.id, + gap: 0, + }) + expect( + obstructionHits.some( + (hit) => + (hit.aId === shortNestedLamp.id && hit.bId === ceilingObstruction.id) || + (hit.bId === shortNestedLamp.id && hit.aId === ceilingObstruction.id), + ), + ).toBe(true) + + // 6c. Tall-lamp control: a 45 cm nested lamp on the tray ([0.611, 1.061]) hits the upper board ([0.971, 0.991]). + const tallNestedLamp = makeNestedLamp('item_nested_lamp_tall', 0.45) + const trayWithTall = { ...tray, children: [tallNestedLamp.id] } + const tallNestedHits = findItemItemCollisions({ + nodes: [level, finishedSlab, bookcaseWithNestedShort, trayWithTall, tallNestedLamp], + levelId: level.id, + gap: 0, + }) + expect(tallNestedHits).toContainEqual( + expect.objectContaining({ + aId: bookcaseWithNestedShort.id, + bId: tallNestedLamp.id, + violation: 'overlap', + }), + ) + + // 6d. Moving procedural descendant on a named-attachment surface (bookcase -> 4 cm procedural tray -> riser): + // a riser sliding +0.31 m upward pierces the upper shelf board ([0.971, 0.991]) and must report the same + // 0.006 m² overlap as its frozen +0.31 m endpoint, while a riser sliding -0.31 m downward or staying + // under the board must stay clear. + const proceduralTrayRecipe = { + ...overlapBlockRecipe, + version: 1 as const, + name: 'Procedural Shelf Tray', + parts: [ + { + id: 'tray_body', + label: 'Tray Body', + count: 1, + shapes: [ + { + id: 'deck', + primitive: 'box' as const, + slot: 'wood', + size: [0.22, 0.04, 0.2], + position: [0, 0.02, 0], + }, + ], + }, + ], + surfaces: [{ id: 'top', label: 'Tray Top', position: [0, 0.04, 0], size: [0.2, 0.18] }], + } + const makeSlidingRiserRecipe = (opts: { + axis: 'x' | 'y' | 'z' + distance?: number + carriageHeight?: number + carriageCenterY?: number + }) => { + const carriageHeight = opts.carriageHeight ?? 0.12 + const carriageCenterY = opts.carriageCenterY ?? 0.08 + return { + ...overlapBlockRecipe, + version: 1 as const, + name: 'Shelf Riser', + parts: [ + { + id: 'foot', + label: 'Foot', + count: 1, + shapes: [ + { + id: 'base', + primitive: 'box' as const, + slot: 'wood', + size: [0.1, 0.02, 0.06], + position: [0, 0.01, 0], + }, + ], + }, + { + id: 'carriage', + label: 'Carriage', + count: 1, + ...(opts.distance !== undefined + ? { + motion: { + kind: 'slide' as const, + axis: opts.axis, + distance: opts.distance, + duration: 1, + }, + } + : {}), + shapes: [ + { + id: 'column', + primitive: 'box' as const, + slot: 'wood', + size: [0.1, carriageHeight, 0.06], + position: [0, carriageCenterY, 0], + }, + ], + }, + ], + } + } + + const buildBookcaseTrayRiserScene = ( + riserId: string, + riserDesign: Record, + ): Record => { + let scene: Record = { + [level.id]: { ...level, children: [finishedSlab.id] }, + [finishedSlab.id]: finishedSlab, + } + const placedBookcase = planDesignPlacement(scene, { + id: 'procedural-item_bookcase_riser', + design: bookcaseRecipe, + hostId: level.id, + position: [2, 0, 2], + rotation: Math.PI / 2, + }) + scene = { + ...scene, + [level.id]: { + ...(scene[level.id] as LevelNode), + children: [finishedSlab.id, placedBookcase.node.id], + }, + [placedBookcase.node.id]: placedBookcase.node, + } + const placedTray = planDesignPlacement(scene, { + id: 'procedural-item_shelf_tray', + design: proceduralTrayRecipe, + hostId: placedBookcase.node.id, + surfaceId: 'mid_shelf', + position: [0, 0, 0], + }) + scene = { + ...scene, + [placedBookcase.node.id]: { + ...placedBookcase.node, + children: [placedTray.node.id], + attachments: placedTray.hostUpdate!.attachments, + }, + [placedTray.node.id]: placedTray.node, + } + const placedRiser = planDesignPlacement(scene, { + id: riserId, + design: riserDesign, + hostId: placedTray.node.id, + surfaceId: 'top', + position: [0, 0, 0], + }) + return { + ...scene, + [placedTray.node.id]: { + ...placedTray.node, + children: [placedRiser.node.id], + attachments: placedRiser.hostUpdate!.attachments, + }, + [placedRiser.node.id]: placedRiser.node, + } + } + + // Frozen +0.31 m endpoint control: carriage centered at y = 0.08 + 0.31 = 0.39 ([0.33, 0.45] -> level [0.941, 1.061]). + const frozenEndpointScene = buildBookcaseTrayRiserScene( + 'procedural-item_riser_frozen', + makeSlidingRiserRecipe({ axis: 'y', carriageCenterY: 0.39 }), + ) + const frozenHits = findItemItemCollisions({ + nodes: Object.values(frozenEndpointScene), + levelId: level.id, + gap: 0, + }) + expect(frozenHits).toEqual([ + expect.objectContaining({ + aId: 'procedural-item_bookcase_riser', + bId: 'procedural-item_riser_frozen', + violation: 'overlap', + reading: { overlapAreaM2: 0.006 }, + }), + ]) + + // Moving +0.31 m upward riser: rest [0, 0.14] clears the upper board, swept [0, 0.45] pierces it. + const risingUpScene = buildBookcaseTrayRiserScene( + 'procedural-item_riser_up', + makeSlidingRiserRecipe({ axis: 'y', distance: 0.31 }), + ) + const risingUpHits = findItemItemCollisions({ + nodes: Object.values(risingUpScene), + levelId: level.id, + gap: 0, + }) + expect(risingUpHits).toEqual([ + expect.objectContaining({ + aId: 'procedural-item_bookcase_riser', + bId: 'procedural-item_riser_up', + violation: 'overlap', + reading: { overlapAreaM2: 0.006 }, + }), + ]) + const risingUpVerified = verifyScene(risingUpScene, {}, { activeLevelId: level.id }).result + expect(risingUpVerified.issues).toContainEqual( + expect.objectContaining({ + type: 'item_overlap', + nodeIds: expect.arrayContaining([ + 'procedural-item_bookcase_riser', + 'procedural-item_riser_up', + ]), + }), + ) + + // Control: riser sliding -0.31 m downward within the shelf opening ([0.31, 0.34] -> [0, 0.34], level [0.611, 0.951]) stays clear. + const slidingDownScene = buildBookcaseTrayRiserScene( + 'procedural-item_riser_down', + makeSlidingRiserRecipe({ + axis: 'y', + distance: -0.31, + carriageHeight: 0.03, + carriageCenterY: 0.325, + }), + ) + expect( + findItemItemCollisions({ + nodes: Object.values(slidingDownScene), + levelId: level.id, + gap: 0, + }), + ).toEqual([]) + expect( + verifyScene(slidingDownScene, {}, { activeLevelId: level.id }).result.issues.filter( + (issue) => issue.type === 'item_overlap', + ), + ).toEqual([]) + + // Control: riser sliding +0.20 m upward but staying under the upper board ([0, 0.34], level [0.611, 0.951]) stays clear. + const stayingUnderScene = buildBookcaseTrayRiserScene( + 'procedural-item_riser_under', + makeSlidingRiserRecipe({ axis: 'y', distance: 0.2 }), + ) + expect( + findItemItemCollisions({ + nodes: Object.values(stayingUnderScene), + levelId: level.id, + gap: 0, + }), + ).toEqual([]) + + // Swept X/Z: riser sliding -0.36 m horizontally into the left bookcase panel ([-0.40, -0.38]) must report overlap, + // while +0.10 m staying inside the bay stays clear. + const slidingSideHitScene = buildBookcaseTrayRiserScene( + 'procedural-item_riser_side_hit', + makeSlidingRiserRecipe({ axis: 'x', distance: -0.36 }), + ) + expect( + findItemItemCollisions({ + nodes: Object.values(slidingSideHitScene), + levelId: level.id, + gap: 0, + }), + ).toContainEqual( + expect.objectContaining({ + aId: 'procedural-item_bookcase_riser', + bId: 'procedural-item_riser_side_hit', + violation: 'overlap', + }), + ) + const slidingSideClearScene = buildBookcaseTrayRiserScene( + 'procedural-item_riser_side_clear', + makeSlidingRiserRecipe({ axis: 'x', distance: 0.1 }), + ) + expect( + findItemItemCollisions({ + nodes: Object.values(slidingSideClearScene), + levelId: level.id, + gap: 0, + }), + ).toEqual([]) + + // Overhanging descendant sunk below surfaceY - STACK_TOLERANCE whose rest AABB is outside the + // bookcase's rest AABB, sliding horizontally into mid_shelf: fallback uses sweptPlanAabb so it + // still reports overlap instead of skipping on disjoint rest AABBs. + const overhangingTray = ItemNode.parse({ + ...tray, + id: 'item_overhanging_tray', + parentId: 'procedural-item_bookcase_overhang', + position: [0.46, 0, 0], + rotation: [0, 0, 0], + }) + const sunkenOverhangingRiser = makeProcedural( + 'procedural-item_riser_overhang_sunk', + overhangingTray.id, + [0.05, -0.05, 0], + [0, 0, 0], + makeSlidingRiserRecipe({ axis: 'x', distance: -0.25 }), + ) + const bookcaseWithOverhang = makeProcedural( + 'procedural-item_bookcase_overhang', + level.id, + [2, 0, 2], + [0, Math.PI / 2, 0], + bookcaseRecipe, + { + children: [overhangingTray.id], + attachments: { [overhangingTray.id]: 'mid_shelf' }, + }, + ) + const overhangHits = findItemItemCollisions({ + nodes: [ + level, + finishedSlab, + bookcaseWithOverhang, + { ...overhangingTray, children: [sunkenOverhangingRiser.id] }, + sunkenOverhangingRiser, + ], + levelId: level.id, + gap: 0, + }) + expect(overhangHits).toContainEqual( + expect.objectContaining({ + aId: bookcaseWithOverhang.id, + bId: sunkenOverhangingRiser.id, + violation: 'overlap', + }), + ) + + // v2 part-tree prismatic joint descendant on mid_shelf also sweeps upward into the upper board. + const v2PrismaticRiser = makeProcedural( + 'procedural-item_riser_v2_joint', + 'procedural-item_shelf_tray', + [0, 0, 0], + [0, 0, 0], + { + ...overlapBlockRecipe, + version: 2 as const, + name: 'Prismatic Shelf Riser', + parts: [ + { + id: 'foot', + label: 'Foot', + count: 1, + shapes: [ + { + id: 'base', + primitive: 'box' as const, + slot: 'wood', + size: [0.1, 0.02, 0.06], + position: [0, 0.01, 0], + }, + ], + }, + { + id: 'carriage', + label: 'Carriage', + count: 1, + parent: 'foot', + shapes: [ + { + id: 'column', + primitive: 'box' as const, + slot: 'wood', + size: [0.1, 0.12, 0.06], + position: [0, 0.08, 0], + }, + ], + }, + ], + joints: [ + { + child: 'carriage', + kind: 'prismatic' as const, + origin: [0, 0, 0], + axis: [0, 1, 0], + open: 0.31, + }, + ], + }, + ) + const v2TrayBase = risingUpScene['procedural-item_shelf_tray'] as ProceduralItemNode + const v2SceneNodes: AnyNode[] = [ + risingUpScene[level.id]!, + finishedSlab, + risingUpScene['procedural-item_bookcase_riser']!, + { + ...v2TrayBase, + children: [v2PrismaticRiser.id], + attachments: { [v2PrismaticRiser.id]: 'top' }, + }, + v2PrismaticRiser, + ] + expect( + findItemItemCollisions({ nodes: v2SceneNodes, levelId: level.id, gap: 0 }), + ).toContainEqual( + expect.objectContaining({ + aId: 'procedural-item_bookcase_riser', + bId: v2PrismaticRiser.id, + violation: 'overlap', + }), + ) + }) + + test('ground fallback samples sloping terrain at the node origin rather than off-center footprint center', () => { + const baseTerrain = createTerrainField({ cols: 17, rows: 17, spacing: 1, origin: [-8, -8] }) + const plateau = flattenPatch(baseTerrain, { minX: 2, minZ: 2, maxX: 5, maxZ: 5 }, 2.5) + const building = BuildingNode.parse({ + id: 'building_terrain_origin', + parentId: 'site_terrain_origin', + children: ['level_terrain_origin'], + }) + const level = LevelNode.parse({ + id: 'level_terrain_origin', + parentId: building.id, + name: 'G', + level: 0, + children: ['procedural-item_offcenter_terrain', 'item_plateau_block', 'item_low_block'], + }) + const site = { + id: 'site_terrain_origin', + type: 'site', + object: 'node', + parentId: null, + visible: true, + metadata: {}, + children: [building.id], + terrain: encodeTerrainField(applyHeightPatch(baseTerrain, plateau as never)), + } as unknown as AnyNode + + // Off-center procedural item: node origin at [0, 0, 3] (ground = 0 m), shape centered at local [3, 0.5, 0] + // -> world footprint center at [3, 0, 3] (over the 2.5 m plateau!). + const offCenterRecipe = { + ...overlapBlockRecipe, + name: 'Cantilever Bench', + parts: [ + { + id: 'seat', + label: 'Seat', + count: 1, + shapes: [ + { + id: 'bar', + primitive: 'box' as const, + slot: 'wood', + size: [0.6, 1.0, 0.6], + position: [3, 0.5, 0], + }, + ], + }, + ], + } + const offCenter = makeProcedural( + 'procedural-item_offcenter_terrain', + level.id, + [0, 0, 3], + [0, 0, 0], + offCenterRecipe, + ) + // Floor item at [3, 0, 3] sits on the 2.5 m plateau ([2.5, 3.5]) -> clears offCenter ([0, 1]). + const plateauBlock = ItemNode.parse({ + id: 'item_plateau_block', + parentId: level.id, + position: [3, 0, 3], + rotation: [0, 0, 0], + name: 'Plateau Block', + asset: { + id: 'blk_plateau', + category: 'furniture', + name: 'Block', + src: '/items/b.glb', + dimensions: [0.5, 1.0, 0.5], + thumbnail: '', + }, + }) + // If offCenter had wrongly sampled ground at its footprint center (2.5 m), it would collide with plateauBlock! + expect( + findItemItemCollisions({ + nodes: [site, building, level, offCenter, plateauBlock], + levelId: level.id, + }), + ).toEqual([]) + // Conversely, a block placed down at world y=[0, 1] collides with offCenter. + const lowBlock = ItemNode.parse({ + ...plateauBlock, + id: 'item_low_block', + position: [3, -2.5, 3], + }) + expect( + findItemItemCollisions({ + nodes: [site, building, level, offCenter, lowBlock], + levelId: level.id, + }), + ).toHaveLength(1) + }) + + test('named-attachment host check sweeps moving host parts instead of testing rest pose only', () => { + const level = LevelNode.parse({ + id: 'level_moving_host', + name: 'G', + level: 0, + height: 3, + children: ['ceiling_moving_host'], + }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_moving_host', + parentId: level.id, + height: 3, + polygon: [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], + ], + children: ['procedural-item_sliding_host'], + }) + const makeSlidingCeilingHostRecipe = (slideDistance: number) => ({ + ...overlapBlockRecipe, + version: 2 as const, + name: 'Sliding Ceiling Rack', + mounting: { attachTo: 'ceiling' as const, reference: 'mount' }, + parts: [ + { + id: 'frame', + label: 'Frame', + count: 1, + shapes: [ + { + id: 'top_bar', + primitive: 'box' as const, + slot: 'wood', + size: [1.0, 0.04, 0.4], + position: [0, 0.58, 0], + }, + { + id: 'deck', + primitive: 'box' as const, + slot: 'wood', + size: [1.0, 0.04, 0.4], + position: [0, 0.02, 0], + }, + ], + }, + { + id: 'sliding_panel', + label: 'Sliding Panel', + count: 1, + motion: { + kind: 'slide' as const, + axis: 'x' as const, + distance: slideDistance, + duration: 1, + }, + shapes: [ + { + id: 'panel', + primitive: 'box' as const, + slot: 'wood', + size: [0.1, 0.35, 0.3], + position: [-0.26, 0.25, 0], + }, + ], + }, + ], + surfaces: [ + { id: 'mount', label: 'Mount', position: [0, 0.6, 0], size: [1.0, 0.4] }, + { id: 'deck', label: 'Deck', position: [0, 0.04, 0], size: [0.9, 0.35] }, + ], + }) + + const deckItem = ItemNode.parse({ + id: 'item_on_sliding_deck', + parentId: 'procedural-item_sliding_host', + position: [0, 0, 0], + rotation: [0, 0, 0], + name: 'Deck Box', + asset: { + id: 'deck_box', + category: 'decor', + name: 'Box', + src: '/items/box.glb', + dimensions: [0.16, 0.25, 0.16], + thumbnail: '', + }, + }) + + // Panel at rest is x=[-0.31, -0.21], clear of deckItem x=[-0.08, +0.08], + // but sliding +0.28 m sweeps it to x=[-0.03, +0.07] right through deckItem -> must report overlap. + const hostColliding = makeProcedural( + 'procedural-item_sliding_host', + ceiling.id, + [2, 0, 2], + [0, 0, 0], + makeSlidingCeilingHostRecipe(0.28), + { + children: [deckItem.id], + attachments: { [deckItem.id]: 'deck' }, + }, + ) + const collidingNodes: AnyNode[] = [level, ceiling, hostColliding, deckItem] + const hits = findItemItemCollisions({ nodes: collidingNodes, levelId: level.id, gap: 0 }) + expect(hits).toHaveLength(1) + expect(hits[0]).toMatchObject({ + aId: hostColliding.id, + bId: deckItem.id, + violation: 'overlap', + }) + const verified = verifyScene( + Object.fromEntries(collidingNodes.map((n) => [n.id, n])), + {}, + { activeLevelId: level.id }, + ).result + expect(verified.issues).toContainEqual( + expect.objectContaining({ + type: 'item_overlap', + nodeIds: expect.arrayContaining([hostColliding.id, deckItem.id]), + }), + ) + + // Control: panel slides -0.28 m away from deckItem -> stays clear with 0 collisions. + const hostClear = makeProcedural( + 'procedural-item_sliding_host', + ceiling.id, + [2, 0, 2], + [0, 0, 0], + makeSlidingCeilingHostRecipe(-0.28), + { + children: [deckItem.id], + attachments: { [deckItem.id]: 'deck' }, + }, + ) + expect( + findItemItemCollisions({ + nodes: [level, ceiling, hostClear, deckItem], + levelId: level.id, + gap: 0, + }), + ).toEqual([]) + }) + + test('findBlockedDoors does not fall back to itemLevelHeightRange when heightsOf returns null, and raw source without manifest never throws', () => { + const level = LevelNode.parse({ id: 'level_door_anim', name: 'G', level: 0, height: 3 }) + const wall = WallNode.parse({ + id: 'wall_door_anim', + parentId: level.id, + start: [0, 0], + end: [4, 0], + height: 3, + }) + const door = DoorNode.parse({ + id: 'door_anim', + parentId: wall.id, + position: [2, 0, 0], + width: 0.9, + height: 2.1, + }) + // Animated script item positioned high in Y at the doorway: heightsOf returns null (unproven), + // so findBlockedDoors must NOT fall back to itemLevelHeightRange and waive the doorway block. + const animatedLamp = authoredItem('item_anim_door_lamp', level.id, { + name: 'Animated Door Lamp', + category: 'lighting', + size: [0.5, 0.3, 0.5], + }) + animatedLamp.position = [2, 2.5, 0.4] + animatedLamp.source!.manifest.animations = [{ name: 'bob', duration: 1 }] + const blocked = findBlockedDoors({ + nodes: [level, wall, door, animatedLamp], + levelId: level.id, + }) + expect(blocked).toHaveLength(1) + expect(blocked[0]?.itemId).toBe(animatedLamp.id) + + // Raw item with `source` present but `manifest` missing must not throw in plan corners or underlay check. + const rawSourceItem = { + ...ItemNode.parse({ + id: 'item_raw_source', + parentId: level.id, + position: [1, 0, 1], + rotation: [0, 0, 0], + name: 'Rug', + asset: { + id: 'rug_raw', + category: 'rug', + name: 'Rug', + src: '/items/rug.glb', + dimensions: [1.5, 0.02, 1.0], + thumbnail: '', + }, + }), + source: {}, + } as unknown as ItemNode + expect(() => itemNodePlanCorners(rawSourceItem)).not.toThrow() + expect(() => isFloorUnderlay(rawSourceItem)).not.toThrow() + expect(isFloorUnderlay(rawSourceItem)).toBe(true) + }) + + test('inspectProceduralItemPlanFootprint enforces 3-tuple rotation and proceduralItemLevelPose rejects self-tilted procedural items', () => { + const level = LevelNode.parse({ id: 'level_proc_rot_guard', name: 'G', level: 0 }) + const baseProc = makeProcedural('procedural-item_rot_guard', level.id, [1, 0, 1]) + + const nonArrayRot = { ...baseProc, rotation: null } as unknown as ProceduralItemNode + expect(inspectProceduralItemPlanFootprint(nonArrayRot)).toEqual({ + ok: false, + reason: 'non_finite_rotation', + }) + + const shortTupleRot = { ...baseProc, rotation: [0, 1] } as unknown as ProceduralItemNode + expect(inspectProceduralItemPlanFootprint(shortTupleRot)).toEqual({ + ok: false, + reason: 'non_finite_rotation', + }) + + const tiltedProc = makeProcedural( + 'procedural-item_self_tilted', + level.id, + [1, 0, 1], + [Math.PI / 2, 0, 0], + ) + const byId = new Map([ + [level.id, level], + [tiltedProc.id, tiltedProc], + ]) + expect(proceduralItemLevelPose(tiltedProc, byId)).toBeNull() + + const fiveMicroTilt = makeProcedural( + 'procedural-item_five_micro_tilt', + level.id, + [1, 0, 1], + [5e-6, 0, 0], + ) + const fiveMicroById = new Map([ + [level.id, level], + [fiveMicroTilt.id, fiveMicroTilt], + ]) + expect(proceduralItemLevelPose(fiveMicroTilt, fiveMicroById)).toBeNull() + expect(collectOccupiedFootprints([level, fiveMicroTilt], { levelId: level.id })).toEqual([]) + + // Roof-mounted and block-mounted items are excluded from floorOnly footprints. + const roofMounted = ItemNode.parse({ + id: 'item_roof_mounted', + parentId: level.id, + position: [2, 0, 2], + rotation: [0, 0, 0], + roofSegmentId: 'roof-segment_1', + name: 'Roof Mounted', + asset: { + id: 'roof_unit', + category: 'equipment', + name: 'Unit', + src: '/items/u.glb', + dimensions: [1, 1, 1], + thumbnail: '', + }, + }) + expect( + collectOccupiedFootprints([level, roofMounted], { levelId: level.id, floorOnly: true }), + ).toEqual([]) + + // Malformed intermediate non-floor hosts (e.g. wall-attached or roof-mounted item parented to + // a floor table) and cyclic runtime metadata cannot fabricate vertical separation waivers. + const floorTable = ItemNode.parse( + item('item_floor_table_host', [2, 0, 2], [1, 0.8, 1], 'Table', 0, level.id), + ) + const malformedWallMountIntermediate = ItemNode.parse({ + ...item('item_wall_intermediate', [0, 0.8, 0], [0.4, 0.4, 0.4], 'Sconce', 0, floorTable.id), + asset: { + id: 'wall_sconce', + category: 'lighting', + name: 'Sconce', + src: '/items/s.glb', + dimensions: [0.4, 0.4, 0.4], + thumbnail: '', + attachTo: 'wall', + }, + }) + const hostedCatalogVase = ItemNode.parse( + item( + 'item_vase_on_malformed_host', + [0, 0.4, 0], + [0.2, 0.3, 0.2], + 'Vase', + 0, + malformedWallMountIntermediate.id, + ), + ) + const hostedProceduralBox = makeProcedural( + 'procedural-item_on_malformed_host', + malformedWallMountIntermediate.id, + [0, 0.4, 0], + [0, 0, 0], + ) + const malformedNodesList: AnyNode[] = [ + level, + { ...floorTable, children: [malformedWallMountIntermediate.id] }, + { + ...malformedWallMountIntermediate, + children: [hostedCatalogVase.id, hostedProceduralBox.id], + }, + hostedCatalogVase, + hostedProceduralBox, + ] + const malformedRecord = Object.fromEntries(malformedNodesList.map((n) => [n.id, n])) + const malformedById = new Map(malformedNodesList.map((n) => [n.id, n])) + expect(itemHeightsInLevel(hostedCatalogVase, malformedRecord, malformedById)).toBeUndefined() + const malformedHits = findItemItemCollisions({ + nodes: malformedNodesList, + levelId: level.id, + gap: 0, + }) + expect( + malformedHits.some( + (hit) => + (hit.aId === floorTable.id && hit.bId === hostedCatalogVase.id) || + (hit.bId === floorTable.id && hit.aId === hostedCatalogVase.id), + ), + ).toBe(true) + expect( + malformedHits.some( + (hit) => + (hit.aId === floorTable.id && hit.bId === hostedProceduralBox.id) || + (hit.bId === floorTable.id && hit.aId === hostedProceduralBox.id), + ), + ).toBe(true) + + const cyclicMeta: Record = {} + cyclicMeta.self = cyclicMeta + const cyclicLevel = { ...level, metadata: cyclicMeta } as unknown as AnyNode + expect(() => + findItemItemCollisions({ nodes: [cyclicLevel, floorTable], levelId: level.id, gap: 0 }), + ).not.toThrow() + + // Shared non-cyclic DAG tuple references on host nodes remain valid finite context. + const sharedZero: [number, number, number] = [0, 0, 0] + const dagTable = { + ...floorTable, + position: sharedZero, + rotation: sharedZero, + } + const dagTopVase = ItemNode.parse( + item('item_vase_on_dag_table', [0, 0.8, 0], [0.2, 0.3, 0.2], 'Vase', 0, dagTable.id), + ) + expect( + findItemItemCollisions({ + nodes: [level, { ...dagTable, children: [dagTopVase.id] }, dagTopVase], + levelId: level.id, + gap: 0, + }), + ).toEqual([]) + }) + + test('level-parented attachTo items preserve vertical separation and wall-panelling real strips', () => { + const level = LevelNode.parse({ id: 'level_mounted_heights', name: 'G', level: 0, height: 3 }) + const wall = WallNode.parse({ + id: 'wall_mounted_heights', + parentId: level.id, + start: [0, 0], + end: [5, 0], + height: 3, + thickness: 0.15, + }) + const door = DoorNode.parse({ + id: 'door_mounted_heights', + parentId: wall.id, + wallId: wall.id, + position: [2.5, 1.05, 0], + width: 0.9, + height: 2.1, + }) + wall.children = [door.id] + + const floorTable = ItemNode.parse( + item('item_table_under_mounted', [2.5, 0, 1.2], [1.2, 0.75, 0.8], 'Table', 0, level.id), + ) + + // Level-parented catalog chandelier with attachTo: 'ceiling' at y = 2.25 m overlaps both the door keep-out + // (z <= 0.65) and the 0.75 m table (z >= 0.80) in plan, yet clears both vertically. + const levelCatalogPendant = ItemNode.parse({ + ...item('item_level_pendant', [2.5, 2.25, 0.7], [0.8, 0.4, 0.8], 'Chandelier', 0, level.id), + asset: { + id: 'chandelier_01', + category: 'lighting', + name: 'Chandelier', + src: '/items/chandelier.glb', + dimensions: [0.8, 0.4, 0.8], + thumbnail: '', + attachTo: 'ceiling', + }, + }) + // Lowered to y = 0.50 m, the same chandelier genuinely collides with the table and blocks the door. + const lowCatalogPendant = { + ...levelCatalogPendant, + id: 'item_level_pendant_low' as const, + position: [2.5, 0.5, 0.7] as [number, number, number], + } + + // Level-parented room-wide wall panelling with attachTo: 'wall': thin strip along z = [-2.05, -1.99] + // while bounds span [-2.5..2.5, 0..2.4, -2.05..2.05], enclosing the table and doorway in plan. + const panelling = authoredItem('item_room_panelling', level.id, { + name: 'Boiserie', + category: 'panelling', + size: [5, 2.4, 4.1], + }) + panelling.position = [2.5, 0, 1.5] + panelling.asset.attachTo = 'wall' + panelling.source!.manifest.bounds = { + min: [-2.5, 0, -2.05], + max: [2.5, 2.4, 2.05], + } + panelling.source!.manifest.surfaces = [ + { + y: 2.4, + polygon: [ + [-2.5, 1.99], + [2.5, 1.99], + [2.5, 2.05], + [-2.5, 2.05], + ], + }, + ] + panelling.source!.manifest.undersides = [] + + const cleanNodes: AnyNode[] = [level, wall, door, floorTable, levelCatalogPendant, panelling] + const cleanRecord = Object.fromEntries(cleanNodes.map((n) => [n.id, n])) + const cleanById = new Map(cleanNodes.map((n) => [n.id, n])) + + expect(itemHeightsInLevel(levelCatalogPendant, cleanRecord, cleanById)).toEqual({ + levelId: level.id, + min: 2.25, + max: 2.65, + }) + expect(itemSolidsInLevel(panelling, cleanRecord)).not.toBeNull() + expect(findItemItemCollisions({ nodes: cleanNodes, levelId: level.id })).toEqual([]) + expect(findBlockedDoors({ nodes: cleanNodes, levelId: level.id })).toEqual([]) + + expect( + findItemItemCollisions({ + nodes: [level, floorTable, lowCatalogPendant], + levelId: level.id, + }), + ).toHaveLength(1) + expect( + findBlockedDoors({ + nodes: [level, wall, door, lowCatalogPendant], + levelId: level.id, + }), + ).toHaveLength(1) + }) + + test('floor procedural items sweep moving parts into neighbors without inflating unmoving body regions', () => { + const level = LevelNode.parse({ id: 'level_floor_motion', name: 'G', level: 0, height: 3 }) + + // Wide floor sideboard: static body spans x = [-1.0, +1.0], y = [0, 0.75], z = [-0.25, +0.25]; + // left drawer (x = [-0.9, -0.4], y = [0.55, 0.72]) slides +0.45 m forward in +Z to z = +0.70; + // left flip-up lid (x = [-0.9, -0.4], y = [0.75, 0.78]) slides +0.42 m upward in +Y to y = 1.20. + const sideboardRecipe = { + ...overlapBlockRecipe, + version: 1 as const, + name: 'Animated Sideboard', + parts: [ + { + id: 'carcass', + label: 'Carcass', + count: 1, + shapes: [ + { + id: 'cabinet_body', + primitive: 'box' as const, + slot: 'wood', + size: [2.0, 0.75, 0.5], + position: [0, 0.375, 0], + }, + ], + }, + { + id: 'left_drawer', + label: 'Left Drawer', + count: 1, + motion: { + kind: 'slide' as const, + axis: 'z' as const, + distance: 0.45, + duration: 1, + }, + shapes: [ + { + id: 'drawer_box', + primitive: 'box' as const, + slot: 'wood', + size: [0.5, 0.17, 0.45], + position: [-0.65, 0.635, 0.025], + }, + ], + }, + { + id: 'left_lid', + label: 'Left Flip Lid', + count: 1, + motion: { + kind: 'slide' as const, + axis: 'y' as const, + distance: 0.42, + duration: 1, + }, + shapes: [ + { + id: 'lid_panel', + primitive: 'box' as const, + slot: 'wood', + size: [0.5, 0.03, 0.4], + position: [-0.65, 0.765, 0], + }, + ], + }, + ], + } + const sideboard = makeProcedural( + 'procedural-item_sideboard_motion', + level.id, + [0, 0, 0], + [0, 0, 0], + sideboardRecipe, + ) + + // 1. Occupied footprint includes the forward +0.45 m drawer slide (maxZ = 0.25 + 0.45 = 0.70). + const [occ] = collectOccupiedFootprints([level, sideboard], { levelId: level.id }) + expect(occ?.aabb.maxZ).toBeCloseTo(0.7, 5) + + // 2. Tall chair directly in front of the left drawer (x = [-0.85, -0.45], z = [0.45, 0.85], y = [0, 0.85]) + // is outside the rest footprint (z <= 0.25) yet hit by the sliding drawer (z <= 0.70). + const chairInDrawerPath = ItemNode.parse( + item('item_chair_drawer_hit', [-0.65, 0, 0.65], [0.4, 0.85, 0.4], 'Chair', 0, level.id), + ) + expect( + findItemItemCollisions({ + nodes: [level, sideboard, chairInDrawerPath], + levelId: level.id, + gap: 0.08, + }), + ).toContainEqual( + expect.objectContaining({ + aId: sideboard.id, + bId: chairInDrawerPath.id, + violation: 'overlap', + }), + ) + + // 3. Same chair in front of the UNMOVING right side (x = [+0.45, +0.85], z = [0.45, 0.85], 0.20 m clear of rest z = 0.25) + // must NOT be falsely flagged. + const chairOnStaticRight = ItemNode.parse( + item('item_chair_static_right', [0.65, 0, 0.65], [0.4, 0.85, 0.4], 'Chair', 0, level.id), + ) + expect( + findItemItemCollisions({ + nodes: [level, sideboard, chairOnStaticRight], + levelId: level.id, + gap: 0.08, + }), + ).toEqual([]) + + // 4. Low footstool (y = [0, 0.40]) under the left drawer path (drawer bottom y = 0.55) clears vertically! + const lowStoolUnderDrawer = ItemNode.parse( + item('item_stool_under_drawer', [-0.65, 0, 0.65], [0.4, 0.4, 0.4], 'Stool', 0, level.id), + ) + expect( + findItemItemCollisions({ + nodes: [level, sideboard, lowStoolUnderDrawer], + levelId: level.id, + gap: 0.08, + }), + ).toEqual([]) + + // 5. Overhead pendant hanging at y = [0.95, 1.35] over the UNMOVING right side (x = +0.65, carcass top y = 0.75) + // must NOT be flagged by the left lid's y = 1.20 swept height; whereas over the left lid (x = -0.65) it collides. + const ceiling = CeilingNode.parse({ + id: 'ceiling_sideboard_motion', + parentId: level.id, + height: 3, + polygon: [ + [-3, -3], + [3, -3], + [3, 3], + [-3, 3], + ], + }) + const makeOverPendant = (id: string, x: number) => { + const p = authoredItem(id, ceiling.id, { + name: 'Pendant', + category: 'lighting', + size: [0.3, 2.04, 0.3], + }) + p.position = [x, 0, 0] + p.asset.attachTo = 'ceiling' + // ceiling underside = 2.99 -> bottom = 2.99 - 2.04 = 0.95 m (above 0.75 m carcass, inside 1.20 m left lid) + p.source!.manifest.bounds = { + min: [-0.15, -2.04, -0.15], + max: [0.15, 0, 0.15], + } + return p + } + const pendantRight = makeOverPendant('item_pendant_right_clear', 0.65) + const pendantLeft = makeOverPendant('item_pendant_left_hit', -0.65) + + expect( + findItemItemCollisions({ + nodes: [level, ceiling, sideboard, pendantRight], + levelId: level.id, + gap: 0.08, + }), + ).toEqual([]) + expect( + findItemItemCollisions({ + nodes: [level, ceiling, sideboard, pendantLeft], + levelId: level.id, + gap: 0.08, + }), + ).toContainEqual( + expect.objectContaining({ + aId: sideboard.id, + bId: pendantLeft.id, + violation: 'overlap', + }), + ) + + // When moving parts are omitted/gated out (no emitted shape carries motionGroup despite jointGroups), + // vertical separation stays intact and the left pendant at 0.95 m clears the 0.75 m carcass. + const staticOnlySideboard: ProceduralItemNode = { + ...sideboard, + id: 'procedural-item_sideboard_zero_drawers', + recipe: { + ...sideboard.recipe, + version: 2 as const, + jointGroups: [ + { + id: 'unused_lid_joint', + kind: 'slide' as const, + axis: 'y' as const, + distance: 0.5, + }, + ], + parts: sideboard.recipe.parts.filter((part) => !('motion' in part && part.motion)), + }, + } + expect( + findItemItemCollisions({ + nodes: [level, ceiling, staticOnlySideboard, pendantLeft], + levelId: level.id, + gap: 0.08, + }), + ).toEqual([]) + }) + }) }) diff --git a/packages/core/src/agent-operations/layout-clearance.ts b/packages/core/src/agent-operations/layout-clearance.ts index 4374bd84b3..6f24928d31 100644 --- a/packages/core/src/agent-operations/layout-clearance.ts +++ b/packages/core/src/agent-operations/layout-clearance.ts @@ -9,9 +9,15 @@ */ import { floorConstructionLift, liftedManualSlab } from '../lib/floor-construction-lift' +import { floorFinishTopAt } from '../lib/floor-script' import { selectSlabSupportForItem } from '../lib/item-slab-support' import { getRenderableSlabPolygon } from '../lib/slab-polygon' import { levelBaseElevationAt } from '../lib/terrain-support-query' +import { jointReach } from '../procedural-items/joints' +import type { ProceduralItemNode } from '../procedural-items/node' +import { proceduralFootprint } from '../procedural-items/node-frames' +import { type Evaluation, evaluateRecipe, shapeBounds } from '../procedural-items/recipe' +import type { Frame } from '../procedural-items/spatial' import { type Bounds, boundsOf, @@ -20,6 +26,7 @@ import { rotateVector, transformPoint, } from '../procedural-items/spatial' +import { nodeLevelFrame } from '../procedural-items/world-pose' import { type AnyNode, getScaledDimensions, type ItemNode } from '../schema' import { resolveCeilingHeight } from '../services/level-height' import { CEILING_DRAW_OFFSET } from '../services/storey' @@ -30,15 +37,25 @@ import { type DoorClearZone, type DoorSide, findBlockedDoors as findBlockedDoorsByBox, + hasNonFloorItemAttachment, itemNodePlanAabb, itemNodePlanCorners, itemPlanAabb, + PLANAR_ROTATION_EPSILON, type PlanAabb, + proceduralNodePlanAabb, resolveNodeLevelId, } from './door-clearance' import { designedTogether, isFloorUnderlay, isWallDressing, wallBoundWord } from './furniture-kind' -import { type ItemSolid, manifestSolids, relateSolids, type ToLevel } from './item-solids' -import { itemLevelHeightRange, itemLevelPose, itemPlanAabbInLevel } from './item-space' +import { type ItemSolid, manifestSolids, relateSolids } from './item-solids' +import { + itemLevelHeightRange, + itemLevelPose, + itemPlanAabbInLevel, + proceduralItemLevelPose, + proceduralPlanAabbInLevel, + proceduralPlanCornersInLevel, +} from './item-space' import { axisOverlap, type ClearMove, @@ -53,9 +70,11 @@ import { distanceToSegment, pointInPolygon, type Vec2 } from './plan-geometry' export { aabbsOverlap, collectDoorKeepouts, + inspectProceduralItemPlanFootprint, itemNodePlanAabb, itemPlanAabb, type PlanAabb, + proceduralNodePlanAabb, resolveNodeLevelId, } from './door-clearance' @@ -137,24 +156,101 @@ function collisionMessage( } export function nodeItemAabb(node: AnyNode): PlanAabb | null { - return itemNodePlanAabb(node) + return node.type === 'procedural-item' ? proceduralNodePlanAabb(node) : itemNodePlanAabb(node) +} + +function hasNonFloorHost(node: AnyNode, byId: Map): boolean { + let current: AnyNode | undefined = node + const seen = new Set() + while (current && current.type !== 'level') { + if (seen.has(current.id)) return true + seen.add(current.id) + if ( + current.type === 'ceiling' || + current.type === 'wall' || + current.type === 'roof' || + current.type === 'roof-segment' || + current.type === 'block' + ) + return true + if (current.type === 'procedural-item') { + const attach = current.recipe?.mounting?.attachTo + if (current.wallId || (attach != null && (attach as string) !== 'floor')) return true + } else if (current.type === 'item' && hasNonFloorItemAttachment(current)) { + return true + } + current = current.parentId ? byId.get(current.parentId) : undefined + } + return false +} + +function cachedEvaluateProcedural( + node: ProceduralItemNode, + cache: Map, +): Evaluation | null { + if (cache.has(node.id)) return cache.get(node.id) ?? null + if (!Array.isArray(node.recipe?.parts)) { + cache.set(node.id, null) + return null + } + try { + const evaluated = evaluateRecipe(node.recipe, node.parameters) + cache.set(node.id, evaluated) + return evaluated + } catch { + cache.set(node.id, null) + return null + } +} + +function recordFromNodes(nodes: readonly AnyNode[]): Record { + const out: Record = Object.create(null) + for (const node of nodes) out[node.id] = node + return out } export function collectOccupiedFootprints( nodes: Iterable, - options?: { levelId?: string; excludeIds?: Set; floorOnly?: boolean }, + options?: { + levelId?: string + excludeIds?: Set + floorOnly?: boolean + evalCache?: Map + frameCache?: Map + nodesRecord?: Record + }, ): OccupiedFootprint[] { const list = [...nodes] const byId = new Map(list.map((n) => [n.id, n])) + const nodesRecord = options?.nodesRecord ?? recordFromNodes(list) + const evalCache = options?.evalCache ?? new Map() + const frameCache = options?.frameCache ?? new Map() const out: OccupiedFootprint[] = [] for (const node of list) { - if (node.type !== 'item') continue + if (node.type !== 'item' && node.type !== 'procedural-item') continue if (options?.excludeIds?.has(node.id)) continue - const attach = node.asset?.attachTo - if ( - options?.floorOnly && - (attach === 'wall' || attach === 'wall-side' || attach === 'ceiling') - ) { + if (options?.floorOnly && hasNonFloorHost(node, byId)) continue + if (node.type === 'procedural-item') { + const levelId = resolveNodeLevelId(node.id, byId) + if (options?.levelId && levelId !== options.levelId) continue + if (levelId && node.parentId === levelId && isFloorUnderlay(node)) continue + if (node.wallId || (node.parentId && byId.get(node.parentId)?.type === 'wall')) continue + if (!planarRotation(node.rotation)) continue + const evaluated = cachedEvaluateProcedural(node, evalCache) + if (!evaluated) continue + const aabb = proceduralPlanAabbInLevel(node, byId, { + nodes: nodesRecord, + frameCache, + evaluated, + }) + if (!aabb) continue + const name = node.name ?? node.recipe?.name + out.push({ + id: node.id, + name: typeof name === 'string' ? name : undefined, + levelId, + aabb, + }) continue } const levelId = resolveNodeLevelId(node.id, byId) @@ -162,11 +258,7 @@ export function collectOccupiedFootprints( if (levelId && node.parentId === levelId && isFloorUnderlay(node)) continue // A wall's children keep wall-local coordinates and are read by the wall observations. if (node.parentId && byId.get(node.parentId)?.type === 'wall') continue - // Floor packing: prefer level-parented items (not ceiling-hosted children). - if (options?.floorOnly && node.parentId && levelId && node.parentId !== levelId) { - if (attach === 'wall' || attach === 'wall-side' || attach === 'ceiling') continue - } - const aabb = itemPlanAabbInLevel(node, byId) + const aabb = itemPlanAabbInLevel(node, byId, { nodes: nodesRecord, frameCache }) if (!aabb) continue const name = node.name ?? node.asset?.name out.push({ @@ -190,21 +282,49 @@ function finiteVec3(value: unknown): value is [number, number, number] { } function planarRotation(value: unknown): value is [number, number, number] { - return finiteVec3(value) && value[0] === 0 && value[2] === 0 + return ( + finiteVec3(value) && + Math.abs(value[0]) <= PLANAR_ROTATION_EPSILON && + Math.abs(value[2]) <= PLANAR_ROTATION_EPSILON + ) +} + +function ownNode( + nodes: Readonly>, + id: string | null | undefined, +): AnyNode | undefined { + return typeof id === 'string' && Object.hasOwn(nodes, id) ? nodes[id] : undefined } -function finiteNumbers(value: unknown): boolean { +function finiteNumbers( + value: unknown, + memo = new WeakMap(), +): boolean { if (typeof value === 'number') return Number.isFinite(value) - if (Array.isArray(value)) return value.every(finiteNumbers) - if (value && typeof value === 'object') return Object.values(value).every(finiteNumbers) + if (value && typeof value === 'object') { + const state = memo.get(value) + if (state !== undefined) return state === true + memo.set(value, 'visiting') + const ok = Array.isArray(value) + ? value.every((entry) => finiteNumbers(entry, memo)) + : Object.values(value).every((entry) => finiteNumbers(entry, memo)) + memo.set(value, ok) + return ok + } return true } -/** Snapshot counterpart of the item floorPlaced support election; never reads the live grid. */ -function itemFloorLift(node: ItemNode, nodes: Record): number { - // The renderer's item floorPlaced.applies skips corrective surface attachments. - if (node.asset.attachTo) return 0 +function electFloorPlacedLift( + node: (ItemNode | ProceduralItemNode) & { supportSlabId?: string }, + footprint: { + position: [number, number, number] + dimensions: [number, number, number] + rotation: [number, number, number] + }, + nodes: Record, +): number { const levelId = node.parentId! + // Sample ground at the node's own XZ origin to match floor-placed-elevation.ts. const ground = () => levelBaseElevationAt(nodes, levelId, node.position[0], node.position[2]) + floorConstructionLift(nodes, node) @@ -226,7 +346,7 @@ function itemFloorLift(node: ItemNode, nodes: Record): number { }) const support = selectSlabSupportForItem( slabs, - { position: node.position, dimensions: getScaledDimensions(node), rotation: node.rotation }, + footprint, (slab) => getRenderableSlabPolygon(slab, { walls, @@ -234,18 +354,159 @@ function itemFloorLift(node: ItemNode, nodes: Record): number { }), { preferredSlabId: node.supportSlabId }, ) - return support ? support.elevation : ground() + if (!support) return ground() + return ( + floorFinishTopAt(nodes, levelId, support.id, footprint.position[0], footprint.position[2]) ?? + support.elevation + ) } -/** - * Only script manifests supply raw bounds for the renderer's corrective asset pose. - * Catalog dimensions describe a plan box, not proof of the raw model's Y origin. - */ -export function scriptItemBoundsInLevel( +/** Snapshot counterpart of the item floorPlaced support election; never reads the live grid. */ +function itemFloorLift(node: ItemNode, nodes: Record): number { + // The renderer's item floorPlaced.applies skips corrective surface attachments. + if (node.asset.attachTo) return 0 + return electFloorPlacedLift( + node, + { position: node.position, dimensions: getScaledDimensions(node), rotation: node.rotation }, + nodes, + ) +} + +function proceduralFloorLift(node: ProceduralItemNode, nodes: Record): number { + if (node.recipe?.mounting || node.wallId) return 0 + const fp = proceduralFootprint(node) + return electFloorPlacedLift(node, fp, nodes) +} + +function hasItemHostRef(node: ItemNode): boolean { + return Boolean(node.wallId || node.roofSegmentId || node.roofFace || node.blockFaceId) +} + +function resolveHostChainBaseElevation( + root: ItemNode | ProceduralItemNode, + nodes: Record, +): { levelId: string; baseY: number } | undefined { + const rootParent = ownNode(nodes, root.parentId) + if (rootParent?.type === 'level' && finiteNumbers(rootParent)) { + if (root.type === 'procedural-item' && (root.wallId || root.recipe?.mounting)) { + return undefined + } + if (root.type === 'item' && hasItemHostRef(root)) { + return undefined + } + try { + const baseY = + root.type === 'procedural-item' + ? proceduralFloorLift(root, nodes) + : itemFloorLift(root, nodes) + return Number.isFinite(baseY) ? { levelId: rootParent.id, baseY } : undefined + } catch { + return undefined + } + } + if ( + root.type === 'procedural-item' && + !root.wallId && + root.recipe?.mounting?.attachTo === 'ceiling' && + rootParent?.type === 'ceiling' && + rootParent.parentId + ) { + const level = ownNode(nodes, rootParent.parentId) + if (level?.type !== 'level' || !finiteNumbers(level) || !finiteNumbers(rootParent)) { + return undefined + } + try { + evaluateRecipe(root.recipe, root.parameters) + const baseY = resolveCeilingHeight(rootParent, nodes) - CEILING_DRAW_OFFSET + return Number.isFinite(baseY) ? { levelId: level.id, baseY } : undefined + } catch { + return undefined + } + } + return undefined +} + +function resolveValidHostChainRoot( + node: ItemNode | ProceduralItemNode, + nodes: Record, +): ItemNode | ProceduralItemNode | undefined { + if (node.type === 'item' && hasItemHostRef(node)) return undefined + const directParent = ownNode(nodes, node.parentId) + if ( + node.type === 'item' && + node.asset?.attachTo && + (directParent?.type === 'item' || directParent?.type === 'procedural-item') + ) { + return undefined + } + let root: ItemNode | ProceduralItemNode = node + const seen = new Set([node.id]) + while (root.parentId) { + const parentKey: string = root.parentId + if (seen.has(parentKey)) return undefined + seen.add(parentKey) + const nextParent = ownNode(nodes, parentKey) + if (nextParent?.type !== 'item' && nextParent?.type !== 'procedural-item') break + if (!finiteNumbers(nextParent)) return undefined + if (nextParent.type === 'procedural-item') { + if (nextParent.wallId) return undefined + const attach = nextParent.recipe?.mounting?.attachTo + if (attach === 'wall-side') return undefined + if (nextParent.recipe?.mounting && attach !== 'ceiling') return undefined + if (attach === 'ceiling') { + const grandParent = ownNode(nodes, nextParent.parentId) + if (grandParent?.type !== 'ceiling' || !Array.isArray(nextParent.recipe?.parts)) { + return undefined + } + } + } else if (hasNonFloorItemAttachment(nextParent)) { + return undefined + } + root = nextParent + } + return root +} + +function isPlanarFrame(pose: Frame): boolean { + const up = pose.axes[1] + return Math.abs(up[0]) <= 1e-5 && Math.abs(up[1] - 1) <= 1e-5 && Math.abs(up[2]) <= 1e-5 +} + +function transformScriptManifestPoint( + node: ItemNode, + assetScale: [number, number, number], + pose: Frame, + point: [number, number, number], +): [number, number, number] { + // Match the model groups: corrective asset pose is inside the node-scale group. + const rotated = rotateVector( + point.map((value, axis) => value * assetScale[axis]!) as [number, number, number], + node.asset.rotation, + ) + return transformPoint( + pose, + rotated.map((value, axis) => (value + node.asset.offset[axis]!) * node.scale[axis]!) as [ + number, + number, + number, + ], + ) +} + +function scriptItemLevelFrame( node: AnyNode | undefined, nodes: Record, -): { levelId: string; bounds: Bounds; corners: [number, number, number][] } | undefined { - if (node?.type !== 'item' || node.roofSegmentId || node.blockFaceId) return + frameCache?: Map, +): + | { + node: ItemNode + levelId: string + pose: Frame + bounds: { min: [number, number, number]; max: [number, number, number] } + assetScale: [number, number, number] + } + | undefined { + if (node?.type !== 'item' || hasItemHostRef(node)) return const bounds = node.source?.manifest?.bounds const assetScale = node.asset.scale ?? [1, 1, 1] if ( @@ -266,41 +527,68 @@ export function scriptItemBoundsInLevel( node.asset.dimensions.some((size) => size <= 0) ) return - const parent = node.parentId ? nodes[node.parentId] : undefined - const level = - parent?.type === 'level' - ? parent - : parent?.type === 'ceiling' && parent.parentId - ? nodes[parent.parentId] - : undefined - if (level?.type !== 'level' || !finiteNumbers(level) || !finiteNumbers(parent)) return - try { - const hostY = - parent?.type === 'ceiling' - ? resolveCeilingHeight(parent, nodes) - CEILING_DRAW_OFFSET - : itemFloorLift(node, nodes) - const pose = frame( - [node.position[0], hostY + node.position[1], node.position[2]], - node.rotation, - ) - // Match the model groups: corrective asset pose is inside the node-scale group. - const corners = boxCorners(bounds.min, bounds.max).map((point) => { - const rotated = rotateVector( - point.map((value, axis) => value * assetScale[axis]!) as [number, number, number], - node.asset.rotation, - ) - return transformPoint( - pose, - rotated.map((value, axis) => (value + node.asset.offset[axis]!) * node.scale[axis]!) as [ - number, - number, - number, - ], + const parent = ownNode(nodes, node.parentId) + if (parent?.type === 'level' || (parent?.type === 'ceiling' && parent.parentId)) { + const level = parent.type === 'level' ? parent : ownNode(nodes, parent.parentId) + if (level?.type !== 'level' || !finiteNumbers(level) || !finiteNumbers(parent)) return + try { + const hostY = + parent.type === 'ceiling' + ? resolveCeilingHeight(parent, nodes) - CEILING_DRAW_OFFSET + : itemFloorLift(node, nodes) + if (!Number.isFinite(hostY)) return + const pose = frame( + [node.position[0], hostY + node.position[1], node.position[2]], + node.rotation, ) + return { node, levelId: level.id, pose, bounds, assetScale } + } catch { + // Malformed or unsupported support geometry is not evidence of separation. + return + } + } + if (parent?.type !== 'item' && parent?.type !== 'procedural-item') return + const root = resolveValidHostChainRoot(node, nodes) + if (!root) return + const resolvedRoot = resolveHostChainBaseElevation(root, nodes) + if (!resolvedRoot) return + try { + const localFrame = nodeLevelFrame(node.id, nodes, new Set(), { + planOnly: true, + cache: frameCache, }) - if (corners.every(finiteVec3)) return { levelId: level.id, bounds: boundsOf(corners), corners } + if (!finiteVec3(localFrame.position) || !localFrame.axes.every(finiteVec3)) return + const pose: Frame = { + position: [ + localFrame.position[0], + localFrame.position[1] + resolvedRoot.baseY, + localFrame.position[2], + ], + axes: localFrame.axes, + } + if (!finiteVec3(pose.position)) return + return { node, levelId: resolvedRoot.levelId, pose, bounds, assetScale } } catch { - // Malformed or unsupported support geometry is not evidence of separation. + // Malformed or unsupported host-chain geometry is not evidence of separation. + return + } +} + +/** + * Only script manifests supply raw bounds for the renderer's corrective asset pose. + * Catalog dimensions describe a plan box, not proof of the raw model's Y origin. + */ +export function scriptItemBoundsInLevel( + node: AnyNode | undefined, + nodes: Record, +): { levelId: string; bounds: Bounds; corners: [number, number, number][] } | undefined { + const resolved = scriptItemLevelFrame(node, nodes) + if (!resolved) return + const corners = boxCorners(resolved.bounds.min, resolved.bounds.max).map((point) => + transformScriptManifestPoint(resolved.node, resolved.assetScale, resolved.pose, point), + ) + if (corners.every(finiteVec3)) { + return { levelId: resolved.levelId, bounds: boundsOf(corners), corners } } } @@ -313,36 +601,20 @@ export function scriptItemToLevel( node: ItemNode, nodes: Record, ): ((point: [number, number, number]) => [number, number, number]) | undefined { - const resolved = scriptItemBoundsInLevel(node, nodes) - const origin = node.source?.manifest.bounds.min - const corner = resolved?.corners[0] - if (!(origin && corner)) return - const corrected = (point: [number, number, number]) => { - const asset = rotateVector( - point.map((value, axis) => value * (node.asset.scale?.[axis] ?? 1)) as [ - number, - number, - number, - ], - node.asset.rotation, - ) - return rotateVector( - asset.map( - (value, axis) => (value + (node.asset.offset[axis] ?? 0)) * (node.scale[axis] ?? 1), - ) as [number, number, number], - node.rotation, - ) - } - // The elected attachment translation comes from the shared bounds resolver, not a guessed floor Y. - const first = corrected(origin) - const shift = corner.map((value, axis) => value - (first[axis] ?? 0)) + const resolved = scriptItemLevelFrame(node, nodes) + if (!resolved) return + const corners = boxCorners(resolved.bounds.min, resolved.bounds.max).map((point) => + transformScriptManifestPoint(resolved.node, resolved.assetScale, resolved.pose, point), + ) + if (!corners.every(finiteVec3)) return return (point) => - corrected(point).map((value, axis) => value + shift[axis]!) as [number, number, number] + transformScriptManifestPoint(resolved.node, resolved.assetScale, resolved.pose, point) } function itemVerticalInterval( node: AnyNode | undefined, nodes: Record, + frameCache?: Map, ): ItemVerticalInterval | undefined { // Keep the existing plan-layout evidence limited to yaw-only model poses. if ( @@ -351,23 +623,24 @@ function itemVerticalInterval( !planarRotation(node.asset.rotation) ) return - const resolved = scriptItemBoundsInLevel(node, nodes) - if (resolved) - return { - levelId: resolved.levelId, - min: resolved.bounds.min[1], - max: resolved.bounds.max[1], - } + const resolved = scriptItemLevelFrame(node, nodes, frameCache) + if (!resolved || !isPlanarFrame(resolved.pose)) return + const corners = boxCorners(resolved.bounds.min, resolved.bounds.max).map((point) => + transformScriptManifestPoint(resolved.node, resolved.assetScale, resolved.pose, point), + ) + if (!corners.every(finiteVec3)) return + const bounds = boundsOf(corners) + return { + levelId: resolved.levelId, + min: bounds.min[1], + max: bounds.max[1], + } } -/** - * An item's real shape in its level's frame (see `item-solids`), or null where there is none to read: - * a script with no faces, a catalogue model, a tilted or animated one. A thing hosted by another item - * stands at its host chain's pose, on the floor construction under the item at the chain's root. - */ -export function itemSolidsInLevel( +function resolveItemSolidsInLevel( node: ItemNode, nodes: Record, + frameCache?: Map, ): ItemSolid[] | null { const manifest = node.source?.manifest if ( @@ -377,9 +650,14 @@ export function itemSolidsInLevel( !planarRotation(node.asset.rotation) ) return null - const direct = scriptItemToLevel(node, nodes) - const toLevel = direct ?? hostedToLevel(node, nodes) - if (!toLevel) return null + const resolved = scriptItemLevelFrame(node, nodes, frameCache) + if (!resolved || !isPlanarFrame(resolved.pose)) return null + const corners = boxCorners(resolved.bounds.min, resolved.bounds.max).map((point) => + transformScriptManifestPoint(resolved.node, resolved.assetScale, resolved.pose, point), + ) + if (!corners.every(finiteVec3)) return null + const toLevel = (point: [number, number, number]) => + transformScriptManifestPoint(resolved.node, resolved.assetScale, resolved.pose, point) try { const solids = manifestSolids(manifest, toLevel) return solids?.every((solid) => Number.isFinite(solid.y0) && Number.isFinite(solid.y1)) @@ -391,48 +669,16 @@ export function itemSolidsInLevel( } } -/** The map of a manifest point to the level for an item hosted by other items, or undefined. */ -function hostedToLevel(node: ItemNode, nodes: Record): ToLevel | undefined { - // biome-ignore lint/plugin: an item hosted by other items resolves each parent through the whole scene - const byId = new Map(Object.entries(nodes)) - const pose = itemLevelPose(node, byId) - if ( - !pose || - !node.scale.every((value) => value > 0) || - !(node.asset.scale ?? [1, 1, 1]).every((value) => value > 0) - ) - return - let root: ItemNode = node - for (let depth = 0; depth < 16; depth++) { - const parent = root.parentId ? nodes[root.parentId] : undefined - if (parent?.type !== 'item') break - root = parent - } - const rootParent = root.parentId ? nodes[root.parentId] : undefined - if (rootParent?.type !== 'level') return - const lift = itemFloorLift(root, nodes) - if (!Number.isFinite(lift)) return - const assetScale = node.asset.scale ?? [1, 1, 1] - const turn: [number, number, number] = [node.rotation[0], pose.yawDeg, node.rotation[2]] - return (point) => { - const asset = rotateVector( - point.map((value, axis) => value * assetScale[axis]!) as [number, number, number], - node.asset.rotation, - ) - const placed = rotateVector( - asset.map((value, axis) => (value + node.asset.offset[axis]!) * node.scale[axis]!) as [ - number, - number, - number, - ], - turn, - ) - return [ - placed[0] + pose.position[0], - placed[1] + pose.position[1] + lift, - placed[2] + pose.position[2], - ] - } +/** + * An item's real shape in its level's frame (see `item-solids`), or null where there is none to read: + * a script with no faces, a catalogue model, a tilted or animated one. A thing hosted by another item + * stands at its host chain's pose, on the floor construction under the item at the chain's root. + */ +export function itemSolidsInLevel( + node: ItemNode, + nodes: Record, +): ItemSolid[] | null { + return resolveItemSolidsInLevel(node, nodes) } /** @@ -443,9 +689,11 @@ export function findBlockedDoors( args: Parameters[0], ): BlockedDoorIssue[] { const list = [...args.nodes] - const nodes = Object.fromEntries(list.map((node) => [node.id, node])) + const nodes = recordFromNodes(list) const byId = new Map(list.map((node) => [node.id, node])) - const finite = list.every((node) => node.type === 'item' || finiteNumbers(node)) + const finite = list.every( + (node) => node.type === 'item' || node.type === 'procedural-item' || finiteNumbers(node), + ) return findBlockedDoorsByBox({ ...args, nodes: list, @@ -463,33 +711,394 @@ export const MIN_OVERLAP_AREA = 0.001 * above its host, lifted by the floor construction under the item at the root of its host chain. A * thing hosted by a ceiling or a wall, or one whose heights are unknown, has none. */ +function resolveItemHeightsInLevel( + node: ItemNode, + nodes: Record, + byId: Map, + finiteContext = true, + frameCache?: Map, +): ItemVerticalInterval | undefined { + if (node.source) { + return finiteContext ? itemVerticalInterval(node, nodes, frameCache) : undefined + } + const range = itemLevelHeightRange(node, byId, { nodes, frameCache }) + const levelId = resolveNodeLevelId(node.id, byId) + if (!(range && levelId && finiteContext)) return undefined + const root = resolveValidHostChainRoot(node, nodes) + if (!root) return undefined + const resolvedRoot = resolveHostChainBaseElevation(root, nodes) + if (!resolvedRoot || resolvedRoot.levelId !== levelId) return undefined + return { levelId, min: range.min + resolvedRoot.baseY, max: range.max + resolvedRoot.baseY } +} + export function itemHeightsInLevel( node: ItemNode, nodes: Record, byId: Map, finiteContext = true, ): ItemVerticalInterval | undefined { - const measured = finiteContext ? itemVerticalInterval(node, nodes) : undefined - if (measured) return measured - const range = itemLevelHeightRange(node, byId) - let root: ItemNode = node - for (let depth = 0; depth < 16; depth++) { - const parent = root.parentId ? nodes[root.parentId] : undefined - if (parent?.type !== 'item') break - root = parent - } - const rootParent = root.parentId ? nodes[root.parentId] : undefined + return resolveItemHeightsInLevel(node, nodes, byId, finiteContext) +} + +type SweptProceduralBounds = { + min: [number, number, number] + max: [number, number, number] +} + +function sweptProceduralBounds(evaluated: Evaluation): SweptProceduralBounds | null { + if ( + !finiteVec3(evaluated.min) || + !finiteVec3(evaluated.max) || + !finiteVec3(evaluated.dimensions) || + evaluated.dimensions.some((size) => !(size > 0)) + ) { + return null + } + const min: [number, number, number] = [...evaluated.min] + const max: [number, number, number] = [...evaluated.max] + if (evaluated.reach) { + if (!finiteVec3(evaluated.reach.min) || !finiteVec3(evaluated.reach.max)) return null + for (let k = 0; k < 3; k++) { + min[k] = Math.min(min[k]!, evaluated.reach.min[k]!) + max[k] = Math.max(max[k]!, evaluated.reach.max[k]!) + } + } + const hasMovingShape = evaluated.shapes.some((shape) => Boolean(shape.motionGroup)) + if (hasMovingShape) { + let swept: ReturnType + try { + swept = jointReach(evaluated.motions, evaluated.shapes, shapeBounds) + } catch { + return null + } + if (hasMovingShape) { + const motionById = new Map(evaluated.motions.map((motion) => [motion.id, motion])) + const reachedRoots = new Set(swept.map((entry) => entry.motion.id)) + const coveredGroups = new Set() + for (const motion of evaluated.motions) { + let current: (typeof evaluated.motions)[number] | undefined = motion + const seen = new Set() + while (current?.parent) { + if (seen.has(current.id)) { + current = undefined + break + } + seen.add(current.id) + current = motionById.get(current.parent) + } + if (current && reachedRoots.has(current.id)) { + coveredGroups.add(motion.id) + } + } + if ( + evaluated.shapes.some( + (shape) => Boolean(shape.motionGroup) && !coveredGroups.has(shape.motionGroup!), + ) + ) { + return null + } + } + for (const { bounds } of swept) { + if (!finiteVec3(bounds.min) || !finiteVec3(bounds.max)) return null + for (let k = 0; k < 3; k++) { + min[k] = Math.min(min[k]!, bounds.min[k]!) + max[k] = Math.max(max[k]!, bounds.max[k]!) + } + } + } + if (min.some((lo, axis) => lo > max[axis]!)) return null + return { min, max } +} + +function cachedSweptProceduralBounds( + id: string, + evaluated: Evaluation, + sweptCache?: Map, +): SweptProceduralBounds | null { + if (sweptCache?.has(id)) return sweptCache.get(id) ?? null + const computed = sweptProceduralBounds(evaluated) + sweptCache?.set(id, computed) + return computed +} + +function proceduralOriginYInLevel( + node: ProceduralItemNode, + evaluated: Evaluation, + nodes: Record, + byId: Map, + finiteContext: boolean, + frameCache?: Map, +): { levelId: string; originY: number } | undefined { + if ( + !finiteContext || + node.wallId || + !Array.isArray(node.recipe?.parts) || + !finiteVec3(node.position) || + !planarRotation(node.rotation) + ) { + return undefined + } + const parent = ownNode(nodes, node.parentId) + if (node.recipe.mounting?.attachTo === 'ceiling') { + if (parent?.type !== 'ceiling' || !parent.parentId) return undefined + const level = ownNode(nodes, parent.parentId) + if (level?.type !== 'level' || !finiteNumbers(level) || !finiteNumbers(parent)) return undefined + const reference = evaluated.surfaces.find((s) => s.id === node.recipe.mounting?.reference) + if (!reference) return undefined + try { + const hostY = resolveCeilingHeight(parent, nodes) - CEILING_DRAW_OFFSET + const offset = rotateVector(reference.position, node.rotation) + const originY = hostY + node.position[1] - offset[1] + return Number.isFinite(originY) ? { levelId: level.id, originY } : undefined + } catch { + return undefined + } + } + if (node.recipe.mounting) return undefined + const pose = proceduralItemLevelPose(node, byId, { nodes, frameCache }) + if (!pose) return undefined + const root = resolveValidHostChainRoot(node, nodes) + if (!root) return undefined const levelId = resolveNodeLevelId(node.id, byId) - if (!(range && levelId && finiteContext && rootParent?.type === 'level')) return undefined - const lift = itemFloorLift(root, nodes) - return Number.isFinite(lift) - ? { levelId, min: range.min + lift, max: range.max + lift } + if (!levelId) return undefined + const resolvedRoot = resolveHostChainBaseElevation(root, nodes) + if (!resolvedRoot || resolvedRoot.levelId !== levelId) return undefined + const originY = resolvedRoot.baseY + pose.position[1] + return Number.isFinite(originY) ? { levelId, originY } : undefined +} + +function proceduralHeightsInLevel( + node: ProceduralItemNode, + nodes: Record, + byId: Map, + finiteContext = true, + evalCache?: Map, + frameCache?: Map, + sweptCache?: Map, +): ItemVerticalInterval | undefined { + if ( + !finiteContext || + node.wallId || + !Array.isArray(node.recipe?.parts) || + !finiteVec3(node.position) || + !planarRotation(node.rotation) + ) { + return undefined + } + const evaluated = evalCache + ? cachedEvaluateProcedural(node, evalCache) + : (() => { + try { + return evaluateRecipe(node.recipe, node.parameters) + } catch { + return null + } + })() + if (!evaluated) return undefined + const extent = cachedSweptProceduralBounds(node.id, evaluated, sweptCache) + if (!extent) return undefined + const resolvedOrigin = proceduralOriginYInLevel( + node, + evaluated, + nodes, + byId, + finiteContext, + frameCache, + ) + if (!resolvedOrigin) return undefined + const min = resolvedOrigin.originY + extent.min[1] + const max = resolvedOrigin.originY + extent.max[1] + return Number.isFinite(min) && Number.isFinite(max) + ? { levelId: resolvedOrigin.levelId, min, max } : undefined } /** How far an item may sink into what it stands on and still be resting on it, in metres. */ export const STACK_TOLERANCE = 0.02 +function convexHull2D(points: readonly Vec2[]): [number, number][] { + if (points.length <= 1) return points.map(([x, z]) => [x, z]) + const sorted = [...points].sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1])) + const unique = sorted.filter( + (pt, idx) => idx === 0 || pt[0] !== sorted[idx - 1]![0] || pt[1] !== sorted[idx - 1]![1], + ) + if (unique.length <= 2) return unique.map(([x, z]) => [x, z]) + 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 lower: Vec2[] = [] + for (const pt of unique) { + while ( + lower.length >= 2 && + cross(lower[lower.length - 2]!, lower[lower.length - 1]!, pt) <= 0 + ) { + lower.pop() + } + lower.push(pt) + } + const upper: Vec2[] = [] + for (let i = unique.length - 1; i >= 0; i--) { + const pt = unique[i]! + while ( + upper.length >= 2 && + cross(upper[upper.length - 2]!, upper[upper.length - 1]!, pt) <= 0 + ) { + upper.pop() + } + upper.push(pt) + } + lower.pop() + upper.pop() + return [...lower, ...upper].map(([x, z]) => [x, z]) +} + +function namedAttachmentSupportContext( + host: ProceduralItemNode, + surfaceId: string, + nodes: Record, + byId: Map, + finiteContext: boolean, + evalCache: Map, + frameCache: Map, + sweptCache: Map, +): { surfaceY: number; hostOriginY: number; evaluated: Evaluation } | undefined { + if (!finiteContext) return undefined + const evaluated = cachedEvaluateProcedural(host, evalCache) + if (!evaluated) return undefined + const surface = evaluated.surfaces.find((entry) => entry.id === surfaceId) + if (!surface || !finiteVec3(surface.position)) return undefined + if (Math.abs(surface.rotation[0]) > 1e-6 || Math.abs(surface.rotation[2]) > 1e-6) { + return undefined + } + const extent = cachedSweptProceduralBounds(host.id, evaluated, sweptCache) + if (!extent) return undefined + const resolvedOrigin = proceduralOriginYInLevel( + host, + evaluated, + nodes, + byId, + finiteContext, + frameCache, + ) + if (!resolvedOrigin) return undefined + const hostOriginY = resolvedOrigin.originY + const surfaceY = hostOriginY + surface.position[1] + if (!(Number.isFinite(hostOriginY) && Number.isFinite(surfaceY))) return undefined + return { surfaceY, hostOriginY, evaluated } +} + +type CachedHostShapeEntry = { + localMinY: number + localMaxY: number + localPlanPoints: Vec2[] +} + +function resolveCachedHostShapeEntries( + hostId: string, + evaluated: Evaluation, + cache: Map, +): readonly CachedHostShapeEntry[] | null { + if (cache.has(hostId)) return cache.get(hostId) ?? null + const entries: CachedHostShapeEntry[] = [] + for (const shape of evaluated.shapes) { + let bounds = shapeBounds(shape) + let sweptMotion = false + if (shape.motionGroup) { + let swept: ReturnType + try { + swept = jointReach(evaluated.motions, [shape], shapeBounds) + } catch { + cache.set(hostId, null) + return null + } + if (swept.length === 0) { + cache.set(hostId, null) + return null + } + bounds = boundsOf(swept.flatMap((entry) => [entry.bounds.min, entry.bounds.max])) + sweptMotion = true + } + if (![...bounds.min, ...bounds.max].every(Number.isFinite)) { + cache.set(hostId, null) + return null + } + let localPlanPoints: Vec2[] + if (!sweptMotion && shape.primitive !== 'ellipsoid') { + const half = shape.size.map((v) => v / 2) as [number, number, number] + const shapeFrame = frame(shape.position, shape.rotation) + localPlanPoints = boxCorners([-half[0], -half[1], -half[2]], [half[0], half[1], half[2]]).map( + (pt) => { + const worldPt = transformPoint(shapeFrame, pt) + return [worldPt[0], worldPt[2]] as Vec2 + }, + ) + } else { + localPlanPoints = [ + [bounds.min[0], bounds.min[2]], + [bounds.max[0], bounds.min[2]], + [bounds.max[0], bounds.max[2]], + [bounds.min[0], bounds.max[2]], + ] + } + entries.push({ + localMinY: bounds.min[1], + localMaxY: bounds.max[1], + localPlanPoints, + }) + } + cache.set(hostId, entries) + return entries +} + +/** + * Host shapes extending above a named attachment surface that vertically overlap the attached + * child (for example, the shelf board above a bookcase bay, or side/back panels). + * Returns `null` when the host pose or shape geometry cannot be resolved conservatively. + */ +function hostPartsAboveSurfaceSolids( + host: ProceduralItemNode, + supportY: number, + hostOriginY: number, + childY: ItemVerticalInterval, + evaluated: Evaluation, + byId: Map, + nodes: Record, + frameCache: Map, + hostShapeCache: Map, +): ItemSolid[] | null { + const pose = proceduralItemLevelPose(host, byId, { nodes, frameCache }) + if (!pose) return null + const entries = resolveCachedHostShapeEntries(host.id, evaluated, hostShapeCache) + if (!entries) return null + const cos = Math.cos(pose.yawDeg) + const sin = Math.sin(pose.yawDeg) + const place = (lx: number, lz: number): [number, number] => [ + pose.position[0] + lx * cos + lz * sin, + pose.position[2] - lx * sin + lz * cos, + ] + const above: ItemSolid[] = [] + for (const entry of entries) { + const y0 = hostOriginY + entry.localMinY + const y1 = hostOriginY + entry.localMaxY + // Waive the supporting surface and anything at or below it (1 mm surface tolerance). + if (y1 <= supportY + 1e-3) continue + // Skip shapes strictly above or strictly below the attached child (1 mm touch tolerance). + if (childY.max <= y0 + 1e-3 || childY.min >= y1 - 1e-3) continue + const outer = convexHull2D(entry.localPlanPoints.map(([lx, lz]) => place(lx, lz))) + if (outer.length < 3) continue + above.push({ + polygons: [{ outer, holes: [] }], + y0, + y1, + }) + } + return above +} + +type VolumeBox = { + aabb: PlanAabb + y: ItemVerticalInterval | undefined +} + export function findItemItemCollisions(args: { nodes: Iterable levelId?: string @@ -497,82 +1106,491 @@ export function findItemItemCollisions(args: { }): ItemCollision[] { const gap = args.gap ?? DEFAULT_ITEM_GAP const list = [...args.nodes] - const nodes = Object.fromEntries(list.map((node) => [node.id, node])) - const footprints = collectOccupiedFootprints(list, { levelId: args.levelId }) + const nodes = recordFromNodes(list) + const evalCache = new Map() + const frameCache = new Map() + const sweptCache = new Map() + const hostShapeCache = new Map() + const footprints = collectOccupiedFootprints(list, { + levelId: args.levelId, + evalCache, + frameCache, + nodesRecord: nodes, + }) // Drawing fallbacks on invalid support heights cannot prove collision separation. - const finiteContext = list.every((node) => node.type === 'item' || finiteNumbers(node)) + const finiteContext = list.every( + (node) => node.type === 'item' || node.type === 'procedural-item' || finiteNumbers(node), + ) const byId = new Map(list.map((node) => [node.id, node])) const heights = new Map() - for (const { id } of footprints) - heights.set(id, itemHeightsInLevel(nodes[id] as ItemNode, nodes, byId, finiteContext)) + for (const { id } of footprints) { + const target = ownNode(nodes, id) + heights.set( + id, + target?.type === 'procedural-item' + ? proceduralHeightsInLevel( + target, + nodes, + byId, + finiteContext, + evalCache, + frameCache, + sweptCache, + ) + : target?.type === 'item' + ? resolveItemHeightsInLevel(target, nodes, byId, finiteContext, frameCache) + : undefined, + ) + } // A box is as tall as its heights say; a real shape is read for wall panelling only. const solids = new Map() const solidsOf = (id: string): readonly ItemSolid[] | null => { - if (!solids.has(id)) - solids.set(id, finiteContext ? itemSolidsInLevel(nodes[id] as ItemNode, nodes) : null) + if (!solids.has(id)) { + const target = ownNode(nodes, id) + solids.set( + id, + finiteContext && target?.type === 'item' + ? resolveItemSolidsInLevel(target, nodes, frameCache) + : null, + ) + } return solids.get(id) ?? null } + const boxSolids = new Map() const boxSolid = (id: string): readonly ItemSolid[] | null => { - const node = nodes[id] as ItemNode - const pose = itemLevelPose(node, byId) - if (!pose) return null - const corners = itemNodePlanCorners({ - ...node, - position: pose.position, - rotation: [node.rotation[0], pose.yawDeg, node.rotation[2]], - }) - if (!corners.every((corner) => corner.every(Number.isFinite))) return null - const interval = heights.get(id) - return [ - { - polygons: [{ outer: corners.map(([x, z]) => [x, z] as [number, number]), holes: [] }], - y0: interval?.min ?? Number.NEGATIVE_INFINITY, - y1: interval?.max ?? Number.POSITIVE_INFINITY, - }, - ] + if (boxSolids.has(id)) return boxSolids.get(id) ?? null + const compute = (): readonly ItemSolid[] | null => { + const node = ownNode(nodes, id) + let corners: Vec2[] | null = null + if (node?.type === 'procedural-item') { + const evaluated = cachedEvaluateProcedural(node, evalCache) ?? undefined + corners = proceduralPlanCornersInLevel(node, byId, { nodes, frameCache, evaluated }) + } else if (node?.type === 'item') { + const pose = itemLevelPose(node, byId, { nodes, frameCache }) + if (!pose) return null + corners = itemNodePlanCorners({ + ...node, + position: pose.position, + rotation: [node.rotation[0], pose.yawDeg, node.rotation[2]], + }) + } + if (!corners?.every((corner) => corner.every(Number.isFinite))) return null + const hull = convexHull2D(corners) + if (hull.length < 3) return null + const interval = heights.get(id) + return [ + { + polygons: [{ outer: hull, holes: [] }], + y0: interval?.min ?? Number.NEGATIVE_INFINITY, + y1: interval?.max ?? Number.POSITIVE_INFINITY, + }, + ] + } + const result = compute() + boxSolids.set(id, result) + return result } + const sweptPlanAabbs = new Map() + const sweptPlanAabb = (id: string): PlanAabb | null => { + if (sweptPlanAabbs.has(id)) return sweptPlanAabbs.get(id) ?? null + const compute = (): PlanAabb | null => { + const node = ownNode(nodes, id) + if (node?.type !== 'procedural-item') return null + const evaluated = cachedEvaluateProcedural(node, evalCache) + if (!evaluated) return null + const swept = cachedSweptProceduralBounds(node.id, evaluated, sweptCache) + if (!swept) return null + return proceduralPlanAabbInLevel(node, byId, { + nodes, + frameCache, + evaluated: { ...evaluated, reach: swept }, + }) + } + const result = compute() + sweptPlanAabbs.set(id, result) + return result + } + const proceduralOriginCache = new Map() + const resolvedProceduralOrigin = ( + node: ProceduralItemNode, + evaluated: Evaluation, + ): { levelId: string; originY: number } | null => { + if (proceduralOriginCache.has(node.id)) return proceduralOriginCache.get(node.id) ?? null + const resolved = + proceduralOriginYInLevel(node, evaluated, nodes, byId, finiteContext, frameCache) ?? null + proceduralOriginCache.set(node.id, resolved) + return resolved + } + const proceduralPiecesCache = new Map< + string, + { boxes: readonly VolumeBox[]; solids: readonly ItemSolid[] } | null + >() + const proceduralPieces = ( + id: string, + ): { boxes: readonly VolumeBox[]; solids: readonly ItemSolid[] } | null => { + if (proceduralPiecesCache.has(id)) return proceduralPiecesCache.get(id) ?? null + const compute = (): { boxes: readonly VolumeBox[]; solids: readonly ItemSolid[] } | null => { + const node = ownNode(nodes, id) + if (node?.type !== 'procedural-item') return null + const evaluated = cachedEvaluateProcedural(node, evalCache) + if (!evaluated) return null + const hasMotion = evaluated.shapes.some((shape) => Boolean(shape.motionGroup)) + if (!hasMotion) return null + if (!cachedSweptProceduralBounds(node.id, evaluated, sweptCache)) return null + + const localPieces: SweptProceduralBounds[] = [] + const staticShapes = evaluated.shapes.filter((shape) => !shape.motionGroup) + if (staticShapes.length > 0) { + const sMin: [number, number, number] = [ + Number.POSITIVE_INFINITY, + Number.POSITIVE_INFINITY, + Number.POSITIVE_INFINITY, + ] + const sMax: [number, number, number] = [ + Number.NEGATIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Number.NEGATIVE_INFINITY, + ] + for (const shape of staticShapes) { + const b = shapeBounds(shape) + if (!finiteVec3(b.min) || !finiteVec3(b.max)) return null + for (let k = 0; k < 3; k++) { + sMin[k] = Math.min(sMin[k]!, b.min[k]!) + sMax[k] = Math.max(sMax[k]!, b.max[k]!) + } + } + if (sMin.some((lo, axis) => lo > sMax[axis]!)) return null + localPieces.push({ min: sMin, max: sMax }) + } + for (const shape of evaluated.shapes) { + if (!shape.motionGroup) continue + const restB = shapeBounds(shape) + if (!finiteVec3(restB.min) || !finiteVec3(restB.max)) return null + let swept: ReturnType + try { + swept = jointReach(evaluated.motions, [shape], shapeBounds) + } catch { + return null + } + if (swept.length === 0) return null + const mMin: [number, number, number] = [...restB.min] + const mMax: [number, number, number] = [...restB.max] + for (const entry of swept) { + if (!finiteVec3(entry.bounds.min) || !finiteVec3(entry.bounds.max)) return null + for (let k = 0; k < 3; k++) { + mMin[k] = Math.min(mMin[k]!, entry.bounds.min[k]!) + mMax[k] = Math.max(mMax[k]!, entry.bounds.max[k]!) + } + } + if (mMin.some((lo, axis) => lo > mMax[axis]!)) return null + localPieces.push({ min: mMin, max: mMax }) + } + if (localPieces.length === 0) return null + + const origin = resolvedProceduralOrigin(node, evaluated) + const boxes: VolumeBox[] = [] + const pieceSolids: ItemSolid[] = [] + for (const piece of localPieces) { + const corners = proceduralPlanCornersInLevel(node, byId, { + nodes, + frameCache, + evaluated: { ...evaluated, reach: piece }, + }) + if (!corners?.every((corner) => corner.every(Number.isFinite))) return null + const aabb: PlanAabb = { + minX: Math.min(...corners.map(([x]) => x)), + maxX: Math.max(...corners.map(([x]) => x)), + minZ: Math.min(...corners.map(([, z]) => z)), + maxZ: Math.max(...corners.map(([, z]) => z)), + } + const yMin = origin ? origin.originY + piece.min[1] : Number.NaN + const yMax = origin ? origin.originY + piece.max[1] : Number.NaN + const y: ItemVerticalInterval | undefined = + origin && Number.isFinite(yMin) && Number.isFinite(yMax) + ? { levelId: origin.levelId, min: yMin, max: yMax } + : undefined + boxes.push({ aabb, y }) + const hull = convexHull2D(corners) + if (hull.length < 3) return null + pieceSolids.push({ + polygons: [{ outer: hull, holes: [] }], + y0: y?.min ?? Number.NEGATIVE_INFINITY, + y1: y?.max ?? Number.POSITIVE_INFINITY, + }) + } + return { boxes, solids: pieceSolids } + } + const result = compute() + proceduralPiecesCache.set(id, result) + return result + } + const sweptBoxSolids = new Map() + const sweptBoxSolid = (id: string, requireFiniteHeight = false): readonly ItemSolid[] | null => { + const pieces = proceduralPieces(id) + if (pieces) { + if (requireFiniteHeight && !heights.get(id)) return null + return pieces.solids + } + if (requireFiniteHeight && !heights.get(id)) return null + if (sweptBoxSolids.has(id)) return sweptBoxSolids.get(id) ?? null + const compute = (): readonly ItemSolid[] | null => { + const node = ownNode(nodes, id) + if (node?.type === 'item') return boxSolid(id) + if (node?.type !== 'procedural-item') return null + const interval = heights.get(id) + const evaluated = cachedEvaluateProcedural(node, evalCache) + if (!evaluated) return null + const swept = cachedSweptProceduralBounds(node.id, evaluated, sweptCache) + if (!swept) return null + const corners = proceduralPlanCornersInLevel(node, byId, { + nodes, + frameCache, + evaluated: { ...evaluated, reach: swept }, + }) + if (!corners?.every((corner) => corner.every(Number.isFinite))) return null + const hull = convexHull2D(corners) + if (hull.length < 3) return null + return [ + { + polygons: [{ outer: hull, holes: [] }], + y0: interval?.min ?? Number.NEGATIVE_INFINITY, + y1: interval?.max ?? Number.POSITIVE_INFINITY, + }, + ] + } + const result = compute() + sweptBoxSolids.set(id, result) + return result + } + const hasUnprovenProceduralMotion = (id: string): boolean => { + const node = ownNode(nodes, id) + if (node?.type !== 'procedural-item') return false + const evaluated = cachedEvaluateProcedural(node, evalCache) + if (!evaluated) return false + const hasMotion = evaluated.shapes.some((shape) => Boolean(shape.motionGroup)) + return hasMotion && proceduralPieces(id) === null + } + // Precompute named-attachment procedural ancestors once per footprint (O(n * depth)) rather than + // walking parent chains inside the O(n^2) pair loop. + const attachedAncestors = new Map>() + for (const { id } of footprints) { + const seen = new Set() + let hostSurfaces: Map | undefined + let current = ownNode(nodes, id) + while (current?.parentId) { + if (seen.has(current.id)) { + hostSurfaces = undefined + break + } + seen.add(current.id) + const parent = ownNode(nodes, current.parentId) + if (!parent || (parent.type !== 'item' && parent.type !== 'procedural-item')) { + break + } + if (seen.has(parent.id)) { + hostSurfaces = undefined + break + } + if ( + parent.type === 'procedural-item' && + parent.attachments && + Object.hasOwn(parent.attachments, current.id) + ) { + const surfaceId = parent.attachments[current.id] + if (typeof surfaceId === 'string') { + hostSurfaces ??= new Map() + hostSurfaces.set(parent.id, surfaceId) + } + } + current = parent + } + if (hostSurfaces && hostSurfaces.size > 0) { + attachedAncestors.set(id, hostSurfaces) + } + } + const isWallDressingNode = (id: string): boolean => { + const target = ownNode(nodes, id) + return target?.type === 'item' && isWallDressing(target) + } + const hasAttachedAncestors = attachedAncestors.size > 0 const collisions: ItemCollision[] = [] for (let i = 0; i < footprints.length; i++) { + const a = footprints[i]! + const ancestorsOfA = hasAttachedAncestors ? attachedAncestors.get(a.id) : undefined + const aBroadAabb = sweptPlanAabb(a.id) ?? a.aabb + const aUnprovenMotion = hasUnprovenProceduralMotion(a.id) for (let j = i + 1; j < footprints.length; j++) { - const a = footprints[i]! const b = footprints[j]! if (a.levelId && b.levelId && a.levelId !== b.levelId) continue - if (!aabbsOverlap(a.aabb, b.aabb, gap)) continue + const ancestorsOfB = hasAttachedAncestors ? attachedAncestors.get(b.id) : undefined + let attachedChildToHost: { + host: ProceduralItemNode + surfaceId: string + childId: string + childY: ItemVerticalInterval | undefined + } | null = null + if (ancestorsOfA !== undefined || ancestorsOfB !== undefined) { + const nodeA = ownNode(nodes, a.id) + const nodeB = ownNode(nodes, b.id) + const surfaceOnA = nodeA?.type === 'procedural-item' ? ancestorsOfB?.get(a.id) : undefined + const surfaceOnB = + surfaceOnA === undefined && nodeB?.type === 'procedural-item' + ? ancestorsOfA?.get(b.id) + : undefined + if (surfaceOnA !== undefined) { + attachedChildToHost = { + host: nodeA as ProceduralItemNode, + surfaceId: surfaceOnA, + childId: b.id, + childY: heights.get(b.id), + } + } else if (surfaceOnB !== undefined) { + attachedChildToHost = { + host: nodeB as ProceduralItemNode, + surfaceId: surfaceOnB, + childId: a.id, + childY: heights.get(a.id), + } + } + } + const bBroadAabb = sweptPlanAabb(b.id) ?? b.aabb + const bUnprovenMotion = hasUnprovenProceduralMotion(b.id) + const unprovenMotion = aUnprovenMotion || bUnprovenMotion + if (!attachedChildToHost && !aabbsOverlap(aBroadAabb, bBroadAabb, gap)) continue const aY = heights.get(a.id) const bY = heights.get(b.id) - let violation: ItemCollision['violation'] - let reading: ItemPairReading - if (isWallDressing(nodes[a.id] as ItemNode) || isWallDressing(nodes[b.id] as ItemNode)) { - // Wall panelling is thin strips along the walls, and its box is the room's: it is read by its - // strips, a piece beside it by its footprint. Nothing else is: a script's horizontal faces leave - // out its rails, backs and foliage, so the box stays the shape of the rest. - const left = solidsOf(a.id) ?? boxSolid(a.id) - const right = solidsOf(b.id) ?? boxSolid(b.id) - if (!(left && right)) continue - const relation = relateSolids(left, right, { - stack: STACK_TOLERANCE, - minArea: MIN_OVERLAP_AREA, - }) - if (relation.overlapArea > 0) { - violation = 'overlap' - reading = { overlapAreaM2: roundMm(relation.overlapArea) } - } else if (relation.gap < gap) { - violation = 'clearance' - reading = { gapM: roundMm(relation.gap) } - } else continue - } else { - // Two boxes. One standing on the other (a lamp on a table, a vase on a console) is stacked, - // whether it is the other's child or a sibling in the scene: its bottom is at or above the - // other's top, to within what a model sinks into it. Unknown heights waive nothing. - if ( - aY && - bY && - aY.levelId === bY.levelId && - (aY.min >= bY.max - STACK_TOLERANCE - 1e-9 || bY.min >= aY.max - STACK_TOLERANCE - 1e-9) + let outcome: { violation: ItemCollision['violation']; reading: ItemPairReading } | undefined + let reportAabbA = aBroadAabb + let reportAabbB = bBroadAabb + let unprovenAttachment = false + if (attachedChildToHost) { + const support = namedAttachmentSupportContext( + attachedChildToHost.host, + attachedChildToHost.surfaceId, + nodes, + byId, + finiteContext, + evalCache, + frameCache, + sweptCache, ) - continue - violation = aabbsOverlap(a.aabb, b.aabb, 0) ? 'overlap' : 'clearance' - reading = boxReading(a.aabb, b.aabb, gap) + if (support === undefined || attachedChildToHost.childY === undefined) { + unprovenAttachment = true + } else if (attachedChildToHost.childY.min >= support.surfaceY - STACK_TOLERANCE - 1e-9) { + const aboveSolids = hostPartsAboveSurfaceSolids( + attachedChildToHost.host, + support.surfaceY, + support.hostOriginY, + attachedChildToHost.childY, + support.evaluated, + byId, + nodes, + frameCache, + hostShapeCache, + ) + if (aboveSolids === null) { + unprovenAttachment = true + } else { + if (aboveSolids.length === 0 && !unprovenMotion) continue + const childSolid = isWallDressingNode(attachedChildToHost.childId) + ? (solidsOf(attachedChildToHost.childId) ?? + sweptBoxSolid(attachedChildToHost.childId, true)) + : sweptBoxSolid(attachedChildToHost.childId, true) + if (!childSolid || unprovenMotion) { + unprovenAttachment = true + } else { + const relation = relateSolids(aboveSolids, childSolid, { + stack: 0, + minArea: MIN_OVERLAP_AREA, + }) + if (relation.overlapArea <= 0) continue + outcome = { + violation: 'overlap', + reading: { overlapAreaM2: roundMm(relation.overlapArea) }, + } + } + } + } + } + const unprovenAttachedMotion = Boolean(attachedChildToHost) && unprovenMotion + if (!outcome) { + if (!unprovenAttachedMotion && !aabbsOverlap(aBroadAabb, bBroadAabb, gap)) continue + if (unprovenAttachedMotion) { + outcome = { + violation: 'overlap', + reading: aabbsOverlap(aBroadAabb, bBroadAabb, 0) + ? boxReading(aBroadAabb, bBroadAabb, gap) + : { overlapAreaM2: roundMm(MIN_OVERLAP_AREA) }, + } + } else if (isWallDressingNode(a.id) || isWallDressingNode(b.id)) { + // Wall panelling is thin strips along the walls, and its box is the room's: it is read by its + // strips, a piece beside it by its footprint. Nothing else is: a script's horizontal faces leave + // out its rails, backs and foliage, so the box stays the shape of the rest. + const left = + solidsOf(a.id) ?? + (unprovenMotion ? boxSolid(a.id) : (sweptBoxSolid(a.id) ?? boxSolid(a.id))) + const right = + solidsOf(b.id) ?? + (unprovenMotion ? boxSolid(b.id) : (sweptBoxSolid(b.id) ?? boxSolid(b.id))) + if (!(left && right)) continue + const relation = relateSolids(left, right, { + stack: STACK_TOLERANCE, + minArea: MIN_OVERLAP_AREA, + }) + if (relation.overlapArea > 0) { + outcome = { + violation: 'overlap', + reading: { overlapAreaM2: roundMm(relation.overlapArea) }, + } + } else if (relation.gap < gap) { + outcome = { + violation: 'clearance', + reading: { gapM: roundMm(relation.gap) }, + } + } else continue + } else { + // Two boxes (or piecewise rest + moving-part boxes for animated procedural designs). + // One standing on the other (a lamp on a table, a vase on a console) is stacked, + // whether it is the other's child or a sibling in the scene: its bottom is at or above the + // other's top, to within what a model sinks into it. Unknown heights waive nothing. + const aPieces = !unprovenMotion ? proceduralPieces(a.id) : null + const bPieces = !unprovenMotion ? proceduralPieces(b.id) : null + const aBoxes: readonly VolumeBox[] = aPieces + ? aPieces.boxes + : [{ aabb: aBroadAabb, y: unprovenMotion ? undefined : aY }] + const bBoxes: readonly VolumeBox[] = bPieces + ? bPieces.boxes + : [{ aabb: bBroadAabb, y: unprovenMotion ? undefined : bY }] + let bestDepth = Number.NEGATIVE_INFINITY + let bestPair: [VolumeBox, VolumeBox] | null = null + for (const va of aBoxes) { + for (const vb of bBoxes) { + if (!aabbsOverlap(va.aabb, vb.aabb, gap)) continue + if ( + !unprovenAttachment && + !unprovenMotion && + va.y && + vb.y && + va.y.levelId === vb.y.levelId && + (va.y.min >= vb.y.max - STACK_TOLERANCE - 1e-9 || + vb.y.min >= va.y.max - STACK_TOLERANCE - 1e-9) + ) { + continue + } + const shared = axisOverlap(va.aabb, vb.aabb) + const depth = Math.min(shared.x, shared.z) + if (depth > bestDepth) { + bestDepth = depth + bestPair = [va, vb] + } + } + } + if (!bestPair) continue + reportAabbA = bestPair[0].aabb + reportAabbB = bestPair[1].aabb + const violation = aabbsOverlap(reportAabbA, reportAabbB, 0) ? 'overlap' : 'clearance' + outcome = { violation, reading: boxReading(reportAabbA, reportAabbB, gap) } + } } collisions.push({ aId: a.id, @@ -581,11 +1599,11 @@ export function findItemItemCollisions(args: { bName: b.name, levelId: a.levelId ?? b.levelId, kind: 'item-aabb', - violation, + violation: outcome.violation, minimumClearanceMeters: gap, - footprints: [roundBox(a.aabb), roundBox(b.aabb)], - reading, - message: collisionMessage(violation, gap, [a, b], reading), + footprints: [roundBox(reportAabbA), roundBox(reportAabbB)], + reading: outcome.reading, + message: collisionMessage(outcome.violation, gap, [a, b], outcome.reading), }) } } @@ -938,8 +1956,8 @@ export function layoutIssuesFromScene(nodes: Iterable): LayoutIssue[] { const [a, b] = [itemById.get(c.aId), itemById.get(c.bId)] if ( c.violation === 'clearance' && - a?.type === 'item' && - b?.type === 'item' && + (a?.type === 'item' || a?.type === 'procedural-item') && + (b?.type === 'item' || b?.type === 'procedural-item') && designedTogether(a, b) ) continue diff --git a/packages/core/src/procedural-items/recipe.ts b/packages/core/src/procedural-items/recipe.ts index e0fc360e98..e5b4e125a4 100644 --- a/packages/core/src/procedural-items/recipe.ts +++ b/packages/core/src/procedural-items/recipe.ts @@ -406,7 +406,7 @@ export type Evaluation = { dimensions: Vec3 parameters: Record triangles: number - /** Recessed ceiling designs with motion: the rest bounds grown by every motion sample. */ + /** Ceiling and floor designs with motion: the rest bounds grown by every motion sample. */ reach?: { min: Vec3; max: Vec3 } } @@ -1280,7 +1280,11 @@ export function evaluateRecipe(recipe: Recipe, values: Record = throw new Error('Wall-side mounting reference must face local -Z') } const reference = recipe.mounting && surfaces.find((s) => s.id === recipe.mounting!.reference) - const reach = insideCut ? { min: [...min] as Vec3, max: [...max] as Vec3 } : undefined + const reach = + recipe.mounting?.attachTo === 'ceiling' || + (!recipe.mounting && shapes.some((shape) => Boolean(shape.motionGroup))) + ? { min: [...min] as Vec3, max: [...max] as Vec3 } + : undefined for (const { motion, bounds } of jointReach( motions.filter((m) => jointGroups.has(m.id)), shapes, @@ -1367,6 +1371,10 @@ export function evaluateRecipe(recipe: Recipe, values: Record = for (const motion of motions) if (motion.kind !== 'slide') motion.pivot = lower(motion.pivot) min[1] -= base max[1] -= base + if (reach) { + reach.min[1] -= base + reach.max[1] -= base + } } const dimensions = max.map((x, i) => x - min[i]!) as Vec3 if (dimensions.some((x) => x > 30) || [...min, ...max].some((x) => Math.abs(x) > 30)) diff --git a/packages/mcp/src/tools/check-collisions.test.ts b/packages/mcp/src/tools/check-collisions.test.ts index 908bcc5aa9..c94633fb4e 100644 --- a/packages/mcp/src/tools/check-collisions.test.ts +++ b/packages/mcp/src/tools/check-collisions.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, test } from 'bun:test' import { Client } from '@modelcontextprotocol/client' import { InMemoryTransport, McpServer } from '@modelcontextprotocol/server' -import { ItemNode } from '@pascal-app/core/schema' +import { CeilingNode, ItemNode, ProceduralItemNode } from '@pascal-app/core/schema' import { SceneBridge } from '../bridge/scene-bridge' import { registerCheckCollisions } from './check-collisions' @@ -316,4 +316,381 @@ describe('check_collisions', () => { reason: 'unresolved_level', }) }) + + describe('procedural-item support (#1255)', () => { + const blockRecipe = { + version: 1, + name: 'M0 D2.5 Overlap Block', + description: 'A solid 2 m by 2 m by 0.9 m floor-standing test block.', + classification: { + category: 'test_furniture', + functionTags: ['test'], + tags: ['collision'], + }, + parameters: [ + { + id: 'width', + label: 'Width', + default: 2, + min: 2, + max: 2, + step: 0.1, + unit: 'm', + axis: 'x', + }, + { + id: 'depth', + label: 'Depth', + default: 2, + min: 2, + max: 2, + step: 0.1, + unit: 'm', + axis: 'z', + }, + { + id: 'height', + label: 'Height', + default: 0.9, + min: 0.9, + max: 0.9, + step: 0.1, + unit: 'm', + axis: 'y', + }, + ], + slots: [{ id: 'wood', label: 'Wood', color: '#8b5a2b', finish: 'wood' }], + parts: [ + { + id: 'block', + label: 'Block', + count: 1, + shapes: [ + { + id: 'body', + primitive: 'box', + slot: 'wood', + size: ['width', 'height', 'depth'], + position: [0, { op: 'div', args: ['height', 2] }, 0], + support: true, + }, + ], + }, + ], + constraints: [], + } + + function makeProcedural( + id: string, + position: [number, number, number], + extra: Record = {}, + ) { + return ProceduralItemNode.parse({ + object: 'node', + id, + type: 'procedural-item', + name: id, + visible: true, + metadata: {}, + recipe: blockRecipe, + parameters: { width: 2, depth: 2, height: 0.9 }, + slots: {}, + position, + rotation: [0, 0, 0], + children: [], + attachments: {}, + ...extra, + }) + } + + test('detects overlapping floor-standing procedural-item nodes and populates checkedItems', async () => { + const level = Object.values(bridge.getNodes()).find((n) => n.type === 'level')! + const a = makeProcedural('procedural-item_m0d25_proc_a', [0, 0, 0], { + name: 'M0 D2.5 Procedural A', + }) + const b = makeProcedural('procedural-item_m0d25_proc_b', [0, 0, 0], { + name: 'M0 D2.5 Procedural B', + }) + bridge.createNode(a, level.id) + bridge.createNode(b, level.id) + + const result = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id, minimumClearance: 0, floorOnly: true }, + }) + const parsed = result.structuredContent as { + status: string + checkedItems: Array<{ + id: string + source: { assetId: string; uri: string; catalog: string } + effectiveDimensionsMeters: [number, number, number] + }> + skippedItems: unknown[] + collisions: Array<{ aId: string; bId: string; kind: string; violation: string }> + } + expect(result.isError).toBeFalsy() + expect(parsed.status).toBe('checked') + expect(parsed.checkedItems).toHaveLength(2) + expect(parsed.checkedItems[0]?.source).toEqual({ + assetId: 'M0 D2.5 Overlap Block', + uri: 'procedural://recipe', + catalog: 'procedural', + }) + expect(parsed.checkedItems[0]?.effectiveDimensionsMeters).toEqual([2, 0.9, 2]) + expect(parsed.skippedItems).toEqual([]) + expect(parsed.collisions).toEqual([ + expect.objectContaining({ + aId: 'procedural-item_m0d25_proc_a', + bId: 'procedural-item_m0d25_proc_b', + kind: 'item-aabb', + violation: 'overlap', + }), + ]) + }) + + test('detects item vs procedural-item overlap and clearance violations', async () => { + const level = Object.values(bridge.getNodes()).find((n) => n.type === 'level')! + const proc = makeProcedural('procedural-item_sofa', [0, 0, 0]) + const nearItem = makeItem([1.55, 0, 0], [1, 0.8, 1]) // 0.05 m gap (< 0.1 m clearance) + bridge.createNode(proc, level.id) + bridge.createNode(nearItem, level.id) + + const result = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id, minimumClearance: 0.1, floorOnly: true }, + }) + const parsed = result.structuredContent as { + status: string + checkedItems: unknown[] + collisions: Array<{ aId: string; bId: string; violation: string }> + } + expect(parsed.status).toBe('checked') + expect(parsed.checkedItems).toHaveLength(2) + expect(parsed.collisions).toHaveLength(1) + expect(parsed.collisions[0]?.violation).toBe('clearance') + }) + + test('skips ceiling-hosted and non-planar procedural-item nodes without leaking phantom collisions', async () => { + const level = Object.values(bridge.getNodes()).find((n) => n.type === 'level')! + const ceiling = CeilingNode.parse({ + id: 'ceiling_proc', + polygon: [ + [-3, -3], + [3, -3], + [3, 3], + [-3, 3], + ], + }) + bridge.createNode(ceiling, level.id) + const pendantRecipe = { + ...blockRecipe, + name: 'Procedural Pendant', + mounting: { attachTo: 'ceiling', reference: 'mount' }, + surfaces: [ + { + id: 'mount', + label: 'Mount', + position: [0, 0.9, 0], + size: [0.2, 0.2], + }, + ], + } + const pendant = makeProcedural('procedural-item_pendant', [0, 0, 0], { + recipe: pendantRecipe, + }) + const tilted = makeProcedural('procedural-item_tilted', [0, 0, 0], { + rotation: [0.2, 0, 0], + }) + bridge.createNode(pendant, ceiling.id) + bridge.createNode(tilted, level.id) + + const floorResult = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id, floorOnly: true }, + }) + const floorParsed = floorResult.structuredContent as { + status: string + checkedItems: unknown[] + skippedItems: Array<{ id: string; reason: string }> + collisions: unknown[] + } + expect(floorParsed.status).toBe('insufficient_evidence') + expect(floorParsed.checkedItems).toHaveLength(0) + expect(floorParsed.collisions).toHaveLength(0) + expect(floorParsed.skippedItems).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: 'procedural-item_pendant', + reason: 'unsupported_attachment', + }), + expect.objectContaining({ id: 'procedural-item_tilted', reason: 'non_planar_rotation' }), + ]), + ) + + const wallSideRecipe = { + ...blockRecipe, + name: 'Wall-Side Sconce Draft', + mounting: { attachTo: 'wall-side', reference: 'back' }, + surfaces: [ + { + id: 'back', + label: 'Back', + position: [0, 0.45, -1], + rotation: [-Math.PI / 2, 0, 0], + size: [0.2, 0.2], + }, + ], + } + const wallDraftOnLevel = makeProcedural('procedural-item_wall_draft', [0, 0, 0], { + recipe: wallSideRecipe, + metadata: { isTransient: true }, + }) + const wallHosted = makeProcedural('procedural-item_wall_hosted', [0, 0, 0], { + wallId: 'wall_host', + }) + bridge.createNode(wallDraftOnLevel, level.id) + bridge.createNode(wallHosted, level.id) + + const floorWithWallHostedResult = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id, floorOnly: true }, + }) + const floorWithWallHosted = floorWithWallHostedResult.structuredContent as { + skippedItems: Array<{ id: string; reason: string }> + } + expect(floorWithWallHosted.skippedItems).toContainEqual( + expect.objectContaining({ + id: 'procedural-item_wall_hosted', + reason: 'unsupported_attachment', + }), + ) + + const defaultResult = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id }, + }) + const defaultParsed = defaultResult.structuredContent as { + status: string + checkedItems: unknown[] + skippedItems: Array<{ id: string; reason: string }> + } + expect(defaultParsed.status).toBe('insufficient_evidence') + expect(defaultParsed.checkedItems).toHaveLength(0) + expect(defaultParsed.skippedItems).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: 'procedural-item_wall_draft', + reason: 'unsupported_attachment', + }), + expect.objectContaining({ + id: 'procedural-item_wall_hosted', + reason: 'unsupported_attachment', + }), + ]), + ) + }) + + test('skips level-parented roof-mounted items in floorOnly mode to match core footprint collection', async () => { + const level = Object.values(bridge.getNodes()).find((n) => n.type === 'level')! + const sofa = makeItem([0, 0, 0], [1, 1, 1]) + const roofUnit = ItemNode.parse({ + ...makeItem([0, 0, 0], [1, 1, 1]), + id: 'item_roof_unit', + name: 'Roof Unit', + roofSegmentId: 'roof-segment_1', + }) + bridge.createNode(sofa, level.id) + bridge.createNode(roofUnit, level.id) + + const result = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id, floorOnly: true }, + }) + const parsed = result.structuredContent as { + status: string + checkedItems: Array<{ id: string }> + skippedItems: Array<{ id: string; reason: string }> + collisions: unknown[] + } + expect(parsed.checkedItems.map((entry) => entry.id)).toEqual([sofa.id]) + expect(parsed.skippedItems).toContainEqual( + expect.objectContaining({ + id: roofUnit.id, + reason: 'unsupported_attachment', + }), + ) + expect(parsed.collisions).toEqual([]) + }) + + test('includes floor procedural-item motion reach in footprintBoundsMeters and collision checks', async () => { + const level = Object.values(bridge.getNodes()).find((n) => n.type === 'level')! + const slidingCabinet = makeProcedural('procedural-item_sliding_cab', [0, 0, 0], { + recipe: { + ...blockRecipe, + name: 'Sliding Drawer Cabinet', + description: 'Floor cabinet with forward-sliding drawer', + parts: [ + { + id: 'body', + label: 'Body', + count: 1, + shapes: [ + { + id: 'carcass', + primitive: 'box', + slot: 'wood', + size: [0.8, 0.8, 0.5], + position: [0, 0.4, 0], + }, + ], + }, + { + id: 'drawer', + label: 'Drawer', + count: 1, + motion: { + kind: 'slide', + axis: 'z', + distance: 0.4, + duration: 1, + }, + shapes: [ + { + id: 'drawer_box', + primitive: 'box', + slot: 'wood', + size: [0.7, 0.2, 0.45], + position: [0, 0.6, 0.025], + }, + ], + }, + ], + }, + }) + const neighborInDrawerPath = makeItem([0, 0, 0.55], [0.5, 0.8, 0.5]) + bridge.createNode(slidingCabinet, level.id) + bridge.createNode(neighborInDrawerPath, level.id) + + const result = await client.callTool({ + name: 'check_collisions', + arguments: { levelId: level.id }, + }) + const parsed = result.structuredContent as { + checkedItems: Array<{ + id: string + footprintBoundsMeters: { minX: number; maxX: number; minZ: number; maxZ: number } + }> + collisions: Array<{ aId: string; bId: string; violation: string }> + } + const cabEntry = parsed.checkedItems.find((entry) => entry.id === slidingCabinet.id) + expect(cabEntry?.footprintBoundsMeters.maxZ).toBeCloseTo(0.65, 5) + expect(parsed.collisions).toContainEqual( + expect.objectContaining({ + aId: slidingCabinet.id, + bId: neighborInDrawerPath.id, + violation: 'overlap', + }), + ) + }) + }) }) diff --git a/packages/mcp/src/tools/check-collisions.ts b/packages/mcp/src/tools/check-collisions.ts index 54e2eada19..4ca1178dc2 100644 --- a/packages/mcp/src/tools/check-collisions.ts +++ b/packages/mcp/src/tools/check-collisions.ts @@ -2,6 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/server' import { findItemItemCollisions, inspectItemPlanFootprint, + inspectProceduralItemPlanFootprint, resolveNodeLevelId, } from '@pascal-app/core/agent-operations' import { ItemNode } from '@pascal-app/core/schema' @@ -213,8 +214,12 @@ export function registerCheckCollisions(server: McpServer, bridge: SceneOperatio const byId = new Map( nodes.map((node) => [node.id, node] as const), ) + const isCollisionTarget = ( + node: (typeof nodes)[number], + ): node is Extract<(typeof nodes)[number], { type: 'item' | 'procedural-item' }> => + node.type === 'item' || node.type === 'procedural-item' const scoped = nodes.filter((node) => { - if (node.type !== 'item' || !scopeLevelId) return true + if (!isCollisionTarget(node) || !scopeLevelId) return true return resolveNodeLevelId(node.id, byId) === scopeLevelId }) const checkedItems: Array<{ @@ -231,29 +236,43 @@ export function registerCheckCollisions(server: McpServer, bridge: SceneOperatio const skippedItems: Array<{ id: string; name: string; reason: string }> = [] for (const node of scoped) { - if (node.type !== 'item') continue + if (!isCollisionTarget(node)) continue + const name = + node.type === 'procedural-item' + ? (node.name ?? node.recipe?.name ?? node.id) + : (node.name ?? node.asset.name ?? node.id) const resolvedLevelId = node === candidateNode ? candidate!.levelId : bridge.resolveLevelId(node.id) if (!resolvedLevelId) { skippedItems.push({ id: node.id, - name: node.name ?? node.asset.name ?? node.id, + name, reason: 'unresolved_level', }) continue } + if (node.type === 'procedural-item' && node.wallId) { + skippedItems.push({ + id: node.id, + name, + reason: 'unsupported_attachment', + }) + continue + } const immediateParent = node === candidateNode ? byId.get(candidate!.levelId) : bridge.getAncestry(node.id)[1] if (immediateParent && immediateParent.type !== 'level') { skippedItems.push({ id: node.id, - name: node.name ?? node.asset.name ?? node.id, + name, reason: floorOnly ? 'unsupported_attachment' : 'parent_local_coordinates', }) continue } - const inspected = inspectItemPlanFootprint(node, { floorOnly }) - const name = node.name ?? node.asset.name ?? node.id + const inspected = + node.type === 'procedural-item' + ? inspectProceduralItemPlanFootprint(node, { floorOnly }) + : inspectItemPlanFootprint(node, { floorOnly }) if (!inspected.ok) { skippedItems.push({ id: node.id, name, reason: inspected.reason }) continue @@ -264,17 +283,24 @@ export function registerCheckCollisions(server: McpServer, bridge: SceneOperatio levelId: resolvedLevelId, positionMeters: node.position, rotationYRadians: inspected.rotationY, - source: { - assetId: - node === candidateNode - ? (candidate!.source?.assetId ?? 'supplied-dimensions') - : node.asset.id, - uri: - node === candidateNode - ? (candidate!.source?.uri ?? 'supplied://dimensions') - : node.asset.src, - catalog: node === candidateNode ? 'supplied' : (node.asset.source ?? 'unknown'), - }, + source: + node.type === 'procedural-item' + ? { + assetId: node.recipe?.name || node.id, + uri: 'procedural://recipe', + catalog: 'procedural', + } + : { + assetId: + node === candidateNode + ? (candidate!.source?.assetId ?? 'supplied-dimensions') + : node.asset.id, + uri: + node === candidateNode + ? (candidate!.source?.uri ?? 'supplied://dimensions') + : node.asset.src, + catalog: node === candidateNode ? 'supplied' : (node.asset.source ?? 'unknown'), + }, sourceDimensionsMeters: inspected.sourceDimensions, effectiveDimensionsMeters: inspected.effectiveDimensions, footprintBoundsMeters: inspected.aabb, @@ -285,7 +311,9 @@ export function registerCheckCollisions(server: McpServer, bridge: SceneOperatio checkedItems.map((item) => (item.id === candidate?.id ? candidateNode!.id : item.id)), ) const found = findItemItemCollisions({ - nodes: scoped.filter((node) => (node.type === 'item' ? checkedItemIds.has(node.id) : true)), + nodes: scoped.filter((node) => + isCollisionTarget(node) ? checkedItemIds.has(node.id) : true, + ), gap: minimumClearance, }) const collisions = found.map((c) => ({