From 2961fea8225a28f63afa38c56fdc793888d23d9f Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 16:16:45 +0100 Subject: [PATCH 01/40] verify_scene names walls that nearly join: an end short of a wall, a wall a few degrees off its line wall_end_short: an end that stops 3-25 cm short of another wall, with the daylight in cm and both walls named; an end that touches a wall is a joint. wall_nearly_aligned: a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line; a larger turn is an angle drawn on purpose and is not named. Both are warnings. verify_scene's issues now carry a severity of info or warning (the MCP output schema allowed only info). Rule tests for each finding and for walls that are joined square, in a T or in a bay, and the three shared case rows the core, MCP and chat runners read. Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/scene-check-cases.ts | 44 ++ .../core/src/agent-operations/verify-scene.ts | 18 + .../src/agent-operations/wall-joins.test.ts | 188 +++++++++ .../core/src/agent-operations/wall-joins.ts | 390 ++++++++++++++++++ packages/core/src/agent-tools/verify-scene.ts | 2 +- packages/mcp/src/tools/shared-tools.ts | 2 +- 6 files changed, 642 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/agent-operations/wall-joins.test.ts create mode 100644 packages/core/src/agent-operations/wall-joins.ts diff --git a/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts b/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts index 3b40f14f6e..7db4926c9a 100644 --- a/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts @@ -53,6 +53,9 @@ const rect = (x0: number, z0: number, x1: number, z1: number): Pt[] => [ [x0, z1], ] +const wallAt = (tag: string, start: Pt, end: Pt) => + WallNode.parse({ id: `wall_${tag}`, name: `Wall ${tag}`, parentId: 'level_0', start, end, height: 2.5 }) + const roomZone = (id: string, levelId: string, name: string, polygon: Pt[], extra = {}) => ZoneNode.parse({ id, parentId: levelId, name, polygon, spaceRole: 'room', ...extra }) @@ -697,4 +700,45 @@ export const CHECK_ROOMS_CASES: AgentToolCase[] = [ }, { lacks: [{ type: 'room_not_enclosed' }] }, ), + // Where straight walls meet: an end that stops 3-25 cm short of another wall (daylight between them), and a wall a few + // degrees off the line of its neighbours (a short wall holding a door, drawn skewed). Angled walls drawn on purpose are quiet. + // wall_open_end (info, with the nearest wall to repair toward) says the same end when the room graph elects no joint: both stand. + verify( + 'verify_scene on a wall that stops 10 cm short of another wall: wall_end_short names both walls with the gap', + () => ground(wallAt('across', [0, 0], [4, 0]), wallAt('stub', [2, 2], [2, 0.15])), + { + contains: [{ type: 'wall_end_short', severity: 'warning', levelId: 'level_0', wallId: 'wall_stub', otherWallId: 'wall_across', end: 'end' }], + check: (result) => { + const [first] = issuesOf(result, 'wall_end_short') + return (first?.gap as number) > 0.099 && (first?.gap as number) < 0.101 ? [] : [`gap ${first?.gap} m, not 10 cm of daylight`] + }, + }, + ), + verify( + 'verify_scene on a short wall between two walls on one line, turned 4 degrees: wall_nearly_aligned names it with the angle and both neighbours', + () => { + const end: Pt = [4 + Math.cos((4 * Math.PI) / 180), Math.sin((4 * Math.PI) / 180)] + return ground(wallAt('left', [0, 0], [4, 0]), wallAt('gap', [4, 0], end), wallAt('right', end, [end[0] + 4, end[1]])) + }, + { + contains: [{ type: 'wall_nearly_aligned', severity: 'warning', levelId: 'level_0', wallId: 'wall_gap', angle: 4 }], + check: (result) => { + const [first] = issuesOf(result, 'wall_nearly_aligned') + const ids = ((first?.neighbours ?? []) as { wallId: string }[]).map((n) => n.wallId).sort().join() + return ids === 'wall_left,wall_right' ? [] : [`neighbours ${ids}, not the two walls it sits between`] + }, + }, + ), + verify( + 'verify_scene on walls joined square, a T and a bay turned 30 degrees: neither wall_end_short nor wall_nearly_aligned', + () => + ground( + wallAt('a', [0, 0], [4, 0]), + wallAt('b', [4, 0], [4, 3]), + wallAt('stem', [2, 0], [2, 3]), + wallAt('bay1', [4, 3], [6, 3 + 2 * Math.tan((30 * Math.PI) / 180)]), + wallAt('bay2', [6, 3 + 2 * Math.tan((30 * Math.PI) / 180)], [8, 3]), + ), + { lacks: [{ type: 'wall_end_short' }, { type: 'wall_nearly_aligned' }] }, + ), ] diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 33bb834006..0204455522 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -52,6 +52,13 @@ import { } from './scene-queries' import { reviewSince } from './scene-review' import type { AgentContext, AgentOperation, SceneNodes } from './types' +import { + type WallEndShortIssue, + type WallNearlyAlignedIssue, + wallBodies, + wallEndShortIssues, + wallNearlyAlignedIssues, +} from './wall-joins' import { type WallObjectObservation, wallObjectObservations } from './wall-object-observations' /** A problem verify_scene found, typed so it can be counted and acted on. */ @@ -94,6 +101,8 @@ export type SceneIssue = gap?: number nearestWallId?: string } + | WallEndShortIssue + | WallNearlyAlignedIssue /** What verify_scene was asked: its contract's input, which other modules may extend. */ export type VerifySceneInput = Readonly> @@ -390,6 +399,15 @@ export const verifyScene: AgentOperation = ( for (const level of levels) { const { content, levelName } = level if (level.unread) continue + const bodies = wallBodies( + onLevel(level.levelId).filter( + (node): node is AnyNode & { type: 'wall' } => node.type === 'wall', + ), + ) + issues.push( + ...wallEndShortIssues({ levelId: level.levelId, levelName, bodies }), + ...wallNearlyAlignedIssues({ levelId: level.levelId, levelName, bodies }), + ) // A free-standing wall (garden wall, half wall) is legitimate, not something to repair. for (const end of detectOpenWallEnds(nodes, level.levelId)) { if (end.reason === 'isolated') continue diff --git a/packages/core/src/agent-operations/wall-joins.test.ts b/packages/core/src/agent-operations/wall-joins.test.ts new file mode 100644 index 0000000000..19d291da13 --- /dev/null +++ b/packages/core/src/agent-operations/wall-joins.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, test } from 'bun:test' +import { WallNode } from '../schema' +import { wallBodies, wallEndShortIssues, wallNearlyAlignedIssues } from './wall-joins' + +type Pt = [number, number] + +const wall = (id: string, start: Pt, end: Pt, extra: Record = {}) => + WallNode.parse({ + id: `wall_${id}`, + name: `Wall ${id}`, + parentId: 'level_0', + start, + end, + thickness: 0.1, + ...extra, + }) + +const bodiesOf = (...walls: ReturnType[]) => wallBodies(walls) +const shorts = (...walls: ReturnType[]) => + wallEndShortIssues({ levelId: 'level_0', levelName: 'Ground floor', bodies: bodiesOf(...walls) }) +const aligned = (...walls: ReturnType[]) => + wallNearlyAlignedIssues({ + levelId: 'level_0', + levelName: 'Ground floor', + bodies: bodiesOf(...walls), + }) + +/** A point `length` away from `from`, turned `degrees` off the +x axis. */ +const toward = (from: Pt, length: number, degrees: number): Pt => [ + from[0] + length * Math.cos((degrees * Math.PI) / 180), + from[1] + length * Math.sin((degrees * Math.PI) / 180), +] + +describe('wall_end_short', () => { + const across = wall('across', [0, 0], [4, 0]) // 10 cm thick, along x + + test("a wall that stops short of another one's body is said with the daylight and both names", () => { + // 15 cm from the other's centre line, 5 cm of that is the other's half thickness: 10 cm of daylight + const issues = shorts(across, wall('stub', [2, 2], [2, 0.15])) + expect(issues).toHaveLength(1) + expect(issues[0]).toMatchObject({ + type: 'wall_end_short', + severity: 'warning', + wallId: 'wall_stub', + wallName: 'Wall stub', + end: 'end', + otherWallId: 'wall_across', + otherWallName: 'Wall across', + gap: 0.1, + at: [2, 0.15], + nodeIds: ['wall_stub', 'wall_across'], + }) + expect(issues[0]!.message).toContain('10.0 cm short of Wall across (wall_across)') + }) + + test('3 cm of daylight is the least: nearer is a joint', () => { + const issues = shorts(across, wall('s3', [2, 2], [2, 0.081])) + expect(issues.map((issue) => issue.gap)).toEqual([0.031]) + expect(shorts(across, wall('s2', [2, 2], [2, 0.079]))).toEqual([]) // 2.9 cm + }) + + test('an end that touches or enters the other body is a joint', () => { + expect(shorts(across, wall('in', [2, 2], [2, 0.03]))).toEqual([]) + expect(shorts(across, wall('touch', [2, 2], [2, 0.05]))).toEqual([]) + expect(shorts(across, wall('through', [2, 2], [2, -1]))).toEqual([]) + }) + + test('25 cm of daylight is the most: further is a free end near a wall, not a missed joint', () => { + expect(shorts(across, wall('near', [2, 2], [2, 0.3]))).toHaveLength(1) // 0.30 - 0.05 = 25 cm + expect(shorts(across, wall('far', [2, 2], [2, 0.31]))).toEqual([]) + }) + + test('two walls on one line with a gap between their ends: the gap along the axis, no half thickness taken off', () => { + const issues = shorts(wall('left', [0, 0], [2, 0]), wall('right', [2.12, 0], [4, 0])) + expect(issues.map((issue) => [issue.wallId, issue.end, issue.gap])).toEqual([ + ['wall_left', 'end', 0.12], + ['wall_right', 'start', 0.12], + ]) + }) + + test("walls running side by side: the nearest wall is at the end's side, not ahead of it", () => { + expect(shorts(wall('a', [0, 0], [3, 0]), wall('b', [0, 0.2], [4, 0.2]))).toEqual([]) + }) + + test("an end angled at the other wall is measured from its nearest corner to the body's face", () => { + // a wall coming in at 45 degrees; its end cap's lower corner is 10 cm above the face of the body at y = 0.05 + const cornerDrop = 0.05 * Math.SQRT1_2 + const e: Pt = [2, 0.05 + 0.1 + cornerDrop] + const issues = shorts(across, wall('diag', [e[0] + 2, e[1] + 2], e)) + expect(issues.map((issue) => [issue.wallId, issue.gap])).toEqual([['wall_diag', 0.1]]) + }) + + test('a curved wall is not measured and does not hide a gap by standing near it', () => { + const curved = wall('curved', [0, 0], [4, 0], { curveOffset: 0.8 }) + expect(shorts(curved, wall('stub', [2, 2], [2, 0.15]))).toEqual([]) + }) + + test('the justification moves the body, so the gap is measured from the body, not the stored line', () => { + // body on the left of the stored line (justification a): shifted 5 cm toward +z + const left = wall('left', [0, 0], [4, 0], { justification: 'a' }) + expect(left.thickness).toBe(0.1) + const issues = shorts(left, wall('stub', [2, 2], [2, 0.2])) + expect(issues[0]?.gap).toBeCloseTo(0.2 - 0.1, 3) + }) +}) + +describe('wall_nearly_aligned', () => { + /** A 4 m wall, a short wall that turns `degrees` off its line, and a 4 m wall carrying on from the short wall's end. */ + const holder = (degrees: number, length = 1) => { + const end = toward([4, 0], length, degrees) + return [ + wall('left', [0, 0], [4, 0]), + wall('gap', [4, 0], end), + wall('right', end, [end[0] + 4, end[1]]), + ] + } + + test('a short wall skewed between two walls on one line is the one said, with both neighbours and its angle', () => { + const issues = aligned(...holder(4)) + expect(issues).toHaveLength(1) + expect(issues[0]).toMatchObject({ + type: 'wall_nearly_aligned', + severity: 'warning', + wallId: 'wall_gap', + angle: 4, + }) + expect(issues[0]!.neighbours.map((n) => [n.wallId, n.end, n.angle])).toEqual([ + ['wall_left', 'start', 4], + ['wall_right', 'end', 4], + ]) + // the wall's far end stands sin(4 deg) x 1 m off the line of the first wall: 7.0 cm + expect(issues[0]!.offset).toBeCloseTo(0.07, 2) + expect(issues[0]!.nodeIds).toEqual(['wall_gap', 'wall_left', 'wall_right']) + }) + + test('0.5 to 6 degrees is the band: a straighter line is one line, a larger turn is an angle drawn on purpose', () => { + expect(aligned(...holder(0.3, 6))).toEqual([]) // 0.3 degrees: the line of a plan read with noise + expect(aligned(...holder(0.6, 6))).toHaveLength(1) + expect(aligned(...holder(5.9))).toHaveLength(1) + expect(aligned(...holder(8))).toEqual([]) // an angle somebody drew + expect(aligned(...holder(45))).toEqual([]) // a bay + expect(aligned(...holder(90))).toEqual([]) // a corner + }) + + test("a skew that moves the wall's end less than 2 cm off the line is within drawing tolerance", () => { + expect(aligned(...holder(1, 1))).toEqual([]) // 1.7 cm + expect(aligned(...holder(1, 1.3))).toHaveLength(1) // 2.3 cm + }) + + test('one wall carrying on into another a few degrees off: the shorter wall is said, once', () => { + const long = wall('long', [0, 0], [5, 0]) + const issues = aligned(long, wall('short', [5, 0], toward([5, 0], 1, 3))) + expect(issues).toHaveLength(1) + expect(issues[0]).toMatchObject({ wallId: 'wall_short', angle: 3 }) + expect(issues[0]!.neighbours).toEqual([ + { wallId: 'wall_long', name: 'Wall long', end: 'start', angle: 3 }, + ]) + }) + + test('walls that meet at a corner, a T or by an end that is not on theirs are not a line carrying on', () => { + expect(aligned(wall('a', [0, 0], [4, 0]), wall('b', [4, 0], [4, 3]))).toEqual([]) + // a T: the stem ends on the middle of the bar + expect(aligned(wall('bar', [0, 0], [4, 0]), wall('stem', [2, 0], [2.04, 3]))).toEqual([]) + // two walls 3 degrees apart whose ends are 0.5 m from each other + expect( + aligned(wall('a', [0, 0], [4, 0]), wall('b', toward([4.5, 0], 0, 0), toward([4.5, 0], 4, 3))), + ).toEqual([]) + }) + + test('a T whose bar is drawn in two pieces on one line is quiet', () => { + expect( + aligned( + wall('west', [0, 0], [2, 0]), + wall('east', [2, 0], [4, 0]), + wall('stem', [2, 0], [2, 3]), + ), + ).toEqual([]) + }) + + test('curved walls are not measured', () => { + expect( + aligned( + wall('a', [0, 0], [4, 0]), + wall('b', [4, 0], toward([4, 0], 1, 4), { curveOffset: 0.3 }), + ), + ).toEqual([]) + }) +}) diff --git a/packages/core/src/agent-operations/wall-joins.ts b/packages/core/src/agent-operations/wall-joins.ts new file mode 100644 index 0000000000..c850ab4633 --- /dev/null +++ b/packages/core/src/agent-operations/wall-joins.ts @@ -0,0 +1,390 @@ +import type { AnyNode } from '../schema' +import { isCurvedWall } from '../systems/wall/wall-curve' +import { getWallBodyLine } from '../systems/wall/wall-frame' + +/** + * Two facts about where straight walls of one level meet, for `verify_scene`: + * + * - `wall_end_short`: a wall end that stops short of another wall's body, leaving daylight + * between them. The room graph (`wall_open_end`) elects an end within 8 cm of a body as joined + * and says nothing of it; the floor, the finish and the render show the slot. + * - `wall_nearly_aligned`: a wall that continues another a few degrees off its axis, or sits + * between two aligned walls a few degrees off their line (a short wall holding a door, + * drawn skewed). A wall angled by design turns more than this and does not qualify. + * + * Measured on the walls' bodies (the stored line shifted by the justification, a thickness wide), + * straight walls only: a curved wall has no single axis and no single end cap. + */ + +type WallNode = AnyNode & { type: 'wall' } +type Pt = readonly [number, number] + +/** An end that stops this far short of a body or more is a gap; nearer is a joint. */ +export const END_SHORT_MIN_M = 0.03 +/** Further than this the end is a free end that happens to stand near a wall, not a missed joint. */ +export const END_SHORT_MAX_M = 0.25 +/** A turn smaller than this is a straight line drawn with noise; a larger one up to the maximum is the finding. */ +export const ALIGN_MIN_DEG = 0.5 +/** A turn larger than this is an angle somebody drew (a bay, an angled wing). */ +export const ALIGN_MAX_DEG = 6 +/** A skew that moves the wall's far end less than this off its neighbour's line is within drawing tolerance, and is not said. */ +export const ALIGN_MIN_OFFSET_M = 0.02 +/** The two neighbours of a wall count as aligned with each other within this. */ +const NEIGHBOURS_ALIGNED_DEG = 0.5 +/** Shortest wall that is measured. */ +const MIN_LENGTH_M = 0.05 +/** The nearest points of two parts of a wall end and a body must lie this far ahead of the end, as a share of the distance (cos of 60 degrees). */ +const AHEAD = 0.5 + +export type WallBody = { + id: string + name: string + /** The body's centre line, start to end. */ + a: Pt + b: Pt + length: number + /** Unit direction a to b. */ + ux: number + uy: number + thickness: number +} + +export type WallEndShortIssue = { + type: 'wall_end_short' + message: string + severity: 'warning' + levelId: string + wallId: string + wallName: string + end: 'start' | 'end' + otherWallId: string + otherWallName: string + /** Daylight between the end and the other wall's body, in metres. */ + gap: number + /** Where the end is, [x, z]. */ + at: [number, number] + nodeIds: [string, string] +} + +export type WallNearlyAlignedIssue = { + type: 'wall_nearly_aligned' + message: string + severity: 'warning' + levelId: string + wallId: string + wallName: string + /** The largest angle between the wall's axis and a neighbour's, in degrees. */ + angle: number + /** How far the wall's far end stands off the neighbour's line, in metres. */ + offset: number + neighbours: { wallId: string; name: string; end: 'start' | 'end'; angle: number }[] + nodeIds: string[] +} + +const round = (value: number, places: number) => Math.round(value * 10 ** places) / 10 ** places +const nameOf = (wall: WallNode) => wall.name?.trim() || wall.id + +/** The straight, visible walls long enough to measure, as bodies. */ +export function wallBodies(walls: readonly WallNode[]): WallBody[] { + const bodies: WallBody[] = [] + for (const wall of walls) { + if (wall.visible === false || isCurvedWall(wall)) continue + const line = getWallBodyLine(wall) + const dx = line.end.x - line.start.x + const dy = line.end.y - line.start.y + const length = Math.hypot(dx, dy) + if (!(length >= MIN_LENGTH_M) || !Number.isFinite(length)) continue + bodies.push({ + id: wall.id, + name: nameOf(wall), + a: [line.start.x, line.start.y], + b: [line.end.x, line.end.y], + length, + ux: dx / length, + uy: dy / length, + thickness: wall.thickness ?? 0.1, + }) + } + return bodies.sort((p, q) => (p.id < q.id ? -1 : 1)) +} + +const dot = (ax: number, ay: number, bx: number, by: number) => ax * bx + ay * by + +/** The closest points of two segments and their distance (0 where they cross). */ +function closestOfSegments(p1: Pt, p2: Pt, q1: Pt, q2: Pt): { d: number; p: Pt; q: Pt } { + const d1x = p2[0] - p1[0] + const d1y = p2[1] - p1[1] + const d2x = q2[0] - q1[0] + const d2y = q2[1] - q1[1] + const rx = p1[0] - q1[0] + const ry = p1[1] - q1[1] + const a = dot(d1x, d1y, d1x, d1y) + const e = dot(d2x, d2y, d2x, d2y) + const f = dot(d2x, d2y, rx, ry) + let s: number + let t: number + if (a <= 1e-12 && e <= 1e-12) { + s = 0 + t = 0 + } else if (a <= 1e-12) { + s = 0 + t = Math.min(1, Math.max(0, f / e)) + } else { + const c = dot(d1x, d1y, rx, ry) + if (e <= 1e-12) { + t = 0 + s = Math.min(1, Math.max(0, -c / a)) + } else { + const b = dot(d1x, d1y, d2x, d2y) + const denom = a * e - b * b + s = denom > 1e-12 ? Math.min(1, Math.max(0, (b * f - c * e) / denom)) : 0 + t = (b * s + f) / e + if (t < 0) { + t = 0 + s = Math.min(1, Math.max(0, -c / a)) + } else if (t > 1) { + t = 1 + s = Math.min(1, Math.max(0, (b - c) / a)) + } + } + } + const p: Pt = [p1[0] + d1x * s, p1[1] + d1y * s] + const q: Pt = [q1[0] + d2x * t, q1[1] + d2y * t] + return { d: Math.hypot(p[0] - q[0], p[1] - q[1]), p, q } +} + +/** The four corners of a body, in order. */ +function corners(body: WallBody): Pt[] { + const nx = -body.uy * (body.thickness / 2) + const ny = body.ux * (body.thickness / 2) + return [ + [body.a[0] + nx, body.a[1] + ny], + [body.b[0] + nx, body.b[1] + ny], + [body.b[0] - nx, body.b[1] - ny], + [body.a[0] - nx, body.a[1] - ny], + ] +} + +function insideRectangle(point: Pt, rectangle: readonly Pt[]) { + let sign = 0 + for (let i = 0; i < 4; i++) { + const from = rectangle[i]! + const to = rectangle[(i + 1) % 4]! + const cross = + (to[0] - from[0]) * (point[1] - from[1]) - (to[1] - from[1]) * (point[0] - from[0]) + if (Math.abs(cross) < 1e-12) continue + const s = Math.sign(cross) + if (sign === 0) sign = s + else if (s !== sign) return false + } + return true +} + +/** The closest points of a segment and a body's rectangle; 0 apart where they touch or overlap. */ +function closestToBody(c1: Pt, c2: Pt, body: WallBody): { d: number; p: Pt; q: Pt } { + const rectangle = corners(body) + if (insideRectangle(c1, rectangle)) return { d: 0, p: c1, q: c1 } + if (insideRectangle(c2, rectangle)) return { d: 0, p: c2, q: c2 } + let best = { d: Number.POSITIVE_INFINITY, p: c1, q: c1 } as { d: number; p: Pt; q: Pt } + for (let i = 0; i < 4; i++) { + const hit = closestOfSegments(c1, c2, rectangle[i]!, rectangle[(i + 1) % 4]!) + if (hit.d < best.d) best = hit + } + return best +} + +const endPoint = (body: WallBody, end: 'start' | 'end'): Pt => (end === 'start' ? body.a : body.b) +/** The unit direction pointing out of the wall at an end. */ +const outward = (body: WallBody, end: 'start' | 'end'): Pt => + end === 'start' ? [-body.ux, -body.uy] : [body.ux, body.uy] + +/** + * Wall ends that stop 3 to 25 cm short of another wall of the level: the daylight between the + * end's cap and the other wall's body, the other wall named. An end that touches any wall (the + * caps and bodies within 3 cm) is a joint and is not asked; so is an end whose nearest wall lies + * to its side, not ahead of it (two walls running side by side). + */ +export function wallEndShortIssues(input: { + levelId: string + levelName: string + bodies: readonly WallBody[] + min?: number + max?: number +}): WallEndShortIssue[] { + const min = input.min ?? END_SHORT_MIN_M + const max = input.max ?? END_SHORT_MAX_M + const issues: WallEndShortIssue[] = [] + for (const wall of input.bodies) { + for (const end of ['start', 'end'] as const) { + const e = endPoint(wall, end) + const [ox, oy] = outward(wall, end) + const half = wall.thickness / 2 + const cap1: Pt = [e[0] - oy * half, e[1] + ox * half] + const cap2: Pt = [e[0] + oy * half, e[1] - ox * half] + let touching = false + let nearest: { other: WallBody; d: number } | undefined + for (const other of input.bodies) { + if (other.id === wall.id) continue + const hit = closestToBody(cap1, cap2, other) + if (hit.d < min) { + touching = true + break + } + if (hit.d > max) continue + const vx = hit.q[0] - hit.p[0] + const vy = hit.q[1] - hit.p[1] + if (dot(vx, vy, ox, oy) < AHEAD * hit.d) continue + if (!nearest || hit.d < nearest.d) nearest = { other, d: hit.d } + } + if (touching || !nearest) continue + const gap = round(nearest.d, 3) + const cm = (gap * 100).toFixed(1) + issues.push({ + type: 'wall_end_short', + severity: 'warning', + levelId: input.levelId, + wallId: wall.id, + wallName: wall.name, + end, + otherWallId: nearest.other.id, + otherWallName: nearest.other.name, + gap, + at: [round(e[0], 3), round(e[1], 3)], + nodeIds: [wall.id, nearest.other.id], + message: `On ${input.levelName}, ${wall.name} (${wall.id}) ${end} stops ${cm} cm short of ${nearest.other.name} (${nearest.other.id}) at (${e[0].toFixed(2)}, ${e[1].toFixed(2)}): ${cm} cm of daylight between them (asked for a gap of ${min * 100}-${max * 100} cm; a joint is closer, a free end further)`, + }) + } + } + return issues +} + +export type Bend = { + wall: WallBody + end: 'start' | 'end' + other: WallBody + otherEnd: 'start' | 'end' + angle: number +} + +const degrees = (radians: number) => (radians * 180) / Math.PI +const angleBetween = (ax: number, ay: number, bx: number, by: number) => + degrees(Math.acos(Math.min(1, Math.max(-1, dot(ax, ay, bx, by))))) +/** Distance from a point to the infinite line of a body. */ +const offLine = (point: Pt, body: WallBody) => + Math.abs((point[0] - body.a[0]) * body.uy - (point[1] - body.a[1]) * body.ux) + +/** + * Every place one wall carries on into another: the two bodies' ends within a wall thickness of + * each other, and the second heading away from the joint within `maxDeg` of the first's heading. + * The angle is the turn between them (0 is one straight line). + */ +export function wallContinuations(bodies: readonly WallBody[], maxDeg: number): Bend[] { + const bends: Bend[] = [] + for (const wall of bodies) { + for (const end of ['start', 'end'] as const) { + const e = endPoint(wall, end) + const [ox, oy] = outward(wall, end) + for (const other of bodies) { + if (other.id === wall.id) continue + for (const otherEnd of ['start', 'end'] as const) { + const f = endPoint(other, otherEnd) + if (Math.hypot(e[0] - f[0], e[1] - f[1]) > Math.max(wall.thickness, other.thickness)) + continue + // the direction the other wall takes away from the joint + const [dx, dy] = outward(other, otherEnd === 'start' ? 'end' : 'start') + const angle = angleBetween(ox, oy, dx, dy) + if (angle <= maxDeg) bends.push({ wall, end, other, otherEnd, angle }) + } + } + } + } + return bends +} + +/** + * A wall that continues another at an angle between 0.5 and 6 degrees: joined at an end and + * carrying on in nearly the same direction. A wall between two neighbours that are aligned with + * each other is the one reported (the short wall holding a door, drawn skewed), with both + * neighbours; a single bend is reported on the shorter of its two walls. + */ +export function wallNearlyAlignedIssues(input: { + levelId: string + levelName: string + bodies: readonly WallBody[] + min?: number + max?: number + minOffset?: number +}): WallNearlyAlignedIssue[] { + const min = input.min ?? ALIGN_MIN_DEG + const max = input.max ?? ALIGN_MAX_DEG + const minOffset = input.minOffset ?? ALIGN_MIN_OFFSET_M + const bends = wallContinuations(input.bodies, max).filter((bend) => bend.angle >= min) + const byWall = new Map() + for (const bend of bends) byWall.set(bend.wall.id, [...(byWall.get(bend.wall.id) ?? []), bend]) + const issues: WallNearlyAlignedIssue[] = [] + const covered = new Set() + const neighbourOf = (bend: Bend) => ({ + wallId: bend.other.id, + name: bend.other.name, + end: bend.end, + angle: round(bend.angle, 1), + }) + const issue = (wall: WallBody, own: Bend[], offset: number): WallNearlyAlignedIssue => { + const angle = round(Math.max(...own.map((bend) => bend.angle)), 1) + const neighbours = own.map(neighbourOf) + return { + type: 'wall_nearly_aligned', + severity: 'warning', + levelId: input.levelId, + wallId: wall.id, + wallName: wall.name, + angle, + offset: round(offset, 3), + neighbours, + nodeIds: [wall.id, ...own.map((bend) => bend.other.id)], + message: `On ${input.levelName}, ${wall.name} (${wall.id}) lies ${angle.toFixed(1)}° off the axis of ${neighbours + .map((n) => `${n.name} (${n.wallId}) at its ${n.end} (${n.angle.toFixed(1)}°)`) + .join( + ' and ', + )}; its far end stands ${(offset * 100).toFixed(1)} cm off that line (asked for a turn of ${min}-${max}° that moves the far end 2 cm or more: a straighter line is one line, a larger turn is an angle drawn on purpose)`, + } + } + // a wall between two neighbours aligned with each other: the skewed one + for (const [id, own] of byWall) { + const wall = own[0]!.wall + const starts = own.filter((bend) => bend.end === 'start') + const ends = own.filter((bend) => bend.end === 'end') + if (!starts.length || !ends.length) continue + for (const first of starts) { + for (const second of ends) { + const between = angleBetween( + first.other.ux, + first.other.uy, + second.other.ux, + second.other.uy, + ) + const aligned = Math.min(between, 180 - between) < NEIGHBOURS_ALIGNED_DEG + if (!aligned || covered.has(id)) continue + covered.add(id) + const offset = Math.max(offLine(wall.a, first.other), offLine(wall.b, first.other)) + if (offset >= minOffset) issues.push(issue(wall, [first, second], offset)) + } + } + } + // a single bend: the shorter wall carries it, once + const reported = new Set() + for (const bend of bends) { + if (covered.has(bend.wall.id) || covered.has(bend.other.id)) continue + const shorter = + bend.wall.length < bend.other.length || + (bend.wall.length === bend.other.length && bend.wall.id < bend.other.id) + if (!shorter) continue + const key = [bend.wall.id, bend.other.id].sort().join('|') + if (reported.has(key)) continue + reported.add(key) + const far = bend.end === 'start' ? bend.wall.b : bend.wall.a + const offset = offLine(far, bend.other) + if (offset >= minOffset) issues.push(issue(bend.wall, [bend], offset)) + } + return issues.sort((a, b) => (a.wallId < b.wallId ? -1 : 1)) +} diff --git a/packages/core/src/agent-tools/verify-scene.ts b/packages/core/src/agent-tools/verify-scene.ts index 11f8e8ab7c..993d1898fc 100644 --- a/packages/core/src/agent-tools/verify-scene.ts +++ b/packages/core/src/agent-tools/verify-scene.ts @@ -16,7 +16,7 @@ export function extendVerifyScene(extension: { } const DESCRIPTION = - 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' + 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' export const verifySceneTool = { name: 'verify_scene', diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index 767472e23e..6628160e8b 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -306,7 +306,7 @@ const SHARED_TOOLS: SharedTool[] = [ z.looseObject({ type: z.string(), message: z.string(), - severity: z.literal('info').optional(), + severity: z.enum(['info', 'warning']).optional(), nodeId: z.string().optional(), path: z.string().optional(), zoneId: z.string().optional(), From a0906d379ad6c4fbed8748e7d8d93240ae9e1935 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 16:19:22 +0100 Subject: [PATCH 02/40] verify_scene names two rooms on one floor and floor no zone claims zones_overlap: two rooms whose clear floors overlap, with the strip's area, width and place; and floor_unclaimed: floor inside a space the zones cover past half that no zone or stair claims, as a strip or a region. Both are warnings, quiet under 0.1 m2 (overlap), 0.3 m2 (unclaimed) or 15 cm wide. Wall bodies are not floor, a stair claims the floor it stands on, rooms in one space with no wall between them are space_many_rooms and are not named again, and a bare space stays space_no_room. Rule tests for the geometry, and seven shared case rows: the two findings, the tiling that is quiet whether the zones meet on the partition's centre line or its faces, the space no zone covers, and the stair that claims the floor a zone stops short of. Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/scene-check-cases.ts | 122 ++++++++ .../src/agent-operations/room-findings.ts | 53 +++- .../agent-operations/stair-plan-footprint.ts | 60 ++++ .../agent-operations/zone-coverage.test.ts | 70 +++++ .../src/agent-operations/zone-coverage.ts | 292 ++++++++++++++++++ packages/core/src/agent-tools/verify-scene.ts | 2 +- 6 files changed, 595 insertions(+), 4 deletions(-) create mode 100644 packages/core/src/agent-operations/stair-plan-footprint.ts create mode 100644 packages/core/src/agent-operations/zone-coverage.test.ts create mode 100644 packages/core/src/agent-operations/zone-coverage.ts diff --git a/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts b/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts index 7db4926c9a..9aca12349c 100644 --- a/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts @@ -383,6 +383,36 @@ export const VALIDATE_SCENE_CASES: AgentToolCase[] = [ ), ] +/** An 8 × 3 m house with a partition at x = 4: two spaces, west and east, each as the zones given cover it. */ +const twoSpaces = (...extra: AnyNode[]) => + ground( + ...wallRing('level_0', 'pair', rect(0, 0, 8, 3)), + WallNode.parse({ id: 'wall_partition', parentId: 'level_0', start: [4, 0], end: [4, 3] }), + ...extra, + ) + +const westRoom = (extra = {}) => roomZone('zone_west', 'level_0', 'Study', rect(0, 0, 4, 3), extra) +const eastRoom = (polygon: Pt[] = rect(4, 0, 8, 3), extra = {}) => + roomZone('zone_east', 'level_0', 'Bedroom', polygon, extra) + +/** A stair as wide as the east space, standing on its far end: floor a zone need not claim. */ +const wideStair = () => [ + StairNode.parse({ + id: 'stair_wide', + parentId: 'level_0', + name: 'Wide stair', + position: [6, 0, 1.5], + }), + StairSegmentNode.parse({ + id: 'sseg_wide', + parentId: 'stair_wide', + width: 3.9, + length: 1.5, + height: 2.5, + stepCount: 10, + }), +] + export const CHECK_ROOMS_CASES: AgentToolCase[] = [ verify( 'check_rooms { levelId } counts ("4 walls, 1 detected spaces, 1 zones"): the level\'s content.walls, spaces and content.zones', @@ -700,6 +730,98 @@ export const CHECK_ROOMS_CASES: AgentToolCase[] = [ }, { lacks: [{ type: 'room_not_enclosed' }] }, ), + // Rooms are tiled by their zones: two rooms on one floor, or floor the walls enclose that no zone claims. Wall bodies are + // not floor, a width is the short side of the rectangle with the piece's area and perimeter after a 7.5 cm opening, and what is under 0.1 m² (overlap) or 0.3 m² (unclaimed) or 15 cm wide is quiet. + // A store adopts a drawn zone as its space's room when it loads a scene, so a zone that overlaps another or stops short can only + // be read as declared: the cases that raise a finding run on the core runner; the quiet ones run everywhere. + verify( + 'verify_scene on two rooms whose zones share a half-metre strip across their partition: zones_overlap names both rooms with the strip\'s area, width and place', + () => twoSpaces(westRoom(), eastRoom(rect(3.5, 0, 8, 3))), + { + surfaces: ['core'], + contains: [{ type: 'zones_overlap', severity: 'warning', levelId: 'level_0' }], + lacks: [{ type: 'space_many_rooms' }], + check: (result) => { + const found = issuesOf(result, 'zones_overlap') + const [first] = found + const ids = [...((first?.zoneIds ?? []) as string[])].sort().join() + const [x] = (first?.at ?? [0, 0]) as Pt + return [ + ...(found.length === 1 ? [] : [`${found.length} zones_overlap, not one strip`]), + ...(ids === 'zone_east,zone_west' ? [] : [`zones ${ids}, not the study and the bedroom`]), + // 0.5 m less the partition's half thickness on its side, by the wall-to-wall length: about 0.45 x 2.9 + ...((first?.area as number) > 1.2 && (first?.area as number) < 1.4 + ? [] + : [`area ${first?.area} m², not the strip beside the partition`]), + ...((first?.width as number) > 0.4 && (first?.width as number) < 0.5 + ? [] + : [`width ${first?.width} m, not about 0.45`]), + ...(x > 3.5 && x < 4 ? [] : [`at x ${x}, not in the strip`]), + ] + }, + }, + ), + verify( + 'verify_scene on two rooms whose zones meet on the partition\'s centre line: neither overlap nor unclaimed floor', + () => twoSpaces(westRoom(), eastRoom()), + { lacks: [{ type: 'zones_overlap' }, { type: 'floor_unclaimed' }] }, + ), + verify( + 'verify_scene on two rooms whose zones stop at the partition\'s faces, not its centre line: the wall body is not floor, so nothing is unclaimed or overlapped', + () => + twoSpaces( + roomZone('zone_west', 'level_0', 'Study', rect(0.05, 0.05, 3.95, 2.95)), + eastRoom(rect(4.05, 0.05, 7.95, 2.95)), + ), + { lacks: [{ type: 'zones_overlap' }, { type: 'floor_unclaimed' }] }, + ), + verify( + 'verify_scene on a room whose zone covers three quarters of its space: floor_unclaimed with the strip\'s area, width and place, beside the room', + () => twoSpaces(westRoom(), eastRoom(rect(4, 0, 8, 2.25))), + { + surfaces: ['core'], + contains: [{ type: 'floor_unclaimed', severity: 'warning', levelId: 'level_0' }], + lacks: [{ type: 'space_no_room' }, { type: 'zones_overlap' }], + check: (result) => { + const found = issuesOf(result, 'floor_unclaimed') + const [first] = found + const [, z] = (first?.at ?? [0, 0]) as Pt + return [ + ...(found.length === 1 ? [] : [`${found.length} floor_unclaimed, not one strip`]), + // 0.7 m by the east space's 3.9 m + ...((first?.area as number) > 2.5 && (first?.area as number) < 2.9 + ? [] + : [`area ${first?.area} m², not the strip the zone stops short of`]), + ...((first?.width as number) > 0.65 && (first?.width as number) < 0.75 + ? [] + : [`width ${first?.width} m, not about 0.7`]), + ...(z > 2.25 ? [] : [`at z ${z}, not beyond the zone's edge`]), + ...(((first?.zoneIds ?? []) as string[]).includes('zone_east') + ? [] + : ['the room beside the strip is not named']), + ] + }, + }, + ), + verify( + 'verify_scene on a space no zone covers: space_no_room says it, floor_unclaimed does not repeat it', + () => ground(...wallRing('level_0', 'bare', ROOM)), + { + surfaces: ['core'], + contains: [{ type: 'space_no_room', levelId: 'level_0' }], + lacks: [{ type: 'floor_unclaimed' }], + }, + ), + verify( + 'verify_scene on a space whose zone stops short where a stair stands: the stair claims its floor, so nothing is unclaimed', + () => twoSpaces(westRoom(), eastRoom(rect(4, 0, 8, 1.6)), ...wideStair()), + { lacks: [{ type: 'floor_unclaimed' }] }, + ), + verify( + 'verify_scene on the same space with no stair: the floor the zone stops short of is unclaimed', + () => twoSpaces(westRoom(), eastRoom(rect(4, 0, 8, 1.6))), + { surfaces: ['core'], contains: [{ type: 'floor_unclaimed', levelId: 'level_0' }] }, + ), // Where straight walls meet: an end that stops 3-25 cm short of another wall (daylight between them), and a wall a few // degrees off the line of its neighbours (a short wall holding a door, drawn skewed). Angled walls drawn on purpose are quiet. // wall_open_end (info, with the nearest wall to repair toward) says the same end when the room graph elects no joint: both stand. diff --git a/packages/core/src/agent-operations/room-findings.ts b/packages/core/src/agent-operations/room-findings.ts index fabb7f7f70..5d39ebe257 100644 --- a/packages/core/src/agent-operations/room-findings.ts +++ b/packages/core/src/agent-operations/room-findings.ts @@ -4,7 +4,15 @@ import { distanceToSegment } from '../lib/room-topology-index' import { detectSpacesForLevel } from '../lib/space-detection' import type { AnyNode } from '../schema' import { nodesOnLevel } from './scene-queries' +import { type StairNode, stairFootprintPolygons } from './stair-plan-footprint' import type { SceneNodes } from './types' +import { + type FloorUnclaimedIssue, + floorUnclaimedIssues, + wallBodies, + type ZonesOverlapIssue, + zonesOverlapIssues, +} from './zone-coverage' /** A space the walls and separators enclose, where a finding about it places it. */ type SpacePlace = { @@ -19,11 +27,16 @@ type SpacePlace = { /** * A level's rooms against the spaces its walls and separators enclose (the editor's detected * spaces): a space no zone covers, a space several zones split, a room the walls do not close, a - * room with no name. + * room with no name, two rooms on the same floor, floor in a covered space that no zone claims. */ export type RoomFinding = - | ({ type: 'space_no_room'; message: string } & SpacePlace) - | ({ type: 'space_many_rooms'; message: string; zoneIds: string[] } & SpacePlace) + | ({ type: 'space_no_room'; message: string; severity?: undefined } & SpacePlace) + | ({ + type: 'space_many_rooms' + message: string + severity?: undefined + zoneIds: string[] + } & SpacePlace) | { type: 'room_not_enclosed' message: string @@ -33,6 +46,8 @@ export type RoomFinding = zoneId: string } | { type: 'room_unnamed'; message: string; severity: 'info'; levelId: string; zoneId: string } + | ZonesOverlapIssue + | FloorUnclaimedIssue type Zone = AnyNode & { type: 'zone' } type Wall = AnyNode & { type: 'wall' } @@ -142,6 +157,10 @@ export function roomFindings( const roomWalls = walls.filter((wall) => (wall.height ?? ROOM_WALL_HEIGHT) >= ROOM_WALL_HEIGHT) const rooms = zones.map((zone) => zone.spaceRole === 'room' || walled(zone, roomWalls) >= HALF) const issues: RoomFinding[] = [] + /** The rooms each `space_many_rooms` names, which `zones_overlap` leaves to it. */ + const splitSpaces: ReadonlySet[] = [] + /** The spaces zones cover past half: floor left over in them is a finding, a bare space is `space_no_room`. */ + const coveredSpaces: typeof spaces = [] spaces.forEach((space, index) => { const shape = spaceShapes[index]! @@ -152,6 +171,7 @@ export function roomFindings( rooms[z] && zone.floor?.support !== 'open' && covered(zoneShapes[z]!, [shape]) >= HALF, ) const noRoom = covered(shape, zoneShapes) < HALF + if (!noRoom) coveredSpaces.push(space) if (!noRoom && inside.length < 2) return const spaceArea = round(shape.area) const [x, z] = polygonInteriorPoint(space, true).map(round) as [number, number] @@ -161,6 +181,7 @@ export function roomFindings( at: [x, z] as [number, number], wallIds: space.wallIds, } + if (!noRoom) splitSpaces.push(new Set(inside.map((zone) => zone.id))) const where = `On ${levelName}, walls ${space.wallIds.join(', ')} enclose a ${spaceArea.toFixed(1)} m² space at (${x.toFixed(2)}, ${z.toFixed(2)})` issues.push( noRoom @@ -207,5 +228,31 @@ export function roomFindings( }) }) + const floored = zones.filter( + (zone, index) => rooms[index] && zone.floor?.support !== 'open' && zone.hasFloor !== false, + ) + // walls whose bodies cannot be read leave the floor unmeasured: neither rule says anything on this level + const bodies = wallBodies(walls) + if (bodies) + issues.push( + ...zonesOverlapIssues({ + levelId, + levelName, + rooms: floored, + bodies, + skip: (a, b) => splitSpaces.some((ids) => ids.has(a.id) && ids.has(b.id)), + }), + ...floorUnclaimedIssues({ + levelId, + levelName, + spaces: coveredSpaces, + zones, + bodies, + stairs: onLevel + .filter((node): node is StairNode => node.type === 'stair') + .flatMap((stair) => stairFootprintPolygons(nodes, stair)), + }), + ) + return { spaces: spaces.length, issues } } diff --git a/packages/core/src/agent-operations/stair-plan-footprint.ts b/packages/core/src/agent-operations/stair-plan-footprint.ts new file mode 100644 index 0000000000..28079cfe31 --- /dev/null +++ b/packages/core/src/agent-operations/stair-plan-footprint.ts @@ -0,0 +1,60 @@ +import type { AnyNode } from '../schema' +import { computeSegmentTransforms, rotateXZ } from '../systems/stair/stair-footprint' +import { resolveStairTotalRise } from '../systems/stair/stair-rise-query' +import type { Vec2 } from './plan-geometry' +import type { SceneNodes } from './types' + +export type StairNode = AnyNode & { type: 'stair' } + +function toWorldPlanPoint(stair: StairNode, localX: number, localZ: number): Vec2 { + const [worldX, worldZ] = rotateXZ(localX, localZ, stair.rotation ?? 0) + return [stair.position[0] + worldX, stair.position[2] + worldZ] +} + +/** The floor a stair stands on, in its level's plan frame: a straight stair's segments, a curved or spiral stair's turning circle. */ +export function stairFootprintPolygons(nodes: SceneNodes, stair: StairNode): Vec2[][] { + if (stair.stairType === 'curved' || stair.stairType === 'spiral') { + const radius = Math.max(0.05, stair.innerRadius ?? 0.9) + Math.max(stair.width ?? 1, 0.4) + return [ + Array.from({ length: 24 }).map((_, index) => { + const angle = (index / 24) * Math.PI * 2 + return toWorldPlanPoint(stair, Math.cos(angle) * radius, Math.sin(angle) * radius) + }), + ] + } + + const segments = (stair.children ?? []) + .map((childId) => nodes[childId]) + .filter((node): node is AnyNode & { type: 'stair-segment' } => node?.type === 'stair-segment') + const usableSegments = + segments.length > 0 + ? segments + : [ + { + width: stair.width ?? 1, + length: 3, + height: resolveStairTotalRise(stair, nodes as Record), + stepCount: stair.stepCount ?? 10, + attachmentSide: 'front' as const, + }, + ] + const transforms = computeSegmentTransforms(usableSegments) + + return usableSegments.map((segment, index) => { + const transform = transforms[index] ?? { + position: [0, 0, 0] as [number, number, number], + rotation: 0, + } + const halfWidth = segment.width / 2 + const corners: Vec2[] = [ + [-halfWidth, 0], + [halfWidth, 0], + [halfWidth, segment.length], + [-halfWidth, segment.length], + ] + return corners.map(([localX, localZ]) => { + const [rx, rz] = rotateXZ(localX, localZ, transform.rotation) + return toWorldPlanPoint(stair, transform.position[0] + rx, transform.position[2] + rz) + }) + }) +} diff --git a/packages/core/src/agent-operations/zone-coverage.test.ts b/packages/core/src/agent-operations/zone-coverage.test.ts new file mode 100644 index 0000000000..acc9ade5bf --- /dev/null +++ b/packages/core/src/agent-operations/zone-coverage.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, test } from 'bun:test' +import { WallNode, ZoneNode } from '../schema' +import { equivalentWidth, floorUnclaimedIssues, wallBodies } from './zone-coverage' + +const square: [number, number][] = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], +] +const zone = (polygon: [number, number][]) => + ZoneNode.parse({ id: 'zone_a', parentId: 'level_0', name: 'Hall', polygon, spaceRole: 'room' }) +const ask = (zones: ZoneNode[]) => + floorUnclaimedIssues({ + levelId: 'level_0', + levelName: 'Ground', + spaces: [{ polygon: square, wallIds: [] }], + zones, + stairs: [], + bodies: [], + }) + +describe('the width of a piece is the short side of the rectangle with its area and perimeter', () => { + test.each([ + ['a 16 cm x 1 m strip', 0.16, 1, 0.16], + ['a 45 cm x 2.9 m strip', 0.45, 2.9, 0.45], + ['a 3 m square', 3, 3, 3], + ])('%s', (_, w, l, expected) => { + expect(equivalentWidth(w * l, 2 * (w + l))).toBeCloseTo(expected, 6) + }) +}) + +describe('a boolean that fails is not a measurement', () => { + test('a zone with a corner that is not a number leaves the level unmeasured, not the whole space unclaimed', () => { + const broken = { ...zone(square), polygon: [[Number.NaN, 0], ...square.slice(1)] } as ZoneNode + expect( + ask([ + zone([ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ]), + broken, + ]), + ).toEqual([]) + }) + + test('the same space with a sound zone over half of it is measured', () => { + expect( + ask([ + zone([ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ]), + ]), + ).toHaveLength(1) + }) + + test('walls whose footprints cannot be read have no bodies to take out: the level is not measured', () => { + const wall = { + ...WallNode.parse({ id: 'wall_a', parentId: 'level_0', start: [0, 0], end: [4, 0] }), + start: [Number.NaN, 0], + } + expect(wallBodies([wall as WallNode])).toBeNull() + expect(wallBodies([])).toEqual([]) + }) +}) diff --git a/packages/core/src/agent-operations/zone-coverage.ts b/packages/core/src/agent-operations/zone-coverage.ts new file mode 100644 index 0000000000..5cf631708a --- /dev/null +++ b/packages/core/src/agent-operations/zone-coverage.ts @@ -0,0 +1,292 @@ +import { + area as areaOf, + containsPoint, + difference, + distanceToBoundary, + intersection, + type MultiPolygon, + type Polygon, + type PolygonInput, + type Ring, + union, +} from '../lib/polygon-boolean' +import { polygonInteriorPoint } from '../lib/polygon-label' +import type { WallNode, ZoneNode } from '../schema' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' + +/** + * Do a level's zones tile the floor its walls enclose? Two findings, both measured on the clear floor (the wall bodies are not + * floor, so a zone drawn on a wall's centre line or on its face is the same): + * + * - `zones_overlap`: two rooms of the house that both lie on the same clear floor, by `ZONE_OVERLAP_MIN_M2` or more, at least + * `COVERAGE_MIN_WIDTH_M` wide. A pair of rooms that `space_many_rooms` already names (both lie in one enclosed space) is not + * reported again. + * - `floor_unclaimed`: floor inside a space the walls enclose that no zone and no stair claims, by `FLOOR_UNCLAIMED_MIN_M2` or + * more, at least `COVERAGE_MIN_WIDTH_M` wide. A space no zone covers past half is `space_no_room`, not repeated here. Any zone + * claims the floor it lies on (a room, an alfresco, a void, an analysis area), and a stair claims the floor under it. + * + * "At least 15 cm wide" is an opening: what is left when every point within 7.5 cm of the region's edge is taken out and the rest + * grown back, so a gap under 15 cm, or a hairline along a wall that joins a real gap, does not count. The width said is the short + * side of the rectangle with the piece's area and perimeter. All three tolerances are said in the message. + * + * A boolean that fails reads as an empty region (`polygon-boolean` swallows the error), which here would mean "nothing is claimed"; + * when what should be claimed is not empty and its union is, the level is not measured and says nothing. + */ +export const ZONE_OVERLAP_MIN_M2 = 0.1 +export const FLOOR_UNCLAIMED_MIN_M2 = 0.3 +export const COVERAGE_MIN_WIDTH_M = 0.15 +/** A zone's nearest neighbours are named within this distance, m. */ +const NEAR_M = 0.3 + +type Zone = ZoneNode +type Wall = WallNode +type Place = [number, number] + +export type ZonesOverlapIssue = { + type: 'zones_overlap' + message: string + severity: 'warning' + levelId: string + zoneIds: string[] + nodeIds: string[] + at: Place + /** m² */ + area: number + /** m, the short side of the rectangle with the piece's area and perimeter */ + width: number +} + +export type FloorUnclaimedIssue = { + type: 'floor_unclaimed' + message: string + severity: 'warning' + levelId: string + /** The zones within 30 cm of the unclaimed floor, nearest first. */ + zoneIds: string[] + wallIds: string[] + nodeIds: string[] + at: Place + /** m² */ + area: number + /** m, the short side of the rectangle with the piece's area and perimeter */ + width: number +} + +const round2 = (value: number) => Math.round(value * 100) / 100 + +function perimeter(polygon: Polygon): number { + return [polygon.outer, ...polygon.holes].reduce( + (sum, ring) => + sum + + ring.reduce((length, point, i) => { + const next = ring[(i + 1) % ring.length]! + return length + Math.hypot(next[0] - point[0], next[1] - point[1]) + }, 0), + 0, + ) +} + +/** The short side of the rectangle with this area and perimeter: exact for a rectangle, a quarter of the perimeter for a fat shape. */ +export function equivalentWidth(areaM2: number, perimeterM: number): number { + return (perimeterM - Math.sqrt(Math.max(0, perimeterM * perimeterM - 16 * areaM2))) / 4 +} + +/** A union, or null when it failed: non-empty input whose union is empty. */ +function unionOrNull(inputs: readonly PolygonInput[]): MultiPolygon | null { + const parts = inputs.flatMap((input) => + !Array.isArray(input) + ? [input] + : Array.isArray(input[0]) + ? [{ outer: input as Ring, holes: [] }] + : (input as MultiPolygon), + ) + if (!parts.length) return [] + const joined = union(parts) + return joined.length ? joined : null +} + +/** The rectangles of half-width `r` along each edge of the rings, a little past each end: what is within `r` of the region's edge. */ +function edgeBands(rings: readonly Ring[], r: number): Ring[] { + return rings.flatMap((ring) => + ring.flatMap((a, i) => { + const b = ring[(i + 1) % ring.length]! + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + if (length < 1e-6) return [] + const ux = ((b[0] - a[0]) / length) * r + const uz = ((b[1] - a[1]) / length) * r + return [ + [ + [a[0] - ux - uz, a[1] - uz + ux], + [b[0] + ux - uz, b[1] + uz + ux], + [b[0] + ux + uz, b[1] + uz - ux], + [a[0] - ux + uz, a[1] - uz - ux], + ] as Ring, + ] + }), + ) +} + +/** + * The part of a piece that is wide enough: its edge taken in by `COVERAGE_MIN_WIDTH_M / 2` on every side, then given back where + * something is left. Nothing if a boolean fails on the way. + */ +function wideEnough(piece: Polygon): MultiPolygon { + const r = COVERAGE_MIN_WIDTH_M / 2 + const rims = unionOrNull(edgeBands([piece.outer, ...piece.holes], r)) + if (!rims) return [] + const core = difference(piece, rims) + if (!core.length) return [] + const back = unionOrNull([ + ...core, + ...edgeBands( + core.flatMap((p) => [p.outer, ...p.holes]), + r, + ), + ]) + return back ? intersection(back, piece) : [] +} + +/** The pieces of a region at least `COVERAGE_MIN_WIDTH_M` wide and `minM2` big, each with its area and width. */ +function strips(region: MultiPolygon, minM2: number) { + return region + .flatMap((piece) => wideEnough(piece)) + .flatMap((piece) => { + const area = areaOf([piece]) + const width = equivalentWidth(area, perimeter(piece)) + return area >= minM2 && width >= COVERAGE_MIN_WIDTH_M - 1e-6 ? [{ piece, area, width }] : [] + }) +} + +/** + * The wall bodies of a level as one region: where there is wall there is no floor. Detected spaces run to the walls' centre lines, so + * both rules take them out. Null when the walls have footprints and their union failed. + */ +export function wallBodies(walls: readonly Wall[]): MultiPolygon | null { + const miters = calculateLevelMiters([...walls]) + const rings = walls.flatMap((wall) => { + const points = getWallPlanFootprint(wall, miters) + return points.length >= 3 ? [points.map((point) => [point.x, point.y] as [number, number])] : [] + }) + return unionOrNull(rings) +} + +const shapeOf = (zone: Pick): Polygon => ({ + outer: zone.polygon as Ring, + holes: (zone.holes ?? []) as Ring[], +}) + +const where = (piece: Polygon): Place => { + const [x, z] = polygonInteriorPoint({ polygon: piece.outer, holes: piece.holes }, true) + return [round2(x), round2(z)] +} + +/** "a strip 0.45 m wide", or for a shape as fat as it is long "a region about 3 m across". */ +function shapeWords(area: number, width: number): string { + return area / width >= 2 * width + ? `a strip ${round2(width)} m wide` + : `a region about ${round2(width)} m across` +} + +const RULE_TAIL = (minM2: number) => + `(not reported under ${minM2} m² or narrower than ${Math.round(COVERAGE_MIN_WIDTH_M * 100)} cm; wall bodies are not floor)` + +/** Pairs of rooms that lie on the same clear floor. `skip(a, b)` leaves a pair out (rooms of one space, which space_many_rooms names). */ +export function zonesOverlapIssues(input: { + levelId: string + levelName: string + rooms: readonly Zone[] + bodies: MultiPolygon + skip?: (a: Zone, b: Zone) => boolean +}): ZonesOverlapIssue[] { + const { levelId, levelName, rooms, bodies, skip } = input + const issues: ZonesOverlapIssue[] = [] + if (rooms.length < 2) return issues + for (let i = 0; i < rooms.length; i++) { + for (let j = i + 1; j < rooms.length; j++) { + const a = rooms[i]! + const b = rooms[j]! + if (skip?.(a, b)) continue + const shared = intersection(shapeOf(a), shapeOf(b)) + if (!shared.length) continue + const clear = bodies.length ? difference(shared, bodies) : shared + for (const strip of strips(clear, ZONE_OVERLAP_MIN_M2)) { + const at = where(strip.piece) + issues.push({ + type: 'zones_overlap', + message: `On ${levelName}, "${a.name || a.id}" and "${b.name || b.id}" overlap on ${round2(strip.area)} m² of floor (${shapeWords(strip.area, strip.width)}) around (${at[0]}, ${at[1]}) ${RULE_TAIL(ZONE_OVERLAP_MIN_M2)}.`, + severity: 'warning', + levelId, + zoneIds: [a.id, b.id], + nodeIds: [a.id, b.id], + at, + area: round2(strip.area), + width: round2(strip.width), + }) + } + } + } + return issues +} + +/** How far a zone lies from a piece, m: 0 when a vertex or the piece's place is inside it. */ +function distanceTo(zone: Zone, samples: readonly Place[]): number { + const shape = [shapeOf(zone)] + return Math.min( + ...samples.map((point) => (containsPoint(shape, point) ? 0 : distanceToBoundary(shape, point))), + ) +} + +/** Floor inside the given spaces that no zone and no stair claims and no wall stands on. */ +export function floorUnclaimedIssues(input: { + levelId: string + levelName: string + /** The spaces to look in: the ones the walls enclose and the zones cover past half. */ + spaces: readonly { polygon: Ring; holes?: Ring[]; wallIds: string[] }[] + zones: readonly Zone[] + stairs: readonly Ring[] + bodies: MultiPolygon +}): FloorUnclaimedIssue[] { + const { levelId, levelName, spaces, zones, stairs, bodies } = input + const placed = zones.filter((zone) => zone.polygon.length >= 3) + const claimed = unionOrNull([ + ...placed.map((zone) => shapeOf(zone)), + ...stairs.filter((ring) => ring.length >= 3).map((ring) => ({ outer: ring, holes: [] })), + ...bodies, + ]) + if (!claimed) return [] + const issues: FloorUnclaimedIssue[] = [] + for (const space of spaces) { + const whole: Polygon = { outer: space.polygon, holes: space.holes ?? [] } + const left = claimed.length ? difference(whole, claimed) : [whole] + for (const strip of strips(left, FLOOR_UNCLAIMED_MIN_M2)) { + const at = where(strip.piece) + const samples: Place[] = [at, ...strip.piece.outer] + const near = placed + .map((zone) => ({ zone, distance: distanceTo(zone, samples) })) + .filter((x) => x.distance <= NEAR_M) + .sort((x, y) => x.distance - y.distance) + .map((x) => x.zone) + const zoneIds = near.map((zone) => zone.id) + issues.push({ + type: 'floor_unclaimed', + message: `On ${levelName}, ${round2(strip.area)} m² of floor inside the walls (${shapeWords(strip.area, strip.width)}) around (${at[0]}, ${at[1]}) is claimed by no zone or stair${ + near.length + ? `; nearest ${near + .slice(0, 3) + .map((zone) => `"${zone.name || zone.id}"`) + .join(', ')}` + : '' + } ${RULE_TAIL(FLOOR_UNCLAIMED_MIN_M2)}.`, + severity: 'warning', + levelId, + zoneIds, + wallIds: space.wallIds, + nodeIds: [...zoneIds, ...space.wallIds], + at, + area: round2(strip.area), + width: round2(strip.width), + }) + } + } + return issues +} diff --git a/packages/core/src/agent-tools/verify-scene.ts b/packages/core/src/agent-tools/verify-scene.ts index 993d1898fc..35a1a9e203 100644 --- a/packages/core/src/agent-tools/verify-scene.ts +++ b/packages/core/src/agent-tools/verify-scene.ts @@ -16,7 +16,7 @@ export function extendVerifyScene(extension: { } const DESCRIPTION = - 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' + 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), two rooms on the same clear floor (zones_overlap) and floor inside a covered space that no zone or stair claims (floor_unclaimed), both warnings with their area, width and place and quiet under 0.1 m² (overlap), 0.3 m² (unclaimed) or 15 cm wide, wall bodies not counting as floor, an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' export const verifySceneTool = { name: 'verify_scene', From 396962163ea95453a89656488a6a0fd479f14551 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 16:47:32 +0100 Subject: [PATCH 03/40] set_code_profile: which building code a project follows The usage and design checks read a code table (US IRC 2021, Australian NCC, French) and a scene that names none has no jurisdiction. set_code_profile writes the project's profile on its site, the one place it lives, with the rest of the site's metadata kept; null clears it, saying what is already said changes nothing, and a scene with no site or two sites refuses. The shared operation and contract, the MCP tool (destructive hint: it replaces the profile), its README row, guide line and annotation justification, five shared case rows read by the core, MCP and chat runners, and the metadata key's classification. Co-Authored-By: Claude Sonnet 5.5 --- .../agent-operations/__fixtures__/cases.ts | 2 + .../__fixtures__/site-cases.ts | 46 +++ packages/core/src/agent-operations/index.ts | 3 + .../agent-operations/set-code-profile.test.ts | 43 ++ .../src/agent-operations/set-code-profile.ts | 52 +++ packages/core/src/agent-tools/index.ts | 3 + .../core/src/agent-tools/set-code-profile.ts | 25 ++ .../core/src/building/code-profile.test.ts | 88 ++++ packages/core/src/building/code-profile.ts | 377 ++++++++++++++++++ .../core/src/contracts/reference-inventory.ts | 4 + packages/mcp/README.md | 1 + packages/mcp/src/resources/agent-guide.ts | 1 + .../src/tools/read-tool-annotations.test.ts | 1 + packages/mcp/src/tools/shared-tools.ts | 8 + .../tool-annotation-justifications.json | 13 + 15 files changed, 667 insertions(+) create mode 100644 packages/core/src/agent-operations/set-code-profile.test.ts create mode 100644 packages/core/src/agent-operations/set-code-profile.ts create mode 100644 packages/core/src/agent-tools/set-code-profile.ts create mode 100644 packages/core/src/building/code-profile.test.ts create mode 100644 packages/core/src/building/code-profile.ts diff --git a/packages/core/src/agent-operations/__fixtures__/cases.ts b/packages/core/src/agent-operations/__fixtures__/cases.ts index 1ea366fe3a..2539db18e6 100644 --- a/packages/core/src/agent-operations/__fixtures__/cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/cases.ts @@ -39,6 +39,7 @@ import { GET_SITE_CASES, PLACE_BUILDING_CASES, SITE_LINE_CASES, + SET_CODE_PROFILE_CASES, SITE_VERIFY_CASES, } from './site-cases' import { @@ -995,6 +996,7 @@ export const AGENT_TOOL_CASES: readonly AgentToolCase[] = [ ...PLACE_BUILDING_CASES, ...SITE_LINE_CASES, ...SITE_VERIFY_CASES, + ...SET_CODE_PROFILE_CASES, ...FINISH_CASES, ...UNIT_CASES, ] diff --git a/packages/core/src/agent-operations/__fixtures__/site-cases.ts b/packages/core/src/agent-operations/__fixtures__/site-cases.ts index 7832a3b9cc..79c31b0401 100644 --- a/packages/core/src/agent-operations/__fixtures__/site-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/site-cases.ts @@ -937,3 +937,49 @@ export const SITE_VERIFY_CASES: AgentToolCase[] = [ }, }, ] + +export const SET_CODE_PROFILE_CASES: AgentToolCase[] = [ + { + name: 'a project that names a code gets it on the site, the rest of the site metadata kept', + tool: 'set_code_profile', + scene: () => scene(site({ metadata: { codeOverrides: { state: 'FL' } } })), + input: { profile: 'irc-2021' }, + expect: { + result: { siteId: 'site_lot', profile: 'irc-2021', previous: null, unchanged: false }, + after: { site_lot: { metadata: { codeProfile: 'irc-2021', codeOverrides: { state: 'FL' } } } }, + mentions: ['US IRC 2021'], + }, + }, + { + name: 'null clears it: the key goes, the rest stays', + tool: 'set_code_profile', + scene: () => scene(site({ metadata: { codeProfile: 'irc-2021', codeOverrides: { state: 'FL' } } })), + input: { profile: null }, + expect: { + result: { profile: null, previous: 'irc-2021', unchanged: false }, + after: { site_lot: { metadata: { codeOverrides: { state: 'FL' } } } }, + mentions: ['names no code'], + }, + }, + { + name: 'saying what is already said changes nothing', + tool: 'set_code_profile', + scene: () => scene(site({ metadata: { codeProfile: 'au-ncc' } })), + input: { profile: 'au-ncc' }, + expect: { result: { profile: 'au-ncc', unchanged: true }, mentions: ['only the values read in its own texts'] }, + }, + { + name: 'a scene with no site has nowhere to put it', + tool: 'set_code_profile', + scene: () => ({ nodes: {}, rootNodeIds: [] }), + input: { profile: 'irc-2021' }, + expect: { refusal: 'no_site' }, + }, + { + name: 'two sites leave it ambiguous', + tool: 'set_code_profile', + scene: () => scene(site(), SiteNode.parse({ id: 'site_other', children: [] })), + input: { profile: 'irc-2021' }, + expect: { refusal: 'ambiguous_site' }, + }, +] diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index 62d42aa341..b75fac5f96 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -28,6 +28,7 @@ import { ROOM_OPERATIONS } from './room-structure' import { searchAssets } from './search-assets' import { searchMaterials } from './search-materials' import { setCheckpoint } from './set-checkpoint' +import { setCodeProfile } from './set-code-profile' import { setGroundLevel } from './set-ground-level' import { getSite, placeBuilding } from './site' import { fitStair, measureStairOperation } from './stairs' @@ -85,6 +86,7 @@ export * from './scene-queries' export * from './scene-view' export * from './search-assets' export * from './search-materials' +export * from './set-code-profile' export * from './site' export * from './slab-surface-script' export * from './stairs' @@ -111,6 +113,7 @@ const SINGLE_OPERATIONS = { validate_design: validateDesignOperation, place_design: gatedByBrief('place_design', placeDesign), set_checkpoint: setCheckpoint, + set_code_profile: setCodeProfile, design_brief: designBrief, add_wall: addWall, set_wall_type: setWallType, diff --git a/packages/core/src/agent-operations/set-code-profile.test.ts b/packages/core/src/agent-operations/set-code-profile.test.ts new file mode 100644 index 0000000000..300a3333dd --- /dev/null +++ b/packages/core/src/agent-operations/set-code-profile.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from 'bun:test' +import { AgentRefusal } from '../agent-tools/refusal' +import { codeProfileOf } from '../building/code-profile' +import { SiteNode } from '../schema' +import { setCodeProfile } from './set-code-profile' + +const ctx = { activeLevelId: null } +const sites = (metadata?: Record) => + ({ + site_1: SiteNode.parse({ id: 'site_1', children: [], ...(metadata ? { metadata } : {}) }), + }) as never + +describe('set_code_profile', () => { + test('a profile that is not one is refused when it bypasses the contract', () => { + try { + setCodeProfile(sites(), { profile: 'ncc' } as never, ctx) + throw new Error('not refused') + } catch (error) { + expect(error).toBeInstanceOf(AgentRefusal) + expect((error as AgentRefusal).code).toBe('invalid_input') + } + }) + + test('set, read back by the checks, and cleared', () => { + const nodes = sites({ keep: 1 }) + const set = setCodeProfile(nodes, { profile: 'irc-2021' }, ctx) + const written = { site_1: { ...nodes.site_1, ...set.changes!.update![0]!.data } } as never + expect(codeProfileOf(written)?.id).toBe('irc-2021') + expect((written as Record).site_1!.metadata).toEqual({ + keep: 1, + codeProfile: 'irc-2021', + }) + const cleared = setCodeProfile(written, { profile: null }, ctx) + const after = { + site_1: { + ...(written as Record).site_1, + ...cleared.changes!.update![0]!.data, + }, + } as never + expect(codeProfileOf(after)).toBeNull() + expect((after as Record).site_1!.metadata).toEqual({ keep: 1 }) + }) +}) diff --git a/packages/core/src/agent-operations/set-code-profile.ts b/packages/core/src/agent-operations/set-code-profile.ts new file mode 100644 index 0000000000..6fb8ad03ef --- /dev/null +++ b/packages/core/src/agent-operations/set-code-profile.ts @@ -0,0 +1,52 @@ +import { z } from 'zod' +import { refuse } from '../agent-tools/refusal' +import { setCodeProfileTool } from '../agent-tools/set-code-profile' +import { + CODE_PROFILE_KEY, + CODE_PROFILES, + type CodeProfileId, + codeProfileOf, +} from '../building/code-profile' +import type { SiteNode } from '../schema' +import { queryNodes } from './scene-queries' +import type { AgentOperation } from './types' + +const inputSchema = z.strictObject(setCodeProfileTool.input) + +function siteOf(nodes: Parameters>[0]): SiteNode { + const sites = queryNodes(nodes, { type: 'site' }) + if (!sites.length) refuse('no_site', 'The scene has no site to hold the code profile.') + if (sites.length > 1) + refuse( + 'ambiguous_site', + 'The scene has more than one site; which one names the code is ambiguous.', + ) + return sites[0]! +} + +const effect = (profile: CodeProfileId | null) => + profile === null + ? 'The project names no code: the checks that apply a code report information that names the US IRC they used.' + : CODE_PROFILES[profile].id === 'irc-2021' + ? 'The project follows the US IRC 2021: the checks that apply a code report warnings.' + : `The project follows ${CODE_PROFILES[profile].label}, which holds only the values read in its own texts: a check that has no value for it reports nothing.` + +/** + * `set_code_profile`: the one place `site.metadata.codeProfile` is written (the agent tool, the MCP + * tool, the site panel and Architect Pro's `code_basis_set` all call it). The rest of the site's + * metadata is kept; clearing removes the key. + */ +export const setCodeProfile: AgentOperation> = (nodes, input) => { + const parsed = inputSchema.safeParse(input) + if (!parsed.success) refuse('invalid_input', parsed.error.message) + const site = siteOf(nodes) + const profile = parsed.data.profile + const previous = codeProfileOf({ [site.id]: site })?.id ?? null + const message = effect(profile) + const result = { siteId: site.id, profile, previous, unchanged: previous === profile, message } + if (previous === profile) return { result } + const metadata: Record = { ...site.metadata } + if (profile === null) delete metadata[CODE_PROFILE_KEY] + else metadata[CODE_PROFILE_KEY] = profile + return { result, changes: { update: [{ id: site.id, data: { metadata } }] } } +} diff --git a/packages/core/src/agent-tools/index.ts b/packages/core/src/agent-tools/index.ts index 4d72e69160..8c426da779 100644 --- a/packages/core/src/agent-tools/index.ts +++ b/packages/core/src/agent-tools/index.ts @@ -31,6 +31,7 @@ import { placeItemsTool } from './place-items' import { createRoofTool, moveRoofsToRoofLevelTool } from './roofs' import { ROOM_TOOL_CONTRACTS } from './room-structure' import { searchMaterialsTool } from './search-materials' +import { setCodeProfileTool } from './set-code-profile' import { getSiteTool, placeBuildingTool } from './site' import { createStairTool, fitStairTool, measureStairTool } from './stairs' import { UNIT_TOOL_CONTRACTS } from './units' @@ -67,6 +68,7 @@ export * from './retired' export * from './roofs' export * from './room-structure' export * from './search-materials' +export * from './set-code-profile' export * from './site' export { CATALOG_SOURCE, OTHER_SOURCES, OUTSIDE_SOURCES } from './sources' export * from './stairs' @@ -100,6 +102,7 @@ export const AGENT_TOOL_CONTRACTS = [ designBriefTool, placeDesignTool, validateDesignTool, + setCodeProfileTool, addWallTool, setWallTypeTool, addFenceTool, diff --git a/packages/core/src/agent-tools/set-code-profile.ts b/packages/core/src/agent-tools/set-code-profile.ts new file mode 100644 index 0000000000..8764ddcddf --- /dev/null +++ b/packages/core/src/agent-tools/set-code-profile.ts @@ -0,0 +1,25 @@ +import { z } from 'zod' +import { CODE_PROFILE_IDS } from '../building/code-profile' + +export const setCodeProfileTool = { + name: 'set_code_profile', + title: 'Set code profile', + description: + 'Say which building code the project follows: irc-2021 (the US IRC 2021), au-ncc (the Australian NCC) or fr (the French regulations); null clears it. A project that names no code has none: nothing is guessed from an address. ' + + 'The checks that apply a code (bathroom clearances) read it: with irc-2021 they are warnings, with no code they are information that names the US IRC they used, and au-ncc and fr hold only the values read in their own texts (stairs, ceiling heights), none of which those checks use yet, so they report nothing. ' + + 'Stored as site.metadata.codeProfile. Refusals: no_site, ambiguous_site, invalid_input. One undo step.', + input: { + profile: z + .enum(CODE_PROFILE_IDS) + .nullable() + .describe('The code: irc-2021, au-ncc or fr. null: the project names no code.'), + }, +} + +export const codeProfileOutput = { + siteId: z.string(), + profile: z.enum(CODE_PROFILE_IDS).nullable(), + previous: z.enum(CODE_PROFILE_IDS).nullable(), + unchanged: z.boolean(), + message: z.string(), +} diff --git a/packages/core/src/building/code-profile.test.ts b/packages/core/src/building/code-profile.test.ts new file mode 100644 index 0000000000..25d5a8f08f --- /dev/null +++ b/packages/core/src/building/code-profile.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, test } from 'bun:test' +import { + CODE_PROFILE_IDS, + CODE_PROFILES, + codeProfileOf, + FR_2015, + IRC_2021, + ircValue, + NCC_2022, + thresholdOf, +} from './code-profile' + +describe('the code profile table', () => { + test('every IRC row says its section, its citation and whether its text was read', () => { + for (const [id, row] of Object.entries(IRC_2021)) { + expect([id, row.section]).toEqual([id, expect.stringMatching(/^IRC R\d/)]) + expect(row.cite.length).toBeGreaterThan(20) + expect(['code text', 'secondary source']).toContain(row.source) + expect(row.value).toBeGreaterThan(0) + } + }) + + test('the bathroom clearances and the shower figure are marked as secondary sources: their text was not read', () => { + for (const id of [ + 'toiletSideClear', + 'toiletFrontClear', + 'lavatorySideClear', + 'lavatoryFrontClear', + 'showerFrontClear', + ] as const) + expect(IRC_2021[id].source).toBe('secondary source') + expect(IRC_2021.stairHeadroom).toMatchObject({ source: 'code text', value: 80 * 0.0254 }) + }) + + test('the Australian and French profiles hold only the rows read in their own texts, each cited', () => { + expect(CODE_PROFILE_IDS).toEqual(['irc-2021', 'au-ncc', 'fr']) + expect(CODE_PROFILES['au-ncc'].thresholds).toBe(NCC_2022) + expect(CODE_PROFILES.fr.thresholds).toBe(FR_2015) + for (const [rows, section] of [ + [NCC_2022, /^NCC 2022 HP /], + [FR_2015, /^arrêté du 24 décembre 2015 art\. 1\d/], + ] as const) + for (const [id, row] of Object.entries(rows)) { + expect([id, row.section]).toEqual([id, expect.stringMatching(section)]) + expect(row.cite.length).toBeGreaterThan(40) + expect(row.source).toBe('code text') + expect(row.value).toBeGreaterThan(0) + } + // what their texts do not set has no row: a check that needs one reports nothing + for (const id of ['toiletFrontClear', 'doorThresholdDrop', 'habitableRoomArea'] as const) { + expect(thresholdOf(CODE_PROFILES['au-ncc'], id)).toBeUndefined() + expect(thresholdOf(CODE_PROFILES.fr, id)).toBeUndefined() + } + // the same id, a different applicability: the IRC landing is at every exterior door, the NCC's only over a drop + expect(IRC_2021.exteriorDoorLanding.appliesWhen).toBe('every-exterior-door') + expect(NCC_2022.exteriorDoorLanding.appliesWhen).toEqual({ dropOverM: 0.57, risersOver: 3 }) + expect( + Object.entries({ ...IRC_2021, ...NCC_2022, ...FR_2015 }) + .filter(([, row]) => 'appliesWhen' in row) + .map(([id]) => id), + ).toEqual(['exteriorDoorLanding']) + expect(NCC_2022.riserMax.value).toBe(0.19) + expect(NCC_2022.stairLanding.value).toBe(0.75) + expect(FR_2015.stairWidth.value).toBe(0.8) + expect(FR_2015.riserMax.value).toBe(0.18) + expect(thresholdOf(CODE_PROFILES['irc-2021'], 'toiletFrontClear')?.value).toBe( + ircValue('toiletFrontClear'), + ) + }) +}) + +describe('the jurisdiction of a scene', () => { + const site = (metadata?: unknown) => ({ site_1: { type: 'site', metadata } }) + + test('a scene that does not name a code has none: nothing is guessed from an address or a state', () => { + expect(codeProfileOf({})).toBeNull() + expect(codeProfileOf(site({}))).toBeNull() + expect(codeProfileOf(site({ codeOverrides: { state: 'WA' } }))).toBeNull() + expect(codeProfileOf(site({ codeProfile: 'ncc' }))).toBeNull() + expect(codeProfileOf(site({ codeProfile: 42 }))).toBeNull() + }) + + test('site.metadata.codeProfile names it', () => { + expect(codeProfileOf(site({ codeProfile: 'irc-2021' }))?.id).toBe('irc-2021') + expect(codeProfileOf(site({ codeProfile: 'au-ncc' }))?.id).toBe('au-ncc') + expect(codeProfileOf(site({ codeProfile: 'fr' }))?.id).toBe('fr') + }) +}) diff --git a/packages/core/src/building/code-profile.ts b/packages/core/src/building/code-profile.ts new file mode 100644 index 0000000000..0ae89341b6 --- /dev/null +++ b/packages/core/src/building/code-profile.ts @@ -0,0 +1,377 @@ +/** + * The thresholds a building code sets, one table, every row with its unit, its citation and whether the + * text behind it was read. A check that applies a code reads its numbers here, never from a literal. + * + * Which code applies is the project's to say: `site.metadata.codeProfile`. A scene that does not say has + * no jurisdiction, and a code-specific check then reports information that names the code it used, never + * a warning (the listing houses are Australian designs; the US IRC is not what they were drawn to). The + * profiles for Australia (NCC, ABCB Housing Provisions) and France hold only the rows read in their own + * texts (below); a check that has no row for the code reports nothing. These are usage indicators, not a + * compliance check. + */ + +export const CODE_PROFILE_IDS = ['irc-2021', 'au-ncc', 'fr'] as const +export type CodeProfileId = (typeof CODE_PROFILE_IDS)[number] + +/** The text the number was read in (a state's adoption of the model code, or UpCodes), or only a guide, a forum or another checker's constant. */ +export type ThresholdSource = 'code text' | 'secondary source' + +/** + * When a row applies, for a rule that is not for every case. A row without it applies wherever the check that + * reads it looks; a check that reads a row with it evaluates it. `every-exterior-door` is a landing at each + * exterior door; `{ dropOverM, risersOver }` is a doorway whose sill opens onto a stairway or ramp with a + * change in level of more than that many metres or risers (either is enough: the text reads "greater than + * 3 risers or 570 mm"). + */ +export type Applicability = 'every-exterior-door' | { dropOverM: number; risersOver: number } + +export type Threshold = { + value: number + unit: 'm' | 'm2' | 'ratio' + /** The section as a finding names it. */ + section: string + /** The section and, where it matters, the edition and where it was read. */ + cite: string + appliesWhen?: Applicability + source: ThresholdSource +} + +const inches = (n: number) => n * 0.0254 +const feet = (n: number) => n * 0.3048 + +const R311_READ = 'read in the Minnesota (2020) and Colorado (2021) residential codes' + +/** The US International Residential Code, 2021. */ +export const IRC_2021 = { + stairWidth: { + value: inches(36), + unit: 'm', + section: 'IRC R311.7.1', + cite: `IRC R311.7.1, stairway clear width above the handrail (${R311_READ})`, + source: 'code text', + }, + handrailProjection: { + value: inches(4.5), + unit: 'm', + section: 'IRC R311.7.1', + cite: `IRC R311.7.1, a handrail projects at most this far into the stairway (${R311_READ})`, + source: 'code text', + }, + stairHeadroom: { + value: inches(80), + unit: 'm', + section: 'IRC R311.7.2', + cite: `IRC R311.7.2, 6 ft 8 in from the line of the nosings (${R311_READ})`, + source: 'code text', + }, + stairLanding: { + value: inches(36), + unit: 'm', + section: 'IRC R311.7.6', + cite: 'IRC R311.7.6, landing depth in the direction of travel on a straight run (read in the Colorado 2021 residential code)', + source: 'code text', + }, + riserMax: { + value: inches(7.75), + unit: 'm', + section: 'IRC R311.7.5.1', + cite: 'IRC R311.7.5.1 riser height, as the Architect checker holds it; the section text was not read', + source: 'secondary source', + }, + treadMin: { + value: inches(10), + unit: 'm', + section: 'IRC R311.7.5.2', + cite: 'IRC R311.7.5.2 tread depth, as the Architect checker holds it; the section text was not read', + source: 'secondary source', + }, + hallWidth: { + value: inches(36), + unit: 'm', + section: 'IRC R311.6', + cite: 'IRC R311.6 hallway width, as the Architect checker holds it; the section text was not read', + source: 'secondary source', + }, + hallComfortable: { + value: inches(42), + unit: 'm', + section: 'IRC R311.6', + cite: 'a comfortable hallway, as the Architect checker holds it (not a code row)', + source: 'secondary source', + }, + exteriorDoorLanding: { + value: inches(36), + unit: 'm', + section: 'IRC R311.3', + cite: 'IRC R311.3, landing depth at an exterior door, as wide as the door (read in the Colorado 2021 residential code)', + appliesWhen: 'every-exterior-door', + source: 'code text', + }, + doorThresholdDrop: { + value: inches(1.5), + unit: 'm', + section: 'IRC R311.7.6 / R311.3', + cite: 'IRC R311.7.6 (no top landing for an interior flight only if no door swings over the stairs) and R311.3.1 / R311.3.2 (a landing or floor at an exterior door is at most 1-1/2 in below the threshold, or 7-3/4 in where the door does not swing over it); read in the Colorado 2021 residential code', + source: 'code text', + }, + habitableRoomArea: { + value: feet(70) * 0.3048, + unit: 'm2', + section: 'IRC R304.1', + cite: 'IRC R304.1, 70 sq ft (read in the Virginia 2021 residential code); kitchens are exempt', + source: 'code text', + }, + habitableRoomDimension: { + value: feet(7), + unit: 'm', + section: 'IRC R304.2', + cite: 'IRC R304.2, 7 ft in any horizontal dimension (read in the Virginia 2021 residential code); kitchens are exempt', + source: 'code text', + }, + ceilingHeight: { + value: feet(7), + unit: 'm', + section: 'IRC R305.1', + cite: 'IRC R305.1 (read in the Virginia 2021 residential code); a sloped ceiling needs half the floor at this height and none under 5 ft', + source: 'code text', + }, + egressArea: { + value: 0.53, + unit: 'm2', + section: 'IRC R310.2.1', + cite: 'IRC R310.2.1, net clear opening 5.7 sq ft, kept at the 0.53 m2 the Architect checker uses; sizes read in city and county guides summarising the 2021 numbering', + source: 'secondary source', + }, + egressSill: { + value: inches(44), + unit: 'm', + section: 'IRC R310.2.2', + cite: 'IRC R310.2.2 (2018 numbering, R310.2.3 in 2021), sill at most 44 in above the floor (read in the Texas 2018 residential code on UpCodes)', + source: 'code text', + }, + toiletSideClear: { + value: inches(15), + unit: 'm', + section: 'IRC R307.1 / P2705.1', + cite: 'IRC R307.1 / P2705.1 and Figure R307.1: 15 in from the centre to a side wall, partition or vanity. The section text sends to the figure and holds no number; the figure was not read: a 2009 P2705.1 quote and a 2021 training site', + source: 'secondary source', + }, + toiletFrontClear: { + value: inches(21), + unit: 'm', + section: 'IRC R307.1 / P2705.1', + cite: 'IRC R307.1 / P2705.1 and Figure R307.1: 21 in in front to any wall, fixture or door. The figure was not read: a 2009 P2705.1 quote and a 2021 training site', + source: 'secondary source', + }, + lavatorySideClear: { + value: inches(15), + unit: 'm', + section: 'IRC R307.1 / P2705.1', + cite: 'IRC R307.1 / P2705.1 and Figure R307.1, as for a water closet; the figure was not read', + source: 'secondary source', + }, + lavatoryFrontClear: { + value: inches(21), + unit: 'm', + section: 'IRC R307.1 / P2705.1', + cite: 'IRC R307.1 / P2705.1 and Figure R307.1, as for a water closet; the figure was not read', + source: 'secondary source', + }, + showerFrontClear: { + value: inches(24), + unit: 'm', + section: 'IRC R307.1 / P2705.1', + cite: "in front of the shower opening, from the team designer's list; not found in the IRC text or in a 2021 guide (a guide gives 24 in as the Uniform Plumbing Code figure for a water closet)", + source: 'secondary source', + }, +} as const satisfies Record + +const NCC_READ = 'read on ncc.abcb.gov.au, NCC 2022 ABCB Housing Provisions, 27 October 2026' + +/** + * The Australian National Construction Code, ABCB Housing Provisions (NCC 2022), the rows whose text was + * read there. The same ids as the IRC rows, where the rule is the same kind of rule; what the Housing + * Provisions do not set (a stair width, a hall width, a room area, an egress opening, the clearances at + * a toilet, a door that must not swing over stairs) has no row, and a check that needs one reports nothing. + */ +export const NCC_2022 = { + riserMax: { + value: 0.19, + unit: 'm', + section: 'NCC 2022 HP Table 11.2.2a', + cite: `NCC 2022 Housing Provisions Table 11.2.2a, riser at most 190 mm for a stair other than a spiral (115 mm at least; 225 mm for stairs serving rarely used non-habitable rooms, Table 11.2.2b); ${NCC_READ}`, + source: 'code text', + }, + treadMin: { + value: 0.24, + unit: 'm', + section: 'NCC 2022 HP Table 11.2.2a', + cite: `NCC 2022 Housing Provisions Table 11.2.2a, going at least 240 mm (355 mm at most; 2R+G between 550 and 700 mm; 215 mm for stairs serving rarely used non-habitable rooms, Table 11.2.2b); ${NCC_READ}`, + source: 'code text', + }, + stairLanding: { + value: 0.75, + unit: 'm', + section: 'NCC 2022 HP 11.2.5(1)(a)', + cite: `NCC 2022 Housing Provisions 11.2.5(1)(a), a landing at least 750 mm long (500 mm from the inside edge where it turns; 600 mm for a stair serving only rarely used non-habitable rooms, 11.2.5(2)); ${NCC_READ}`, + source: 'code text', + }, + exteriorDoorLanding: { + value: 0.75, + unit: 'm', + section: 'NCC 2022 HP 11.2.5(1)(a), (c), (d)', + cite: `NCC 2022 Housing Provisions 11.2.5(1)(a), (c), (d), a landing at least 750 mm long across the full width of a doorway whose sill opens onto a stairway or ramp with a change in level of more than 3 risers or 570 mm (a threshold more than 230 mm above the adjoining surface incorporates steps, 11.2.6); ${NCC_READ}`, + appliesWhen: { dropOverM: 0.57, risersOver: 3 }, + source: 'code text', + }, + stairHeadroom: { + value: 2, + unit: 'm', + section: 'NCC 2022 HP 10.3.1(1)(f)', + cite: `NCC 2022 Housing Provisions 10.3.1(1)(f), 2.0 m measured vertically above the nosing line of a stairway, ramp or landing; ${NCC_READ}`, + source: 'code text', + }, + ceilingHeight: { + value: 2.4, + unit: 'm', + section: 'NCC 2022 HP 10.3.1(1)(a)', + cite: `NCC 2022 Housing Provisions 10.3.1(1)(a), 2.4 m in a habitable room other than a kitchen (a kitchen, corridor, bathroom or laundry 2.1 m; a sloping ceiling over two thirds of the floor); ${NCC_READ}`, + source: 'code text', + }, +} as const satisfies Partial> + +const FR_READ = + "read on legifrance.gouv.fr (JORFTEXT000031692481), consolidated text in force on 27 October 2026, articles 11 and 12 unmodified since publication: the accessibility rules for new collective housing and individual houses; whom they bind is the decree's, not read here" + +/** + * France: the rows whose text was read in the arrêté du 24 décembre 2015 on the accessibility of new + * dwellings. Nothing here comes from a construction text that sets a room area or a ceiling height for a + * new dwelling (none was found in the national texts opened); the clear space beside a WC (0,80 x 1,30 m) + * is a space for a wheelchair in the unité de vie, not the IRC's centre-to-obstruction figure, so it has no row. + */ +export const FR_2015 = { + hallWidth: { + value: 0.9, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 11 II', + cite: `arrêté du 24 décembre 2015 art. 11, II: la largeur minimale des circulations intérieures est de 0,90 m (porte d'entrée 0,90 m nominal, 0,83 m de passage utile; portes intérieures 0,80 m nominal, 0,77 m utile); ${FR_READ}`, + source: 'code text', + }, + stairWidth: { + value: 0.8, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 12', + cite: `arrêté du 24 décembre 2015 art. 12: l'escalier d'un logement sur plusieurs niveaux a une largeur minimale de 0,80 m (mesurée à l'aplomb de la main courante si elle empiète de plus de 10 cm); ${FR_READ}`, + source: 'code text', + }, + riserMax: { + value: 0.18, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 12', + cite: `arrêté du 24 décembre 2015 art. 12: hauteur de marche inférieure ou égale à 18 cm; ${FR_READ}`, + source: 'code text', + }, + treadMin: { + value: 0.24, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 12', + cite: `arrêté du 24 décembre 2015 art. 12: largeur du giron supérieure ou égale à 24 cm; ${FR_READ}`, + source: 'code text', + }, +} as const satisfies Partial> + +/** + * Numbers the usage checks borrow for what a person can do in a house: a clear passage, a door, a turning + * space, the edge a cane finds. They are not a code row and apply to every project whatever its jurisdiction + * (a usage indicator, not a compliance check); each says where the number comes from. The French figures were + * checked against the arrêté du 24 décembre 2015 (Légifrance); the ADA figures are as the checks held them. + */ +export const USAGE_INDICATORS = { + passage: { + value: 0.9, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 11 II, 36 in', + cite: 'clear width of a path in a house: 0,90 m, the French arrêté du 24 décembre 2015 art. 11 II (consolidated text in force on 27 October 2026, Légifrance); 36 in is the IRC figure for a hall', + source: 'code text', + }, + doorClear: { + value: 0.8, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 11 II (0,77 m clear), 32 in', + cite: 'clear width through an interior door: 32 in (the US figure, not read); the French arrêté du 24 décembre 2015 art. 11 II (consolidated text in force on 27 October 2026, Légifrance) asks 0,80 m nominal and 0,77 m clear, which is why a doorway is read at 0.80 m here and a pinch under it is told apart from a passage', + source: 'secondary source', + }, + turning: { + value: 1.5, + unit: 'm', + section: 'arrêté du 24 décembre 2015 art. 13 and annexe 2; ADA 304.3', + cite: "wheelchair turning space, 1.50 m: an espace de manœuvre avec possibilité de demi-tour, Ø 1,50 m (annexe 2), in a bedroom and a salle d'eau, arrêté du 24 décembre 2015 art. 13 (consolidated text in force on 27 October 2026, Légifrance); ADA 304.3 not read", + source: 'code text', + }, + protrusionLimit: { + value: 0.1, + unit: 'm', + section: 'ADA 307.2, 4 in', + cite: 'nearer than this to the wall, an object is not an obstacle', + source: 'secondary source', + }, + protrusionLowest: { + value: 0.685, + unit: 'm', + section: 'ADA 307.2, 27 in', + cite: 'what a cane finds: a wall object whose lower edge is at or above this', + source: 'secondary source', + }, + protrusionHighest: { + value: 2.03, + unit: 'm', + section: 'ADA 307.2, 80 in', + cite: 'what a cane finds: a wall object whose lower edge is at or below this', + source: 'secondary source', + }, +} as const satisfies Record + +export type IrcThresholdId = keyof typeof IRC_2021 +export type ThresholdId = IrcThresholdId + +export type CodeProfile = { + id: CodeProfileId + label: string + thresholds: Readonly>> +} + +export const CODE_PROFILES: Readonly> = { + 'irc-2021': { id: 'irc-2021', label: 'the US IRC 2021', thresholds: IRC_2021 }, + 'au-ncc': { + id: 'au-ncc', + label: 'the Australian NCC (ABCB Housing Provisions)', + thresholds: NCC_2022, + }, + fr: { id: 'fr', label: 'the French regulations', thresholds: FR_2015 }, +} + +/** Where a project says which code applies: `site.metadata.codeProfile`. */ +export const CODE_PROFILE_KEY = 'codeProfile' + +type SiteLike = { type: string; metadata?: unknown } + +/** + * The profile the project names, or null: a scene that does not say has no jurisdiction. Nothing is + * guessed from an address, a state code (WA is a US and an Australian state) or the browser. + */ +export function codeProfileOf(nodes: Readonly>): CodeProfile | null { + for (const node of Object.values(nodes)) { + if (node.type !== 'site') continue + const named = (node.metadata as Record | undefined)?.[CODE_PROFILE_KEY] + if (typeof named === 'string' && (CODE_PROFILE_IDS as readonly string[]).includes(named)) + return CODE_PROFILES[named as CodeProfileId] + } + return null +} + +/** What a profile holds for a threshold, or undefined: a rule the other codes' texts do not set has no row. */ +export const thresholdOf = (profile: CodeProfile, id: ThresholdId): Threshold | undefined => + profile.thresholds[id] + +/** The IRC value of a threshold, for a checker that is a US checker by design (Architect Pro's `design_check`). */ +export const ircValue = (id: IrcThresholdId): number => IRC_2021[id].value diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index e5752c0b75..2e4fd0b123 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -1082,6 +1082,10 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ "The site's hand-set code facts (Bones' `codeOverrides`: state, county, wind, snow…): numbers, flags and place names. Core reads only its `state`, to tell a US site from another, and names no node.", ['codeOverrides'], ), + ...described( + 'Which building code the project follows (`irc-2021`, `au-ncc`, `fr`): a profile name, never a node id. Read by the code-specific usage checks; a scene that does not name one has no jurisdiction.', + ['codeProfile'], + ), ...described('Read as a truthy flag only; no editor writer.', [ 'arrayModifier', 'curvedWindowMaster', diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 3b336b036f..9b29247202 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -433,6 +433,7 @@ is a "pitch" fraction like `"1/4 pitch"`, which is rise over span. | `merge_windows` | Make two windows that exist one window, as the editor's Merge windows button does; nothing is recreated. On two walls that meet at a corner, each window within 0.30 m of it, they become one corner window (the `add_corner_window` result): each is slid to the corner keeping its width, the glass fused (a fixed window's; other types meet at a post), and both take the first window's height, sill and type, so name first the window whose look you want; the corner is refused over 170° or under 10°. On one wall, two windows with at most 0.30 m between them and nothing between become one window spanning both (overlapping or one inside the other, their union), from the lower sill to the higher head, with the first window's type and style. Use it for two windows already built that open a corner or one wide opening (`verify_scene`'s `corner_unjoined` names a pair for the first); `add_corner_window` builds a new pair. By hand: select two windows and use Merge windows in the multi-selection panel, or place or drag a window near a corner where one waits and click or release (Alt places it plain). | `{ windowIds: [a, b] }` | `{ kind: 'corner' \| 'same_wall', windowIds, removedIds, achieved }`; refusals `window_not_found`, `not_a_window`, `same_window`, `window_not_on_wall`, `window_already_joined` (unwrap it first), `windows_already_joined`, `windows_not_adjacent`, `opening_between`, `walls_not_meeting`, `corner_angle`, `window_not_at_corner`, `height_exceeds_wall`, `opening_overlap` | | `apply_patch` | Batched create/update/delete/move, validated and dry-run before commit. Batch-first is the default: send all create/update/delete ops for a build step in one atomic call (stable order, later ops may reference earlier created ids); do not loop one-op calls. A create with an id already in the scene is refused (`node_exists`); delete it earlier in the same patch to replace it. Updates cannot change `id` or `type` (`identity_change`), `object` or `children` (`immutable_field`), move a node under a missing or childless parent (`invalid_parent`), or add schema issues (`invalid_update`); default gutters and downspouts a delete regenerates are addressable only in a later call (`regenerated_default`). Refusals are tool errors with JSON text `{ code, patchIndex, id, message }`. A level created without a `height`, or an update that clears it, gets the height the editor's load derives from what the level holds (an empty level: 2.5 m), one line per level in `notes`. A roof the patch makes or moves onto the storey whose walls carry it is seated on the level above those walls, one line per roof in `notes`; a new storey at or above the roof level moves it up. Refused: storey content on a roof level (`roof_level`), declaring a level that holds storey content the roof level (`roof_level_holds_storey`), floor indexes that put the roof level under a storey (`roof_level_on_top`). | `{ patches: Patch[] }` | `{ applied: number, notes?: string[] }` | | `add_level` | Add an empty level to a building, as the editor does: on top of its storeys, under its roof level (which moves up one), or below the lowest for a basement (every existing floor, the ground floor included, keeps its place). Omit `buildingId` for the scene's only building. | `{ buildingId?, position?, name?, height? }` | `{ levelId, buildingId, floorIndex, height, shiftedLevelIds? }`; refusals `building_required`, `building_not_found`, `no_building` | +| `set_code_profile` | Say which building code the project follows (`irc-2021`, `au-ncc`, `fr`; `null` clears it), stored as `site.metadata.codeProfile`, in one undo step. The checks that apply a code read it: warnings with `irc-2021`, information that names the US IRC with no code. Nothing is guessed from an address. | | `set_ground_level` | Make a level the building's ground floor, as the level panel's "Set as ground floor": the building names it, is seated so that floor stands over grade as the building's foundation construction seats it, the top of the foundation (8 in, 0.203 m, on block: the default and the US; 0.15 m on cast concrete in Europe; height only, the plan stays), and the floor indexes are renumbered so it is 0 and the levels under it are the basements. | `{ levelId }` | `{ levelId, buildingId, floorElevation, aboveGrade, foundation { region, construction, basis }, movedBuildingBy, renumbered, unchanged? }`; refusals `level_not_found`, `not_a_level`, `no_building`, `not_a_storey` | | `add_wall` | Add a wall to a level, straight or, with `curveOffset`, an arc. Omit `levelId` for the lowest storey. wallType railing builds a guard (default 0.9144 m high); railing sets style, posts, infill and cap; postSize sets thickness. | `{ start, end, levelId?, thickness?, height?, curveOffset?, type?, wallType?, railing? }` | `{ wallId, levelId, length }`; refusals `roof_level`, `wall_too_short`, `level_not_found`, `unknown_wall_type` | | `set_wall_type` | Apply a preset or project wall assembly to existing standard walls; copies layers and total thickness. null clears the assembly. | `{ wallIds, type }` | `{ ok, wallIds, type }`; refusals `unknown_wall_type`, `target_not_found`, `curtain_wall`, `railing_wall` | diff --git a/packages/mcp/src/resources/agent-guide.ts b/packages/mcp/src/resources/agent-guide.ts index aa9431ed20..5d15a1cf93 100644 --- a/packages/mcp/src/resources/agent-guide.ts +++ b/packages/mcp/src/resources/agent-guide.ts @@ -52,6 +52,7 @@ export const AGENT_GUIDE = [ "- Finishes are given with `paint`, as the editor's Paint does: a library material found with `search_materials`, a colour, or a native material for an exact finish. `slots` and material presets are what `paint` writes, not what `apply_patch` is for.", '- Floors and ceilings are derived from rooms, not authored: walls, separators and a zone with `spaceRole: "room"` state the intent, and the structure reconciler builds the floor plate and the ceiling. Creating a slab or ceiling carrying the derived markers (`boundary` / `autoFromWalls`), or reshaping or relinking one, is refused; deleting one records that opt-out on the zone instead. A room without a floor or ceiling is expressed on its zone (`hasFloor: false`, `hasCeiling: false`), and its floor height with `floor.elevation`.', '- Manual slabs remain valid for things that are not rooms: pools, platforms, stair decks, terraces at their own elevation.', + "- `set_code_profile` says which building code the project follows (irc-2021, au-ncc or fr; null clears it), stored as the site's metadata.codeProfile, in one undo step. A project that names no code has none: nothing is guessed from an address. The checks that apply a code read it, as warnings with irc-2021 and as information that names the US IRC they used with no code.", '- A building’s levels stand on a ground line: the level at grade, named by `set_ground_level` (which seats the building so its floor stands at grade and renumbers it to floor index 0) or, until named, the lowest level whose floor is not under the ground; levels with a lower floor index are below grade. `add_level` with `position: "below"` goes one storey under the lowest level and every floor keeps its place. `list_levels` reads it as `groundLevels` and each level’s `gradeStanding` and `isGroundLevel`; `verify_scene` reports a basement the stack stands at grade (basement_at_grade; `set_ground_level` is the fix).', '- `furnish_room` skips or nudges poses that block door clear zones or overlap other items; `verify_scene` and `check_collisions` report remaining issues.', '- Adjacent rooms can share one wall (or have openings that line up). A door keeps about 0.65 m clear on both sides; furniture footprints do not overlap.', diff --git a/packages/mcp/src/tools/read-tool-annotations.test.ts b/packages/mcp/src/tools/read-tool-annotations.test.ts index b29d82b687..5869740d43 100644 --- a/packages/mcp/src/tools/read-tool-annotations.test.ts +++ b/packages/mcp/src/tools/read-tool-annotations.test.ts @@ -121,6 +121,7 @@ const TOOL_POLICIES = [ 'get_project_status', 'load_scene', 'redo', + 'set_code_profile', 'set_ground_level', 'set_unit_members', 'rename_scene', diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index 6628160e8b..d35dc926fd 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -27,6 +27,7 @@ import { addLevelTool, addObjectTool, addWallTool, + codeProfileOutput, createRoofTool, createRoomTool, createStairTool, @@ -59,6 +60,7 @@ import { searchAssetsTool, searchMaterialsTool, setCheckpointTool, + setCodeProfileTool, setGroundLevelTool, setUnitMembersTool, setWallTypeTool, @@ -268,6 +270,12 @@ const SHARED_TOOLS: SharedTool[] = [ ...liveSyncOutput, }, }, + { + contract: setCodeProfileTool, + operation: AGENT_OPERATIONS.set_code_profile, + annotations: DESTRUCTIVE_TOOL_ANNOTATIONS, + outputSchema: { ...codeProfileOutput, ...achievedOutput, ...liveSyncOutput }, + }, { contract: setGroundLevelTool, operation: AGENT_OPERATIONS.set_ground_level, diff --git a/plugin-evals/tool-annotation-justifications.json b/plugin-evals/tool-annotation-justifications.json index 1eca763014..185c1209c9 100644 --- a/plugin-evals/tool-annotation-justifications.json +++ b/plugin-evals/tool-annotation-justifications.json @@ -981,6 +981,19 @@ "openWorldHint": "It operates only on the connected Pascal scene and does not access the public internet." } }, + { + "name": "set_code_profile", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, + "justifications": { + "readOnlyHint": "It is not read-only because it writes the building code the connected Pascal project follows on its site.", + "destructiveHint": "It replaces the project's single code profile (or clears it), so a wrong call changes which thresholds the checks apply; it removes no modeled content and leaves the rest of the site's metadata as it was.", + "openWorldHint": "It operates only on the connected Pascal scene and does not access the public internet." + } + }, { "name": "set_floor_foundation", "annotations": { From aa90429d5f130f5394927d5c815c0ba3da96a69e Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 16:50:11 +0100 Subject: [PATCH 04/40] Usage checks: passages, pockets, clashes, door swings and wall objects, measured on the real shapes verify_scene reads what a person has to move through: the width of a passage and of a doorway, a pocket a piece leaves where nobody can stand, two pieces that clash, a door whose leaf stops against something, an entry that is narrow, an object that stands out from a wall, a turning circle, the clearance beside a bed or a fixture, a window a piece blocks, a door that opens over stair treads. Each is measured on the shapes the scene has (walls and their bodies, door and window frames, stair treads and guards, fences, cabinets, items, and what a scripted object occupies at each height), on a clearance grid, with the building code the project names for the thresholds. Off unless a host turns them on (`setSdfChecks`; `PASCAL_SDF_CHECKS` in the standalone app and the MCP). The circulation graph (the spaces a person walks between, and the doors, openings, stairs and lifts that join them) and the floor each space stands on are the base the widths are walked on. A scripted object's footprint is written by the compiler per height band when usage checks are on (`usageShape`, in the manifest's `shape`); without it an object has no footprint. Read against main's node kinds only: a stair's guard is its rail line, a hand wide; a room's headroom under a roof is not read (no ceiling or headroom finding); curtains and blinds, ramps, free-form roofs and the furniture kind are not read. Rule tests for the findings (passages, turning circles, pockets, the flag) and for each shape, the entrance a measure walks from, and the rule tests of the scripted shapes. The two tests of the model-facing fold of a narrow place come with the verify_scene hub. Co-Authored-By: Claude Sonnet 5.5 --- apps/editor/lib/bootstrap.ts | 5 + packages/core/package.json | 5 + .../src/agent-operations/circulation-graph.ts | 1017 +++++++++ .../circulation-non-spaces.ts | 105 + .../agent-operations/circulation-spaces.ts | 522 +++++ .../src/agent-operations/ground-reader.ts | 32 + packages/core/src/agent-operations/index.ts | 1 + .../core/src/agent-operations/usage-checks.ts | 13 + .../core/src/agent-operations/verify-scene.ts | 2 + .../spatial-grid/built-in-floor-placed.ts | 294 +++ packages/core/src/schema/geometry-source.ts | 23 + packages/core/src/schema/index.ts | 1 + packages/core/src/spatial/usage-field/beds.ts | 379 ++++ .../core/src/spatial/usage-field/blocked.ts | 228 ++ .../src/spatial/usage-field/blocking.test.ts | 423 ++++ .../src/spatial/usage-field/boxes.test.ts | 140 ++ .../core/src/spatial/usage-field/boxes.ts | 94 + .../src/spatial/usage-field/cases.test.ts | 403 ++++ .../spatial/usage-field/catalogue-shapes.ts | 2018 +++++++++++++++++ .../core/src/spatial/usage-field/catalogue.ts | 15 + .../core/src/spatial/usage-field/clash.ts | 211 ++ .../src/spatial/usage-field/door-stairs.ts | 151 ++ .../src/spatial/usage-field/engine.test.ts | 166 ++ .../core/src/spatial/usage-field/entry-way.ts | 262 +++ .../src/spatial/usage-field/fences.test.ts | 92 + .../core/src/spatial/usage-field/fences.ts | 307 +++ .../core/src/spatial/usage-field/field.ts | 168 ++ .../spatial/usage-field/findings-more.test.ts | 575 +++++ .../src/spatial/usage-field/findings.test.ts | 481 ++++ .../core/src/spatial/usage-field/findings.ts | 369 +++ .../core/src/spatial/usage-field/fixtures.ts | 187 ++ .../core/src/spatial/usage-field/flag.test.ts | 20 + packages/core/src/spatial/usage-field/flag.ts | 16 + .../core/src/spatial/usage-field/floors.ts | 42 + .../core/src/spatial/usage-field/index.ts | 6 + .../src/spatial/usage-field/items.test.ts | 286 +++ .../core/src/spatial/usage-field/items.ts | 321 +++ .../core/src/spatial/usage-field/labels.ts | 19 + .../src/spatial/usage-field/level-field.ts | 138 ++ .../src/spatial/usage-field/measure.test.ts | 178 ++ .../core/src/spatial/usage-field/measure.ts | 576 +++++ .../core/src/spatial/usage-field/obstacles.ts | 275 +++ .../src/spatial/usage-field/openings.test.ts | 138 ++ .../core/src/spatial/usage-field/openings.ts | 261 +++ packages/core/src/spatial/usage-field/path.ts | 396 ++++ .../core/src/spatial/usage-field/pieces.ts | 115 + .../spatial/usage-field/protrusion.test.ts | 191 ++ .../src/spatial/usage-field/protrusion.ts | 223 ++ .../src/spatial/usage-field/shapes.test.ts | 139 ++ .../core/src/spatial/usage-field/shapes.ts | 99 + .../src/spatial/usage-field/stairs.test.ts | 116 + .../core/src/spatial/usage-field/stairs.ts | 198 ++ .../core/src/spatial/usage-field/support.ts | 72 + .../core/src/spatial/usage-field/swings.ts | 479 ++++ .../core/src/spatial/usage-field/types.ts | 82 + .../src/spatial/usage-field/walls.test.ts | 100 + .../core/src/spatial/usage-field/walls.ts | 199 ++ .../core/src/spatial/usage-field/way-in.ts | 150 ++ .../core/src/systems/fence/guard-layout.ts | 251 ++ .../core/src/systems/stair/stair-clearance.ts | 9 +- .../src/systems/wall/wall-trim-profiles.ts | 189 ++ .../editor/src/lib/geometry-script/client.ts | 3 + packages/geometry-script/src/blender.ts | 11 +- packages/geometry-script/src/compile.ts | 8 + .../geometry-script/src/sandbox-worker.ts | 5 +- .../geometry-script/src/usage-shape.test.ts | 220 ++ packages/geometry-script/src/usage-shape.ts | 729 ++++++ packages/mcp/src/bin/pascal-mcp.ts | 2 + .../mcp/src/tools/local-geometry-scripts.ts | 11 +- 69 files changed, 14953 insertions(+), 9 deletions(-) create mode 100644 packages/core/src/agent-operations/circulation-graph.ts create mode 100644 packages/core/src/agent-operations/circulation-non-spaces.ts create mode 100644 packages/core/src/agent-operations/circulation-spaces.ts create mode 100644 packages/core/src/agent-operations/ground-reader.ts create mode 100644 packages/core/src/agent-operations/usage-checks.ts create mode 100644 packages/core/src/hooks/spatial-grid/built-in-floor-placed.ts create mode 100644 packages/core/src/spatial/usage-field/beds.ts create mode 100644 packages/core/src/spatial/usage-field/blocked.ts create mode 100644 packages/core/src/spatial/usage-field/blocking.test.ts create mode 100644 packages/core/src/spatial/usage-field/boxes.test.ts create mode 100644 packages/core/src/spatial/usage-field/boxes.ts create mode 100644 packages/core/src/spatial/usage-field/cases.test.ts create mode 100644 packages/core/src/spatial/usage-field/catalogue-shapes.ts create mode 100644 packages/core/src/spatial/usage-field/catalogue.ts create mode 100644 packages/core/src/spatial/usage-field/clash.ts create mode 100644 packages/core/src/spatial/usage-field/door-stairs.ts create mode 100644 packages/core/src/spatial/usage-field/engine.test.ts create mode 100644 packages/core/src/spatial/usage-field/entry-way.ts create mode 100644 packages/core/src/spatial/usage-field/fences.test.ts create mode 100644 packages/core/src/spatial/usage-field/fences.ts create mode 100644 packages/core/src/spatial/usage-field/field.ts create mode 100644 packages/core/src/spatial/usage-field/findings-more.test.ts create mode 100644 packages/core/src/spatial/usage-field/findings.test.ts create mode 100644 packages/core/src/spatial/usage-field/findings.ts create mode 100644 packages/core/src/spatial/usage-field/fixtures.ts create mode 100644 packages/core/src/spatial/usage-field/flag.test.ts create mode 100644 packages/core/src/spatial/usage-field/flag.ts create mode 100644 packages/core/src/spatial/usage-field/floors.ts create mode 100644 packages/core/src/spatial/usage-field/index.ts create mode 100644 packages/core/src/spatial/usage-field/items.test.ts create mode 100644 packages/core/src/spatial/usage-field/items.ts create mode 100644 packages/core/src/spatial/usage-field/labels.ts create mode 100644 packages/core/src/spatial/usage-field/level-field.ts create mode 100644 packages/core/src/spatial/usage-field/measure.test.ts create mode 100644 packages/core/src/spatial/usage-field/measure.ts create mode 100644 packages/core/src/spatial/usage-field/obstacles.ts create mode 100644 packages/core/src/spatial/usage-field/openings.test.ts create mode 100644 packages/core/src/spatial/usage-field/openings.ts create mode 100644 packages/core/src/spatial/usage-field/path.ts create mode 100644 packages/core/src/spatial/usage-field/pieces.ts create mode 100644 packages/core/src/spatial/usage-field/protrusion.test.ts create mode 100644 packages/core/src/spatial/usage-field/protrusion.ts create mode 100644 packages/core/src/spatial/usage-field/shapes.test.ts create mode 100644 packages/core/src/spatial/usage-field/shapes.ts create mode 100644 packages/core/src/spatial/usage-field/stairs.test.ts create mode 100644 packages/core/src/spatial/usage-field/stairs.ts create mode 100644 packages/core/src/spatial/usage-field/support.ts create mode 100644 packages/core/src/spatial/usage-field/swings.ts create mode 100644 packages/core/src/spatial/usage-field/types.ts create mode 100644 packages/core/src/spatial/usage-field/walls.test.ts create mode 100644 packages/core/src/spatial/usage-field/walls.ts create mode 100644 packages/core/src/spatial/usage-field/way-in.ts create mode 100644 packages/core/src/systems/fence/guard-layout.ts create mode 100644 packages/core/src/systems/wall/wall-trim-profiles.ts create mode 100644 packages/geometry-script/src/usage-shape.test.ts create mode 100644 packages/geometry-script/src/usage-shape.ts diff --git a/apps/editor/lib/bootstrap.ts b/apps/editor/lib/bootstrap.ts index 6548709f35..ddaef5e2d5 100644 --- a/apps/editor/lib/bootstrap.ts +++ b/apps/editor/lib/bootstrap.ts @@ -7,6 +7,7 @@ import { nodeRegistry, registerNode, } from '@pascal-app/core' +import { sdfChecksFromEnv, setSdfChecks } from '@pascal-app/core/usage-field' import { registerEditorHostPanel } from '@pascal-app/editor' import { builtinPlugin } from '@pascal-app/nodes' import { bonesHostPanel, bonesPlugin } from '@pascal-app/plugin-bones' @@ -19,6 +20,10 @@ import { treesHostPanel, treesPlugin } from '@pascal-app/plugin-trees' import { registerViewerPresentation } from '@pascal-app/viewer' import { webXRHostPanel, webXRPlugin } from '@webxr/plugin' +// Usage checks (passages, turning circles, flow widths) are off unless the build says so; Next +// inlines the NEXT_PUBLIC_ mirror of the server's PASCAL_SDF_CHECKS. +setSdfChecks(sdfChecksFromEnv(process.env.NEXT_PUBLIC_PASCAL_SDF_CHECKS)) + // Idempotency guards: HMR can reload this module, but `registerNode` // throws on duplicate kinds. Flags live in the module closure so they // reset on a hard reload but survive within a session. diff --git a/packages/core/package.json b/packages/core/package.json index 9b19655432..f5a3d1291b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -41,6 +41,11 @@ "import": "./dist/registry/index.js", "default": "./dist/registry/index.js" }, + "./usage-field": { + "types": "./dist/spatial/usage-field/index.d.ts", + "import": "./dist/spatial/usage-field/index.js", + "default": "./dist/spatial/usage-field/index.js" + }, "./zone-colors": { "types": "./dist/lib/zone-colors.d.ts", "import": "./dist/lib/zone-colors.js", diff --git a/packages/core/src/agent-operations/circulation-graph.ts b/packages/core/src/agent-operations/circulation-graph.ts new file mode 100644 index 0000000000..17cdee41f0 --- /dev/null +++ b/packages/core/src/agent-operations/circulation-graph.ts @@ -0,0 +1,1017 @@ +import { resolveLevelId } from '../lib/node-ancestry' +import { containsPoint, difference, intersection, union } from '../lib/polygon-boolean' +import { polygonInteriorPoint } from '../lib/polygon-label' +import type { AnyNode, StairSegmentNode } from '../schema' +import { getLevelAbove } from '../services/storey' +import { stairBaseElevation } from '../systems/stair/stair-base-elevation' +import { resolveStairArcDimensions } from '../systems/stair/stair-layout' +import { resolveStairTotalRise } from '../systems/stair/stair-rise-query' +import { resolveStairWalkingPaths } from '../systems/stair/stair-walking-line' +import { circulationNonSpaces } from './circulation-non-spaces' +import { + area, + crossesWall, + doorFrame, + doorSidePoints, + doorSides, + type Floor, + floorsOf, + keyOf, + type Pt, + rotate, + type Space, + spaceAt, + spaceElevation, + walkable, +} from './circulation-spaces' +import { groundReader } from './ground-reader' +import type { SceneNodes } from './types' + +export type CirculationNode = { + id: string + kind: 'room' | 'zone' | 'floor' | 'outdoor' | 'outside' | 'stair-landing' | 'lift-landing' + levelId: string | null + sourceId: string | null + name: string + areaM2: number | null + position: [number, number, number] + apartment?: string +} +export type CirculationEdge = { + id: string + from: string + to: string + kind: 'door' | 'opening' | 'open-edge' | 'stair' | 'lift' + sourceId: string | null + widthM: number | null + position: [number, number, number] + lengthM: number + stepHeightM?: number + use?: 'vehicle' | 'pedestrian' + riseM?: number + runM?: number + maximumSlopePercent?: number + maxSlopePercent?: number + startTransitionM?: number + endTransitionM?: number + path?: [number, number, number][] +} +export type CirculationIssue = { + type: string + message: string + nodeIds: string[] + levelIds?: string[] + reasonCode?: string + spaceId?: string +} +/** A space that is not a destination: open air through a floor opening, or an outdoor slab. */ +export type CirculationNonSpace = 'void' | 'outdoor-slab' +/** A door on a raised level that opens to open air with no modelled ground in reach of its sill. */ +export type UnmeasuredEntrance = { doorId: string; spaceId: string; levelId: string } +export type CirculationGraph = { + nodes: Map + edges: CirculationEdge[] + floors: Floor[] + issues: CirculationIssue[] + unsupportedIds: string[] + unmeasuredEntrances: UnmeasuredEntrance[] + /** Stairs with no destination level that are the way in from the outside ground. */ + entranceFlights: Set + nonSpaces: Map +} +const EDGE_STEP = 0.75 +const EDGE_PROBE = 0.3 +const LANDING_PROBE = 0.6 +const LIFT_PROBE = 0.5 +const STAIR_HEIGHT_TOLERANCE_M = 0.05 + +export const nodeName = (nodes: SceneNodes, id: string) => + nodes[id]?.name ?? `Unnamed ${nodes[id]?.type ?? 'element'}` + +function spaceNode(nodes: SceneNodes, floor: Floor, space: Space, point: Pt): CirculationNode { + const id = keyOf(space) + const zone = + space.kind === 'zone' || space.kind === 'outdoor' + ? floor.zones.find((candidate) => `zone:${candidate.id}` === id) + : undefined + const slab = + space.kind === 'outdoor' + ? floor.slabs.find((candidate) => `outdoor:${candidate.id}` === id) + : undefined + const sourceId = zone?.id ?? slab?.id ?? null + const source = sourceId ? nodes[sourceId] : undefined + const floorSlab = + space.kind === 'floor' + ? floor.slabs.find((candidate) => `floor:${floor.id}:${candidate.id}` === id) + : undefined + const at = zone + ? polygonInteriorPoint(zone, true) + : slab + ? polygonInteriorPoint(slab, true) + : point + return { + id, + kind: + space.kind === 'outdoor' + ? 'outdoor' + : space.kind === 'outside' + ? 'outside' + : zone + ? source?.type === 'zone' && source.spaceRole === 'room' + ? 'room' + : 'zone' + : 'floor', + levelId: space.kind === 'outside' ? null : floor.id, + sourceId, + name: sourceId + ? nodeName(nodes, sourceId) + : space.kind === 'outside' + ? 'Outside' + : floorSlab + ? nodeName(nodes, floorSlab.id) + : `${floor.name} open floor`, + areaM2: zone?.area ?? (space.kind === 'outdoor' ? space.area : null), + position: [ + at[0], + space.kind === 'outside' ? floor.elevation : spaceElevation(floor, space, at), + at[1], + ], + ...(space.kind === 'zone' && space.apartment ? { apartment: space.apartment } : {}), + } +} + +function graphWriter(scene: SceneNodes, graph: CirculationGraph) { + const note = (floor: Floor, space: Space, point: Pt) => { + const id = keyOf(space) + if (!graph.nodes.has(id)) graph.nodes.set(id, spaceNode(scene, floor, space, point)) + return id + } + const link = ( + from: string, + to: string, + kind: CirculationEdge['kind'], + sourceId: string | null, + widthM: number | null, + position: CirculationEdge['position'], + lengthM?: number, + stepHeightM?: number, + path?: CirculationEdge['path'], + ) => { + if (from === to) return + if ( + kind === 'open-edge' && + graph.edges.some( + (edge) => + edge.kind === kind && + ((edge.from === from && edge.to === to) || (edge.from === to && edge.to === from)), + ) + ) + return + const start = graph.nodes.get(from) + const end = graph.nodes.get(to) + if (!start || !end) return + const distance = (node: CirculationNode) => + node.kind === 'outside' + ? 0 + : Math.hypot( + node.position[0] - position[0], + node.position[1] - position[1], + node.position[2] - position[2], + ) + graph.edges.push({ + id: `edge:${sourceId ?? kind}:${graph.edges.length}`, + from, + to, + kind, + sourceId, + widthM, + position, + lengthM: lengthM ?? distance(start) + distance(end), + ...(stepHeightM !== undefined ? { stepHeightM } : {}), + ...(path ? { path } : {}), + }) + } + return { note, link } +} +export type CirculationWriter = ReturnType +type Writer = CirculationWriter + +/** + * What an enclosed space leaves that no zone covers is a room to reach only where a person can stand + * in it: thinner than this on average (twice its area over its perimeter), it is the strip between a + * zone's edge and a wall face, or a boolean's rounding, and the zones around it are the room (m). + */ +const MIN_UNZONED_THICKNESS_M = 0.3 + +function standable(outer: readonly Pt[], holes: readonly (readonly Pt[])[]): boolean { + const perimeter = [outer, ...holes].reduce( + (sum, ring) => + sum + + ring.reduce((around, [x, z], i) => { + const [nx, nz] = ring[(i + 1) % ring.length]! + return around + Math.hypot(nx - x, nz - z) + }, 0), + 0, + ) + const matter = area(outer) - holes.reduce((sum, ring) => sum + area(ring), 0) + return perimeter > 0 && (2 * matter) / perimeter >= MIN_UNZONED_THICKNESS_M +} + +function seedSpaces(graph: CirculationGraph, writer: Writer) { + for (const floor of graph.floors) { + for (const zone of floor.zones) { + const point = polygonInteriorPoint(zone, true) + writer.note( + floor, + { + kind: zone.outdoor ? 'outdoor' : 'zone', + key: `zone:${zone.id}`, + area: zone.area, + ...(zone.apartment ? { apartment: zone.apartment } : {}), + }, + point, + ) + } + const cuts = [...floor.voids, ...floor.shafts].map((outer) => ({ outer, holes: [] })) + const walkingFloor = difference( + union(floor.slabs.map((slab) => ({ outer: slab.polygon, holes: slab.holes }))), + cuts, + ) + // Unzoned enclosed rooms must exist even when nothing opens onto them. + floor.pockets.forEach((pocket, index) => { + const remaining = difference( + intersection(pocket.polygon, walkingFloor), + floor.zones.map((zone) => ({ outer: zone.polygon, holes: zone.holes })), + ) + const part = remaining + .filter((candidate) => standable(candidate.outer, candidate.holes)) + .sort((a, b) => area(b.outer) - area(a.outer))[0] + if (!part) return + const point = polygonInteriorPoint({ polygon: part.outer, holes: part.holes }, true) + const space = spaceAt(floor, point) + if (space.kind === 'floor' && space.key === `floor:${floor.id}:${index}`) { + const id = writer.note(floor, space, point) + const node = graph.nodes.get(id) + if (node) + graph.nodes.set(id, { + ...node, + name: `${floor.name} enclosed space ${index + 1}`, + areaM2: area(pocket.polygon), + }) + } + }) + for (const slab of floor.slabs) { + const parts = difference({ outer: slab.polygon, holes: slab.holes }, cuts) + if (parts.length > 1) graph.unsupportedIds.push(slab.id) + const part = parts[0] + if (!part) continue + const point = polygonInteriorPoint({ polygon: part.outer, holes: part.holes }, true) + const space = spaceAt(floor, point) + if (space.kind === 'floor' || space.kind === 'outdoor') writer.note(floor, space, point) + } + } +} + +/** How far a walkway's top may stand from the terrain it lands on and still meet it (m). */ +const LANDING_REACH = 0.3 + +type GroundAt = (point: Pt) => number | null + +/** + * A door of a raised level that opens to open air is an entrance when the terrain at its step is + * within reach of its sill (a street door of a hillside level): the site's outside is then that + * terrain, and the step is the difference. Where no modelled ground is within reach, the approach + * cannot be measured and the space behind the door is unmeasured, not unreachable. + */ +function raisedEntrance( + graph: CirculationGraph, + writer: Writer, + floor: Floor, + door: Extract, + sides: readonly [Space, Space], + probes: readonly [Pt, Pt], + point: Pt, + groundAt: GroundAt, +) { + if (floor.ground) return false + const air = sides.findIndex((side) => side.kind === 'open-air') + const inner = air === 0 ? sides[1] : sides[0] + const innerProbe = air === 0 ? probes[1] : probes[0] + if (air < 0 || !walkable(inner) || inner.kind === 'outside') return false + const sill = spaceElevation(floor, inner, innerProbe) + const terrain = groundAt(probes[air] ?? point) + // A door of a basement whose sill is under the terrain opens onto earth: no way in, and nothing + // to measure. A basement door level with the terrain (a walk-out) is an entrance like any other. + if (floor.belowGround && terrain !== null && terrain - sill > LANDING_REACH) return true + if (terrain !== null && Math.abs(terrain - sill) <= LANDING_REACH) { + writer.link( + writer.note(floor, inner, point), + writer.note(floor, { kind: 'outside' }, point), + door.openingKind === 'opening' ? 'opening' : 'door', + door.id, + door.width, + [point[0], floor.elevation, point[1]], + undefined, + Math.abs(terrain - sill), + ) + return true + } + graph.unmeasuredEntrances.push({ + doorId: door.id, + spaceId: writer.note(floor, inner, point), + levelId: floor.id, + }) + return true +} + +function doorEdges( + scene: SceneNodes, + graph: CirculationGraph, + writer: Writer, + ground: ReturnType, +) { + const floorById = new Map(graph.floors.map((floor) => [floor.id, floor])) + for (const door of Object.values(scene)) { + if (door.type !== 'door') continue + const wall = scene[door.wallId ?? door.parentId ?? ''] + if (wall?.type !== 'wall') { + graph.unsupportedIds.push(door.id) + continue + } + const floor = floorById.get(wall.parentId ?? '') + if (!floor) continue + const sides = doorSides(floor, wall, door.position[0]) + const sidePoints = doorSidePoints(wall, door.position[0]) + const blocked = sides.find((side) => side.kind === 'shaft' || side.kind === 'void') + if (blocked) { + graph.issues.push({ + type: 'door_leads_nowhere', + message: `${nodeName(scene, door.id)} (${floor.name}) opens into ${blocked.kind === 'shaft' ? 'a lift shaft' : 'a stair well'}: no floor to step onto.`, + nodeIds: [door.id, wall.id], + levelIds: [floor.id], + }) + continue + } + const frame = doorFrame(wall, door.position[0]) + const point: Pt = [frame.point.x, frame.point.y] + if ( + raisedEntrance(graph, writer, floor, door, sides, sidePoints, point, (probe) => + ground(floor.id, probe), + ) + ) + continue + if (!sides.every(walkable)) continue + writer.link( + writer.note(floor, sides[0], point), + writer.note(floor, sides[1], point), + door.openingKind === 'opening' ? 'opening' : 'door', + door.id, + door.width, + [point[0], floor.elevation, point[1]], + undefined, + sides.some((side) => side.kind === 'outside' || side.kind === 'outdoor') + ? Math.abs( + spaceElevation(floor, sides[0], sidePoints[0]) - + spaceElevation(floor, sides[1], sidePoints[1]), + ) + : undefined, + ) + } +} + +/** + * Where an open-supported floor above the ground floor reaches the ground: a probe beside its edge + * is open air, and the terrain there is within reach of the floor's top. That side is then the + * site's outside, at the height of the terrain, and the step is the difference. + */ +function groundLanding( + floor: Floor, + sides: readonly [Space, Space], + probes: readonly [Pt, Pt], + elevations: readonly [number, number], + groundAt: GroundAt, +): { index: 0 | 1; terrain: number } | null { + if (floor.ground) return null + for (const index of [0, 1] as const) { + const [side, other] = index === 0 ? [sides[0], sides[1]] : [sides[1], sides[0]] + const deckTop = index === 0 ? elevations[1] : elevations[0] + if (side.kind !== 'open-air' || other.kind !== 'outdoor') continue + const terrain = groundAt(probes[index]) + if (terrain !== null && Math.abs(terrain - deckTop) <= LANDING_REACH) return { index, terrain } + } + return null +} + +function isHighDeckBoundary(floor: Floor, sides: readonly Space[], probes: readonly Pt[]) { + return sides.some((side, index) => { + const probe = probes[index] + return ( + probe && + side.kind === 'outdoor' && + floor.slabs.some( + (slab) => + slab.outdoor && + containsPoint([{ outer: slab.polygon, holes: slab.holes }], probe) && + slab.elevation - floor.groundElevation > LANDING_REACH, + ) + ) + }) +} + +function openEdge(floor: Floor, start: Pt, end: Pt, writer: Writer, groundAt: GroundAt) { + const length = Math.hypot(end[0] - start[0], end[1] - start[1]) + if (length < 0.5) return + const [ux, uz] = [(end[0] - start[0]) / length, (end[1] - start[1]) / length] + const count = Math.max(1, Math.round(length / EDGE_STEP)) + for (let sample = 0; sample < count; sample++) { + const along = ((sample + 0.5) / count) * length + if (along < 0.2 || along > length - 0.2) continue + const point: Pt = [start[0] + ux * along, start[1] + uz * along] + const left: Pt = [point[0] - uz * EDGE_PROBE, point[1] + ux * EDGE_PROBE] + const right: Pt = [point[0] + uz * EDGE_PROBE, point[1] - ux * EDGE_PROBE] + const bare = [spaceAt(floor, left), spaceAt(floor, right)] as const + const bareElevations = [ + spaceElevation(floor, bare[0], left), + spaceElevation(floor, bare[1], right), + ] as const + const landing = groundLanding(floor, bare, [left, right], bareElevations, groundAt) + const sides: readonly [Space, Space] = landing + ? landing.index === 0 + ? [{ kind: 'outside' }, bare[1]] + : [bare[0], { kind: 'outside' }] + : bare + if ( + !sides.every(walkable) || + keyOf(sides[0]) === keyOf(sides[1]) || + crossesWall(floor, left, right) + ) + continue + const outsideFirst = sides[1].kind === 'outside' + const elevations = landing + ? ([ + landing.index === 0 ? landing.terrain : bareElevations[0], + landing.index === 1 ? landing.terrain : bareElevations[1], + ] as const) + : bareElevations + const outdoorOnly = sides.every((side) => side.kind === 'outside' || side.kind === 'outdoor') + if ( + outdoorOnly && + isHighDeckBoundary(floor, sides, [left, right]) && + Math.abs(elevations[0] - elevations[1]) > LANDING_REACH + ) + continue + const elevation = outdoorOnly ? Math.max(...elevations) : floor.elevation + writer.link( + writer.note(floor, outsideFirst ? sides[1] : sides[0], outsideFirst ? right : left), + writer.note(floor, outsideFirst ? sides[0] : sides[1], outsideFirst ? left : right), + 'open-edge', + null, + null, + [point[0], elevation, point[1]], + undefined, + sides.some((side) => side.kind === 'outside' || side.kind === 'outdoor') + ? Math.abs(elevations[0] - elevations[1]) + : undefined, + ) + } +} +function openEdges( + graph: CirculationGraph, + writer: Writer, + ground: ReturnType, +) { + for (const floor of graph.floors) { + const groundAt: GroundAt = (point) => ground(floor.id, point) + for (const polygon of [ + ...floor.zones.map((zone) => zone.polygon), + ...floor.slabs.map((slab) => slab.polygon), + ]) + polygon.forEach((start, index) => { + const end = polygon[(index + 1) % polygon.length] + if (end) openEdge(floor, start, end, writer, groundAt) + }) + } +} + +type StairEnd = { + floor: Floor + endpoint: number[] + adjacent: number[] + head: boolean + width: number +} +function stairBaseY(scene: SceneNodes, floor: Floor, stair: Extract) { + return floor.groundElevation + stairBaseElevation(stair, scene, floor.id) +} +function stairEndPoints( + stair: Extract, + endpoint: number[], + adjacent: number[], + probe = LANDING_PROBE, +) { + const [localX = 0, , localZ = 0] = endpoint + const offset = rotate([localX, localZ], stair.rotation) + const point: Pt = [stair.position[0] + offset[0], stair.position[2] + offset[1]] + const direction = rotate( + [localX - (adjacent[0] ?? 0), localZ - (adjacent[2] ?? 0)], + stair.rotation, + ) + const length = Math.hypot(...direction) + if (!length) return null + const target: Pt = [ + point[0] + (direction[0] / length) * probe, + point[1] + (direction[1] / length) * probe, + ] + return { point, target } +} +function stairLanding( + scene: SceneNodes, + graph: CirculationGraph, + writer: Writer, + stair: Extract, + end: StairEnd, +) { + const { floor, endpoint, adjacent, head, width } = end + const points = stairEndPoints(stair, endpoint, adjacent) + if (!points) return null + const { point, target } = points + const space = spaceAt(floor, target) + const sourceFloor = graph.floors.find( + (candidate) => candidate.id === (stair.fromLevelId ?? resolveLevelId(stair, scene)), + ) + const endpointY = (sourceFloor ? stairBaseY(scene, sourceFloor, stair) : 0) + (endpoint[1] ?? 0) + if ( + !walkable(space) || + space.kind === 'outside' || + crossesWall(floor, point, target) || + Math.abs(endpointY - spaceElevation(floor, space, target)) > STAIR_HEIGHT_TOLERANCE_M + ) { + graph.issues.push({ + type: 'stair_has_no_landing', + message: `No floor to step onto: ${nodeName(scene, stair.id)} at its ${head ? 'head' : 'foot'} (${floor.name}).`, + nodeIds: [stair.id], + levelIds: [floor.id], + }) + return null + } + const id = `stair:${stair.id}:${floor.id}` + graph.nodes.set(id, { + id, + kind: 'stair-landing', + sourceId: stair.id, + levelId: floor.id, + name: `${nodeName(scene, stair.id)} ${head ? 'head' : 'foot'}`, + areaM2: null, + position: [point[0], endpointY, point[1]], + }) + writer.link(id, writer.note(floor, space, target), 'open-edge', stair.id, width, [ + target[0], + floor.elevation, + target[1], + ]) + return id +} +function stairWalk(scene: SceneNodes, stair: Extract) { + const segments = stair.children + .map((id) => scene[id]) + .filter((node): node is StairSegmentNode => node?.type === 'stair-segment') + if ( + stair.stairType === 'straight' && + (!segments.length || segments.length !== stair.children.length) + ) + return null + const paths = resolveStairWalkingPaths(stair, segments, resolveStairTotalRise(stair, scene)) + const path = paths.length === 1 ? paths[0] : undefined + const first = path?.[0], + second = path?.[1], + last = path?.at(-1), + previous = path?.at(-2) + if (!path || !first || !second || !last || !previous) return null + const straight = stair.stairType === 'straight' + const width = straight + ? Math.min(...segments.map((segment) => segment.width)) + : resolveStairArcDimensions(stair, 0).width + const length = path.slice(1).reduce((sum, point, index) => { + const before = path[index] + return before + ? sum + Math.hypot(point[0] - before[0], point[1] - before[1], point[2] - before[2]) + : sum + }, 0) + return { + path, + first, + second, + last, + previous, + width, + startWidth: straight ? (segments[0]?.width ?? width) : width, + endWidth: straight ? (segments.at(-1)?.width ?? width) : width, + length, + } +} + +function stairPath( + stair: Extract, + walk: NonNullable>, + baseY: number, +): [number, number, number][] { + return walk.path.map(([x, y, z]) => { + const offset = rotate([x, z], stair.rotation) + return [stair.position[0] + offset[0], baseY + y, stair.position[2] + offset[1]] + }) +} + +/** + * An end of an entrance flight: a space of the level, or, above the ground floor, open air whose + * terrain is within reach of the end's height, which is then the site's outside at that terrain. + */ +function flightEnd(floor: Floor, point: Pt, y: number, groundAt: GroundAt) { + const space = spaceAt(floor, point) + if (space.kind === 'open-air') { + const terrain = groundAt(point) + if (terrain !== null && Math.abs(terrain - y) <= LANDING_REACH) + return { space: { kind: 'outside' } as Space, y: terrain, grade: true } + } + return { space, y: spaceElevation(floor, space, point), grade: false } +} + +/** The distance in plan from a point to a polyline. */ +function distanceToPath(point: Pt, path: readonly [number, number, number][]) { + let best = Number.POSITIVE_INFINITY + for (let index = 1; index < path.length; index++) { + const [ax = 0, , az = 0] = path[index - 1] ?? [] + const [bx = 0, , bz = 0] = path[index] ?? [] + const [dx, dz] = [bx - ax, bz - az] + const length = dx * dx + dz * dz + const t = length + ? Math.max(0, Math.min(1, ((point[0] - ax) * dx + (point[1] - az) * dz) / length)) + : 0 + best = Math.min(best, Math.hypot(point[0] - (ax + dx * t), point[1] - (az + dz * t))) + } + return best +} + +/** + * The door a facade flight climbs to: a door of the level that opens to air, whose space behind it + * is the flight's top and whose threshold is at the flight's end. Its approach is then measured by + * the flight, so it is an entrance and no longer an unmeasured one. + */ +function doorAtTopOfFlight( + scene: SceneNodes, + graph: CirculationGraph, + writer: Writer, + floor: Floor, + top: Space, + topY: number, + footY: number, + width: number, + path: readonly [number, number, number][], +) { + const found = graph.unmeasuredEntrances.find((entrance) => { + if (entrance.levelId !== floor.id || entrance.spaceId !== keyOf(top)) return false + const door = scene[entrance.doorId] + const wall = door?.type === 'door' ? scene[door.wallId ?? door.parentId ?? ''] : undefined + if (wall?.type !== 'wall' || door?.type !== 'door') return false + const frame = doorFrame(wall, door.position[0]) + return distanceToPath([frame.point.x, frame.point.y], path) <= width / 2 + LANDING_REACH + }) + const door = found ? scene[found.doorId] : undefined + const wall = door?.type === 'door' ? scene[door.wallId ?? door.parentId ?? ''] : undefined + if (!found || wall?.type !== 'wall' || door?.type !== 'door') return false + const frame = doorFrame(wall, door.position[0]) + const point: Pt = [frame.point.x, frame.point.y] + writer.link( + writer.note(floor, top, point), + writer.note(floor, { kind: 'outside' }, point), + door.openingKind === 'opening' ? 'opening' : 'door', + door.id, + door.width, + [point[0], floor.elevation, point[1]], + undefined, + Math.abs(topY - footY), + ) + graph.unmeasuredEntrances = graph.unmeasuredEntrances.filter((entrance) => entrance !== found) + return true +} + +/** + * An entrance flight: a stair with no destination level whose foot (or head) stands on the outside + * ground (the flat grade or the terrain within reach of its height) and whose other end meets a + * walking floor of its own level. It joins Outside to that floor with a measured rise. + */ +function entranceSteps( + scene: SceneNodes, + graph: CirculationGraph, + floor: Floor, + writer: Writer, + stair: Extract, + flight: NonNullable>, + groundAt: GroundAt, +) { + if (stair.toLevelId) return false + // A flight that goes down from a floor is the same flight read from its low end. + const walk = + flight.last[1] < flight.first[1] + ? { + ...flight, + path: [...flight.path].reverse(), + first: flight.last, + second: flight.previous, + last: flight.first, + previous: flight.second, + } + : flight + const baseY = stairBaseY(scene, floor, stair) + const footY = baseY + walk.first[1] + const headY = baseY + walk.last[1] + const path = stairPath(stair, walk, baseY) + const outdoors = (space: Space) => space.kind === 'outside' || space.kind === 'outdoor' + const foot = stairEndPoints(stair, walk.first, walk.second, 0.03) + const head = stairEndPoints(stair, walk.last, walk.previous, 0.03) + if (!foot || !head) return false + const a = flightEnd(floor, foot.target, footY, groundAt) + let b = flightEnd(floor, head.target, headY, groundAt) + // A flight whose top stands at a door ends at the wall: the floor it rises to lies one step + // beyond it. + let facade = walkable(b.space) && crossesWall(floor, head.point, head.target) + const lands = (end: typeof b) => + walkable(end.space) && + (end.grade || + end.space.kind !== 'outside' || + Math.abs(headY - end.y) <= STAIR_HEIGHT_TOLERANCE_M) + if (!lands(b)) { + const beyond = stairEndPoints(stair, walk.last, walk.previous, LANDING_REACH) + const reached = beyond ? flightEnd(floor, beyond.target, headY, groundAt) : null + if ( + beyond && + reached && + walkable(reached.space) && + reached.space.kind !== 'outside' && + crossesWall(floor, head.point, beyond.target) + ) { + b = reached + head.target = beyond.target + facade = true + } + } + if ( + !walkable(a.space) || + !walkable(b.space) || + (!outdoors(a.space) && !outdoors(b.space)) || + (!a.grade && Math.abs(footY - a.y) > STAIR_HEIGHT_TOLERANCE_M) || + (!b.grade && Math.abs(headY - b.y) > STAIR_HEIGHT_TOLERANCE_M) || + crossesWall(floor, foot.point, foot.target) + ) + return false + if (facade || crossesWall(floor, foot.point, head.point)) { + // A facade stair is not a second entrance through a closed wall: it is the approach of a door. + const [outer, inner] = outdoors(a.space) ? [a, b] : [b, a] + const joined = graph.edges.some( + (edge) => + (edge.kind === 'door' || edge.kind === 'opening') && + ((edge.from === keyOf(a.space) && edge.to === keyOf(b.space)) || + (edge.from === keyOf(b.space) && edge.to === keyOf(a.space))), + ) + const approach = + outer.grade && + doorAtTopOfFlight( + scene, + graph, + writer, + floor, + inner.space, + inner.y, + outer.y, + walk.width, + path, + ) + if (joined || approach) graph.entranceFlights.add(stair.id) + return joined || approach + } + writer.link( + writer.note(floor, a.space, foot.target), + writer.note(floor, b.space, head.target), + 'stair', + stair.id, + walk.width, + [foot.point[0], a.y, foot.point[1]], + walk.length, + Math.abs(b.y - a.y), + path, + ) + graph.entranceFlights.add(stair.id) + return true +} + +function stairEdges( + scene: SceneNodes, + graph: CirculationGraph, + writer: Writer, + ground: ReturnType, +) { + const floors = new Map(graph.floors.map((floor) => [floor.id, floor])) + for (const stair of Object.values(scene)) { + if (stair.type !== 'stair') continue + const foot = floors.get(stair.fromLevelId ?? resolveLevelId(stair, scene) ?? '') + const head = floors.get( + stair.toLevelId ?? (foot ? getLevelAbove(foot.id, scene)?.id : undefined) ?? '', + ) + const walk = stairWalk(scene, stair) + if (!foot || !walk) { + graph.unsupportedIds.push(stair.id) + graph.issues.push({ + type: 'stair_has_no_landing', + message: `${nodeName(scene, stair.id)} has no complete modeled walking path from a floor.`, + nodeIds: [stair.id], + levelIds: foot ? [foot.id] : [], + }) + continue + } + if (entranceSteps(scene, graph, foot, writer, stair, walk, (probe) => ground(foot.id, probe))) + continue + const startId = stairLanding(scene, graph, writer, stair, { + floor: foot, + endpoint: walk.first, + adjacent: walk.second, + head: false, + width: walk.startWidth, + }) + const endId = head + ? stairLanding(scene, graph, writer, stair, { + floor: head, + endpoint: walk.last, + adjacent: walk.previous, + head: true, + width: walk.endWidth, + }) + : null + if (!head) { + graph.unsupportedIds.push(stair.id) + graph.issues.push({ + type: 'stair_has_no_landing', + message: `${nodeName(scene, stair.id)} has no destination walking floor.`, + nodeIds: [stair.id], + levelIds: [foot.id], + }) + } + if (!startId || !endId) graph.unsupportedIds.push(stair.id) + if (startId && endId) + writer.link( + startId, + endId, + 'stair', + stair.id, + walk.width, + graph.nodes.get(startId)?.position ?? [0, 0, 0], + walk.length, + undefined, + stairPath(stair, walk, stairBaseY(scene, foot, stair)), + ) + } +} + +function liftLanding( + scene: SceneNodes, + graph: CirculationGraph, + writer: Writer, + lift: Extract, + floor: Floor, + point: Pt, +) { + const front = spaceAt(floor, point) + if (!walkable(front) || front.kind === 'outside') { + graph.issues.push({ + type: 'lift_door_blocked', + message: `${nodeName(scene, lift.id)} opens onto nothing on ${floor.name}.`, + nodeIds: [lift.id], + levelIds: [floor.id], + }) + return null + } + if (front.kind === 'zone' && front.apartment) + graph.issues.push({ + type: 'lift_door_blocked', + message: `${nodeName(scene, lift.id)} opens into ${nodeName(scene, front.apartment)} on ${floor.name}, not shared circulation.`, + nodeIds: [lift.id, front.apartment], + levelIds: [floor.id], + }) + const id = `lift:${lift.id}:${floor.id}` + graph.nodes.set(id, { + id, + kind: 'lift-landing', + sourceId: lift.id, + levelId: floor.id, + name: `${nodeName(scene, lift.id)} ${floor.name}`, + areaM2: null, + position: [point[0], floor.elevation, point[1]], + }) + writer.link(id, writer.note(floor, front, point), 'open-edge', lift.id, lift.doorWidth, [ + point[0], + floor.elevation, + point[1], + ]) + return id +} + +function liftEdges( + scene: SceneNodes, + graph: CirculationGraph, + writer: Writer, + context: ReturnType, +) { + for (const lift of context.elevators) { + const [cx, cz] = context.liftOrigin(lift) + const reach = + (lift.shaftDepth ?? lift.depth) / 2 + (lift.shaftWallThickness ?? 0.09) + LIFT_PROBE + const offset = rotate([0, -reach], lift.rotation) + const point: Pt = [cx + offset[0], cz + offset[1]] + let previous: string | null = null + for (const floor of graph.floors) { + if (!context.serves(lift, floor.id)) continue + const id = liftLanding(scene, graph, writer, lift, floor, point) + if (!id) continue + if (previous) + writer.link( + previous, + id, + 'lift', + lift.id, + lift.doorWidth, + [cx, floor.elevation, cz], + Math.abs(floor.elevation - (graph.nodes.get(previous)?.position[1] ?? floor.elevation)), + ) + previous = id + } + } +} + +export function buildCirculationGraph(scene: SceneNodes): CirculationGraph { + const context = floorsOf(scene) + const graph: CirculationGraph = { + nodes: new Map(), + edges: [], + floors: context.floors, + issues: [], + unsupportedIds: [], + unmeasuredEntrances: [], + entranceFlights: new Set(), + nonSpaces: new Map(), + } + const writer = graphWriter(scene, graph) + seedSpaces(graph, writer) + const ground = groundReader(scene) + doorEdges(scene, graph, writer, ground) + openEdges(graph, writer, ground) + stairEdges(scene, graph, writer, ground) + liftEdges(scene, graph, writer, context) + graph.nonSpaces = circulationNonSpaces(scene, graph) + return graph +} + +export function circulationLinks(graph: CirculationGraph) { + const links = new Map>() + for (const edge of graph.edges) + for (const [from, to] of [ + [edge.from, edge.to], + [edge.to, edge.from], + ]) { + if (!from || !to) continue + const neighbors = links.get(from) ?? new Set() + neighbors.add(to) + links.set(from, neighbors) + } + return links +} + +/** Only outdoor spaces with an actual outdoor route belong to the site's outside. */ +export function exteriorSpaceIds(graph: CirculationGraph) { + const outdoors = (id: string) => { + const kind = graph.nodes.get(id)?.kind + return kind === 'outside' || kind === 'outdoor' + } + return new Set([...reachedFrom(circulationLinks(graph), ['outside'], outdoors)].filter(outdoors)) +} + +export function exteriorEntranceEdges(graph: CirculationGraph) { + const exterior = exteriorSpaceIds(graph) + return graph.edges.filter((edge) => exterior.has(edge.from) !== exterior.has(edge.to)) +} + +export function reachedFrom( + links: Map>, + starts: string[], + through: (id: string) => boolean = () => true, +) { + const seen = new Set(starts) + const queue = [...starts] + for (let index = 0; index < queue.length; index++) { + const id = queue[index] + if (!id || !through(id)) continue + for (const neighbor of links.get(id) ?? []) + if (!seen.has(neighbor)) { + seen.add(neighbor) + queue.push(neighbor) + } + } + return seen +} diff --git a/packages/core/src/agent-operations/circulation-non-spaces.ts b/packages/core/src/agent-operations/circulation-non-spaces.ts new file mode 100644 index 0000000000..bf11337fa8 --- /dev/null +++ b/packages/core/src/agent-operations/circulation-non-spaces.ts @@ -0,0 +1,105 @@ +import { area, difference, intersection, union } from '../lib/polygon-boolean' +import type { CirculationGraph, CirculationNonSpace } from './circulation-graph' +import { doorSidePoints, keyOf, type Pt, spaceAt, spaceRegion } from './circulation-spaces' +import type { SceneNodes } from './types' + +/** A space is a void when most of its plan is open air rather than walking floor. */ +const VOID_SHARE = 0.5 + +/** A slab this near a wall of the level hangs off the building; further, it is a floor of its own. */ +const ATTACHED_WITHIN_M = 0.3 + +function pointSegmentDistance(point: Pt, start: Pt, end: Pt) { + const [dx, dz] = [end[0] - start[0], end[1] - start[1]] + const along = dx * dx + dz * dz + const t = along + ? Math.max(0, Math.min(1, ((point[0] - start[0]) * dx + (point[1] - start[1]) * dz) / along)) + : 0 + return Math.hypot(point[0] - (start[0] + t * dx), point[1] - (start[1] + t * dz)) +} + +const cross = (a: Pt, b: Pt, c: Pt) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + +function segmentDistance(a: Pt, b: Pt, c: Pt, d: Pt) { + if (cross(a, b, c) * cross(a, b, d) < 0 && cross(c, d, a) * cross(c, d, b) < 0) return 0 + return Math.min( + pointSegmentDistance(a, c, d), + pointSegmentDistance(b, c, d), + pointSegmentDistance(c, a, b), + pointSegmentDistance(d, a, b), + ) +} + +function attachedToWall(polygon: readonly Pt[], walls: readonly [Pt, Pt][]) { + return walls.some(([start, end]) => + polygon.some((point, index) => { + const next = polygon[(index + 1) % polygon.length] + return next ? segmentDistance(start, end, point, next) <= ATTACHED_WITHIN_M : false + }), + ) +} + +/** The spaces a door or a window opens onto, by graph key. */ +function openedOnto(scene: SceneNodes, graph: CirculationGraph) { + const floors = new Map( + graph.floors.map((floor) => [floor.id, floor]), + ) + const keys = new Set() + for (const node of Object.values(scene)) { + if (node.type !== 'door' && node.type !== 'window') continue + const wall = scene[node.wallId ?? node.parentId ?? ''] + const floor = wall?.type === 'wall' ? floors.get(wall.parentId ?? '') : undefined + if (wall?.type !== 'wall' || !floor) continue + for (const point of doorSidePoints(wall, node.position[0])) + keys.add(keyOf(spaceAt(floor, point))) + } + return keys +} + +/** + * The graph's spaces that nobody walks to: a void (a lantern void open through a floor opening, a + * lightwell open to the sky over no floor) and an outdoor slab outside the enclosed footprint (a + * balcony slab) hanging off a wall that no door or window opens onto. They are not destinations, so a missing route + * to one is not a missing route to a room. + */ +export function circulationNonSpaces(scene: SceneNodes, graph: CirculationGraph) { + const result = new Map() + let opened: Set | undefined + for (const node of graph.nodes.values()) { + if (node.kind !== 'room' && node.kind !== 'zone' && node.kind !== 'floor') continue + const floor = graph.floors.find((candidate) => candidate.id === node.levelId) + const region = spaceRegion(scene, graph, node) + if (!(floor && region)) continue + const total = area([region]) + if (total < 1e-6) continue + const cuts = [...floor.voids, ...floor.shafts].map((outer) => ({ outer, holes: [] })) + if (cuts.length && area(intersection(region, cuts)) >= total * VOID_SHARE) { + result.set(node.id, 'void') + continue + } + const source = node.sourceId ? scene[node.sourceId] : undefined + // A floorless room is a named unmeasured limit (hasFloor false), not open sky. + if (source?.type === 'zone' && source.hasFloor !== false && source.hasCeiling === false) { + const walking = difference( + union(floor.slabs.map((slab) => ({ outer: slab.polygon, holes: slab.holes }))), + cuts, + ) + if (area(intersection(region, walking)) < total * VOID_SHARE) result.set(node.id, 'void') + continue + } + const slab = + node.kind === 'floor' && !node.sourceId + ? floor.slabs.find((candidate) => node.id === `floor:${floor.id}:${candidate.id}`) + : undefined + if ( + !slab || + !floor.interior.length || + area(intersection(region, floor.interior)) > 1e-6 || + !attachedToWall(slab.polygon, floor.walls) + ) + continue + opened ??= openedOnto(scene, graph) + if (!opened.has(node.id)) result.set(node.id, 'outdoor-slab') + } + return result +} diff --git a/packages/core/src/agent-operations/circulation-spaces.ts b/packages/core/src/agent-operations/circulation-spaces.ts new file mode 100644 index 0000000000..e7de2e4a14 --- /dev/null +++ b/packages/core/src/agent-operations/circulation-spaces.ts @@ -0,0 +1,522 @@ +import { + createFloorOpeningIndex, + type FloorOpeningIndex, + openingsForSurface, +} from '../lib/floor-opening-intent' +import { groundLevelOf } from '../lib/ground-level' +import { + area as clippedArea, + difference, + intersection, + type MultiPolygon, + union, +} from '../lib/polygon-boolean' +import { polygonInteriorPoint } from '../lib/polygon-label' +import { extractRooms } from '../lib/space-detection' +import type { AnyNode, AnyNodeId, ElevatorNode, LevelNode, WallNode } from '../schema' +import { getLevelElevations } from '../services/storey' +import { + getWallCurveFrameAt, + getWallCurveLength, + isCurvedWall, + sampleWallCenterline, +} from '../systems/wall/wall-curve' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import type { CirculationGraph, CirculationNode } from './circulation-graph' +import { pointInPolygon } from './plan-geometry' +import { queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +export type Pt = [number, number] +export type Space = + | { kind: 'outside' } + | { kind: 'open-air' } + | { kind: 'void' } + | { kind: 'shaft' } + | { kind: 'outdoor'; key: string; area: number } + | { kind: 'zone'; key: string; area: number; apartment?: string } + | { kind: 'floor'; key: string } + +export type Floor = { + elevation: number + groundElevation: number + id: LevelNode['id'] + name: string + ground: boolean + /** A floor under the ground line of its building: a basement, whose doors open onto earth. */ + belowGround: boolean + slabs: { + id: string + polygon: Pt[] + holes: Pt[][] + elevation: number + outdoor: boolean + }[] + interior: MultiPolygon + voids: Pt[][] + shafts: Pt[][] + zones: { + id: string + polygon: Pt[] + holes: Pt[][] + area: number + outdoor: boolean + elevation: number + apartment?: string + }[] + pockets: { polygon: Pt[]; area: number }[] + walls: [Pt, Pt][] +} + +export const area = (polygon: readonly Pt[]) => + Math.abs( + polygon.reduce((sum, [x, z], index) => { + const next = polygon[(index + 1) % polygon.length] + return next ? sum + x * next[1] - next[0] * z : sum + }, 0), + ) / 2 +export const rotate = ([x, z]: Pt, rotation: number): Pt => [ + x * Math.cos(rotation) + z * Math.sin(rotation), + -x * Math.sin(rotation) + z * Math.cos(rotation), +] +const cross = (origin: Pt, start: Pt, end: Pt) => + (start[0] - origin[0]) * (end[1] - origin[1]) - (start[1] - origin[1]) * (end[0] - origin[0]) +const touches = (point: Pt, start: Pt, end: Pt) => + Math.abs(cross(start, end, point)) < 1e-9 && + point[0] >= Math.min(start[0], end[0]) - 1e-9 && + point[0] <= Math.max(start[0], end[0]) + 1e-9 && + point[1] >= Math.min(start[1], end[1]) - 1e-9 && + point[1] <= Math.max(start[1], end[1]) + 1e-9 +const segmentsCross = (from: Pt, to: Pt, start: Pt, end: Pt) => + (cross(from, to, start) * cross(from, to, end) < 0 && + cross(start, end, from) * cross(start, end, to) < 0) || + touches(start, from, to) || + touches(end, from, to) || + touches(from, start, end) || + touches(to, start, end) +export const walkable = (space: Space) => + space.kind === 'zone' || + space.kind === 'floor' || + space.kind === 'outside' || + space.kind === 'outdoor' +export const keyOf = (space: Space) => + space.kind === 'zone' || space.kind === 'floor' || space.kind === 'outdoor' + ? space.key + : space.kind +export const crossesWall = (floor: Floor, from: Pt, to: Pt) => + floor.walls.some(([start, end]) => segmentsCross(from, to, start, end)) + +export const liftOrigin = (lift: ElevatorNode): Pt => [lift.position[0], lift.position[2]] +function shaftOf(lift: ElevatorNode): Pt[] { + const [cx, cz] = liftOrigin(lift) + const [halfWidth, halfDepth] = [ + (lift.shaftWidth ?? lift.width) / 2, + (lift.shaftDepth ?? lift.depth) / 2, + ] + return ( + [ + [-halfWidth, -halfDepth], + [halfWidth, -halfDepth], + [halfWidth, halfDepth], + [-halfWidth, halfDepth], + ] as Pt[] + ).map((corner) => { + const [x, z] = rotate(corner, lift.rotation ?? 0) + return [cx + x, cz + z] + }) +} +function liftService(nodes: SceneNodes) { + return (lift: ElevatorNode, levelId: string) => { + const level = nodes[levelId], + from = nodes[lift.fromLevelId ?? ''], + to = nodes[lift.toLevelId ?? ''] + if (level?.type !== 'level' || from?.type !== 'level' || to?.type !== 'level') return false + if (level.parentId !== from.parentId || level.parentId !== to.parentId) return false + return ( + level.level >= Math.min(from.level, to.level) && + level.level <= Math.max(from.level, to.level) && + !(lift.disabledLevelIds ?? []).includes(levelId) + ) + } +} +function zonesOf(on: AnyNode[], apartmentOfZone: Map) { + const zones = on + .filter((node) => node.type === 'zone' && node.polygon.length >= 3) + .flatMap((zone) => { + if (zone.type !== 'zone') return [] + return [ + { + id: zone.id as string, + polygon: zone.polygon, + holes: zone.holes ?? [], + area: area(zone.polygon) - (zone.holes ?? []).reduce((sum, hole) => sum + area(hole), 0), + outdoor: false, + elevation: 0, + apartment: apartmentOfZone.get(zone.id), + }, + ] + }) + // Nested room zones inherit their enclosing apartment's membership: the apartment that holds + // most of the room. A room beside it holds nothing of it, even where the room's vertex average + // falls inside (an arc's samples pull it across the arc). + const shape = (zone: Floor['zones'][number]) => ({ outer: zone.polygon, holes: zone.holes }) + for (const zone of zones) { + if (zone.apartment) continue + zone.apartment = zones.find( + (other) => + other.apartment && + other.area > zone.area && + clippedArea(intersection(shape(zone), shape(other))) > zone.area / 2, + )?.apartment + } + return zones.filter((zone) => { + const smaller = zones.filter((other) => other.area < zone.area) + return ( + !smaller.length || + difference( + { outer: zone.polygon, holes: zone.holes }, + smaller.map((other) => ({ outer: other.polygon, holes: other.holes })), + ).length > 0 + ) + }) +} +function wallSegments(walls: WallNode[]): [Pt, Pt][] { + return walls.flatMap((wall) => { + const points = sampleWallCenterline(wall, isCurvedWall(wall) ? 24 : 1).map( + ({ x, y }): Pt => [x, y], + ) + return points.slice(1).flatMap((point, index): [Pt, Pt][] => { + const previous = points[index] + return previous ? [[previous, point]] : [] + }) + }) +} +type FloorContext = { + apartmentOfZone: Map + elevators: ElevatorNode[] + serves: ReturnType + openings: FloorOpeningIndex + groundByBuilding: Map + belowGround: Set + elevations: ReturnType +} +function enclosedFootprint(on: AnyNode[], walls: WallNode[]) { + const pockets = extractRooms(walls).map((room) => ({ + polygon: room.referencePolygon as Pt[], + area: area(room.referencePolygon as Pt[]), + })) + const courts = on.filter( + (node) => node.type === 'zone' && node.hasFloor === false && node.hasCeiling === false, + ) + const declared = on.flatMap((node) => + node.type === 'zone' && + node.hasFloor !== false && + (node.enclosureStatus === 'enclosed' || (node.boundarySeparatorIds?.length ?? 0) > 0) + ? [{ outer: node.polygon, holes: node.holes ?? [] }] + : [], + ) + const enclosed = pockets.length + ? union([...pockets.map((pocket) => pocket.polygon), ...declared]) + : union( + on.flatMap((node) => + node.type === 'zone' && (node.hasFloor !== false || node.hasCeiling !== false) + ? [{ outer: node.polygon, holes: node.holes ?? [] }] + : [], + ), + ) + const interior = difference( + enclosed, + courts.flatMap((node) => + node.type === 'zone' ? [{ outer: node.polygon, holes: node.holes ?? [] }] : [], + ), + ) + return { pockets, interior, enclosed } +} + +function outdoorZone( + nodes: SceneNodes, + zone: ReturnType[number], + slabs: Floor['slabs'], + outside: boolean, + groundElevation: number, + elevation: number, +) { + const source = nodes[zone.id] + const outdoor = + outside || (source?.type === 'zone' && source.hasFloor === false && source.hasCeiling === false) + const surfaceElevation = outdoorElevation( + slabs, + polygonInteriorPoint(zone, true), + groundElevation, + ) + return { + ...zone, + outdoor, + elevation: outdoor ? surfaceElevation : elevation, + } +} + +function walkingFloor(slabs: Extract[], interior: MultiPolygon) { + const authored = slabs.find((slab) => slab.plateRole === 'base') + if (authored) return authored + let best = slabs[0] + let largest = 0 + for (const slab of slabs) { + if (slab.support === 'open') continue + const overlap = clippedArea( + intersection({ outer: slab.polygon, holes: slab.holes ?? [] }, interior), + ) + if (overlap > largest) { + best = slab + largest = overlap + } + } + return best +} + +function floorOf(nodes: SceneNodes, level: LevelNode, context: FloorContext): Floor { + const on = queryNodes(nodes, { parentId: level.id }) + const slabs = on.filter((node) => node.type === 'slab') + const walls = on.filter((node): node is WallNode => node.type === 'wall') + const { pockets, interior, enclosed } = enclosedFootprint(on, walls) + const base = walkingFloor(slabs, interior) + const ground = level.id === context.groundByBuilding.get(level.parentId) + const groundElevation = context.elevations.get(level.id)?.baseY ?? 0 + const elevation = groundElevation + (base?.elevation ?? 0) + // An open-supported floor (a porch deck, a cantilevered deck, a bridge) outside the enclosed + // footprint is outdoor walking ground at its own elevation, on any level, whether or not the + // house is enclosed yet. The rest are outdoor only on the ground floor, outside an enclosed + // footprint. + const outdoor = (polygon: Pt[], holes: Pt[][], open = false) => + (open || (ground && enclosed.length > 0)) && + clippedArea(intersection({ outer: polygon, holes }, interior)) < 1e-6 + const surfaces = slabs.map((slab) => ({ + id: slab.id, + polygon: slab.polygon, + holes: slab.holes ?? [], + elevation: groundElevation + slab.elevation, + outdoor: outdoor(slab.polygon, slab.holes ?? [], slab.support === 'open'), + })) + const zones = zonesOf(on, context.apartmentOfZone).map((zone) => + ground + ? outdoorZone( + nodes, + zone, + surfaces, + outdoor(zone.polygon, zone.holes), + groundElevation, + elevation, + ) + : { ...zone, elevation }, + ) + return { + id: level.id, + name: level.name ?? `Level ${level.level}`, + elevation, + groundElevation, + ground, + belowGround: context.belowGround.has(level.id), + slabs: surfaces, + interior, + voids: openingsForSurface(nodes, level.id, 'floor', context.openings).map( + (opening) => opening.polygon, + ), + shafts: context.elevators.filter((lift) => context.serves(lift, level.id)).map(shaftOf), + zones, + pockets, + walls: wallSegments(walls), + } +} +export function floorsOf(nodes: SceneNodes) { + const levels = queryNodes(nodes, { type: 'level' }).sort( + (left, right) => left.level - right.level, + ) + const apartments = queryNodes(nodes, { type: 'unit' }).filter( + (node) => node.type === 'unit' && (node.kind ?? 'apartment') === 'apartment', + ) + const apartmentOfZone = new Map( + apartments.flatMap((unit) => + unit.type === 'unit' + ? unit.members.map((member) => [member as string, unit.id as string] as const) + : [], + ), + ) + const elevators = queryNodes(nodes, { type: 'elevator' }) + const serves = liftService(nodes) + // The ground floor is the one the building stands at grade on, the line the underground reads: + // a basement under it has a door onto earth, not an entrance. Without a line (a stack with every + // floor under the ground, levels in no building) it is the lowest floor with a slab. + const groundByBuilding = new Map() + const belowGround = new Set() + for (const level of levels) { + const line = level.parentId + ? groundLevelOf(nodes as Record, level.parentId) + : null + const underLine = line !== null && level.level < line.level.level + if (underLine) belowGround.add(level.id) + if (groundByBuilding.has(level.parentId)) continue + if (queryNodes(nodes, { type: 'slab', parentId: level.id }).length === 0) continue + if (underLine) continue + groundByBuilding.set(level.parentId, level.id) + } + const context = { + apartmentOfZone, + elevators, + serves, + groundByBuilding, + belowGround, + openings: createFloorOpeningIndex(nodes), + elevations: getLevelElevations(nodes), + } + return { + floors: levels.map((level) => floorOf(nodes, level, context)), + apartments, + elevators, + serves, + liftOrigin, + } +} + +export function spaceAt(floor: Floor, point: Pt): Space { + if (floor.shafts.some((shaft) => pointInPolygon(point, shaft, false))) return { kind: 'shaft' } + if (floor.voids.some((hole) => pointInPolygon(point, hole, false))) return { kind: 'void' } + const court = floor.zones.find( + (zone) => + zone.outdoor && + pointInPolygon(point, zone.polygon) && + !zone.holes.some((hole) => pointInPolygon(point, hole, false)), + ) + if (court) return { kind: 'outdoor', key: `zone:${court.id}`, area: court.area } + const covering = floor.slabs.filter((slab) => pointInPolygon(point, slab.polygon)) + if ( + covering.length && + covering.every((slab) => slab.holes.some((hole) => pointInPolygon(point, hole, false))) + ) + return { kind: 'void' } + if (!covering.length) return floor.ground ? { kind: 'outside' } : { kind: 'open-air' } + const garden = covering.find( + (slab) => slab.outdoor && !slab.holes.some((hole) => pointInPolygon(point, hole, false)), + ) + if (garden) + return { + kind: 'outdoor', + key: `outdoor:${garden.id}`, + area: area(garden.polygon) - garden.holes.reduce((sum, hole) => sum + area(hole), 0), + } + let best: Floor['zones'][number] | undefined + for (const zone of floor.zones) + if ( + (!best || zone.area < best.area) && + pointInPolygon(point, zone.polygon) && + !zone.holes.some((hole) => pointInPolygon(point, hole, false)) + ) + best = zone + if (best) + return { + kind: 'zone', + key: `zone:${best.id}`, + area: best.area, + ...(best.apartment ? { apartment: best.apartment } : {}), + } + let pocket = -1 + floor.pockets.forEach((candidate, index) => { + if ( + (pocket < 0 || candidate.area < (floor.pockets[pocket]?.area ?? Infinity)) && + pointInPolygon(point, candidate.polygon) + ) + pocket = index + }) + return { + kind: 'floor', + key: pocket >= 0 ? `floor:${floor.id}:${pocket}` : `floor:${floor.id}:${covering[0]?.id}`, + } +} + +function outdoorElevation(slabs: Floor['slabs'], point: Pt, groundElevation: number) { + const covering = slabs.filter( + (slab) => + pointInPolygon(point, slab.polygon) && + !slab.holes.some((hole) => pointInPolygon(point, hole, false)), + ) + return covering.length ? Math.max(...covering.map((slab) => slab.elevation)) : groundElevation +} + +export function spaceElevation(floor: Floor, space: Space, point?: Pt) { + if (space.kind === 'outside') return floor.groundElevation + if (space.kind !== 'outdoor') return floor.elevation + if (point) return outdoorElevation(floor.slabs, point, floor.groundElevation) + return ( + floor.zones.find((zone) => `zone:${zone.id}` === space.key)?.elevation ?? + floor.slabs.find((slab) => `outdoor:${slab.id}` === space.key)?.elevation ?? + floor.groundElevation + ) +} + +export function floorSpaceReader(nodes: SceneNodes) { + const floors = new Map(floorsOf(nodes).floors.map((floor) => [floor.id, floor])) + return (levelId: string, point: Pt): Space | null => { + const floor = floors.get(levelId) + return floor ? spaceAt(floor, point) : null + } +} +export function wallSidesReader(nodes: SceneNodes) { + const floors = new Map(floorsOf(nodes).floors.map((floor) => [floor.id, floor])) + return (wall: WallNode, along: number): [Space, Space] | null => { + const floor = floors.get(wall.parentId ?? '') + return floor ? doorSides(floor, wall, along) : null + } +} +export function doorFrame(wall: WallNode, along: number) { + return getWallCurveFrameAt(wall, along / (getWallCurveLength(wall) || 1)) +} +export function doorSidePoints(wall: WallNode, along: number): [Pt, Pt] { + const frame = doorFrame(wall, along) + const offsets = getWallFaceOffsets(wall) + const at = (offset: number): Pt => [ + frame.point.x + frame.normal.x * offset, + frame.point.y + frame.normal.y * offset, + ] + return [at(offsets.a + 0.03), at(offsets.b - 0.03)] +} +function doorFaceSpace( + floor: Floor, + centre: Pt, + normal: Pt, + offset: number, + direction: 1 | -1, +): Space { + const probe = (distance: number): Pt => [ + centre[0] + normal[0] * (offset + direction * distance), + centre[1] + normal[1] * (offset + direction * distance), + ] + const near = probe(0.03), + far = probe(0.4) + const nearest = spaceAt(floor, near), + beyond = spaceAt(floor, far) + if (crossesWall(floor, near, far)) return nearest + // Keep the original landing-hazard check without jumping across another room's wall. + if (beyond.kind === 'shaft' || beyond.kind === 'void') return beyond + return nearest.kind === 'floor' ? beyond : nearest +} +export function doorSides(floor: Floor, wall: WallNode, along: number): [Space, Space] { + const frame = doorFrame(wall, along) + const offsets = getWallFaceOffsets(wall) + const centre: Pt = [frame.point.x, frame.point.y], + normal: Pt = [frame.normal.x, frame.normal.y] + return [ + doorFaceSpace(floor, centre, normal, offsets.a, 1), + doorFaceSpace(floor, centre, normal, offsets.b, -1), + ] +} + +export function spaceRegion(scene: SceneNodes, graph: CirculationGraph, node: CirculationNode) { + const source = node.sourceId ? scene[node.sourceId] : undefined + if (source?.type === 'zone' || source?.type === 'slab') + return { outer: source.polygon, holes: source.holes ?? [] } + if (node.kind !== 'floor') return undefined + const floor = graph.floors.find((floor) => floor.id === node.levelId) + const pocket = floor?.pockets.find((_, index) => node.id === `floor:${floor.id}:${index}`) + if (pocket) return { outer: pocket.polygon, holes: [] } + const slab = floor?.slabs.find((slab) => node.id === `floor:${floor.id}:${slab.id}`) + return slab ? { outer: slab.polygon, holes: slab.holes } : undefined +} diff --git a/packages/core/src/agent-operations/ground-reader.ts b/packages/core/src/agent-operations/ground-reader.ts new file mode 100644 index 0000000000..0c2c5b604e --- /dev/null +++ b/packages/core/src/agent-operations/ground-reader.ts @@ -0,0 +1,32 @@ +import { resolveBuildingForLevel } from '../lib/node-ancestry' +import { heightAt } from '../lib/terrain-field' +import { persistedTerrainFieldOf } from '../lib/terrain-source-persisted' +import type { AnyNode, AnyNodeId, SiteNode } from '../schema' +import { queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +type Pt = [number, number] + +/** + * The terrain under a level's plan point, as a height in the level's building frame, or null when + * the level has no building. A site with no persisted terrain is the flat datum plane. The + * building's own offset and turn put its plan in the site's frame, where the terrain is read. + */ +export function groundReader(nodes: SceneNodes) { + const sites = queryNodes(nodes, { type: 'site' }) + const field = sites.length === 1 ? persistedTerrainFieldOf(sites[0] as SiteNode) : null + return (levelId: string, [x, z]: Pt): number | null => { + const buildingId = resolveBuildingForLevel( + levelId as AnyNodeId, + nodes as Record, + ) + const building = buildingId ? nodes[buildingId] : undefined + if (building?.type !== 'building') return null + const [cos, sin] = [Math.cos(building.rotation[1]), Math.sin(building.rotation[1])] + const [siteX, siteZ] = [ + cos * x + sin * z + building.position[0], + -sin * x + cos * z + building.position[2], + ] + return (field ? heightAt(field, siteX, siteZ) : 0) - building.position[1] + } +} diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index b75fac5f96..e598da8175 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -36,6 +36,7 @@ import type { AgentOperation, AgentOperations } from './types' import { createUnit, listUnits, setUnitMembers } from './units' import { verifyScene } from './verify-scene' import { setWallType } from './wall-type' +import './usage-checks' export * from './achieved' export * from './add-column' diff --git a/packages/core/src/agent-operations/usage-checks.ts b/packages/core/src/agent-operations/usage-checks.ts new file mode 100644 index 0000000000..5410bc3a8d --- /dev/null +++ b/packages/core/src/agent-operations/usage-checks.ts @@ -0,0 +1,13 @@ +import { type UsageIssue, usageIssues } from '../spatial/usage-field/findings' +import { sdfChecksOn } from '../spatial/usage-field/flag' +import { registerSceneCheck } from './verify-scene' + +/** + * Passages, turning circles, pockets and wall objects, measured on the real shapes of the scene + * (`spatial/usage-field`). Off unless a host turns usage checks on; off, it adds nothing. + */ +registerSceneCheck({ + name: 'usage', + order: 60, + run: (nodes) => (sdfChecksOn() ? (usageIssues(nodes) as UsageIssue[]) : []), +}) diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 0204455522..eaf579c5ee 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -19,6 +19,7 @@ import { isCeilingGeometry } from '../services/roof-level' import { isRoofOnStoreyWalls } from '../services/roof-move' import { getStoredLevelHeight, getWallCoveringSlabs, getWallTop } from '../services/storey' import { getStoreyDatum } from '../services/storey-datum' +import type { UsageIssue } from '../spatial/usage-field/findings' import { computeSegmentTransforms, rotateXZ, @@ -103,6 +104,7 @@ export type SceneIssue = } | WallEndShortIssue | WallNearlyAlignedIssue + | UsageIssue /** What verify_scene was asked: its contract's input, which other modules may extend. */ export type VerifySceneInput = Readonly> diff --git a/packages/core/src/hooks/spatial-grid/built-in-floor-placed.ts b/packages/core/src/hooks/spatial-grid/built-in-floor-placed.ts new file mode 100644 index 0000000000..bf5f26eb43 --- /dev/null +++ b/packages/core/src/hooks/spatial-grid/built-in-floor-placed.ts @@ -0,0 +1,294 @@ +import type { ProceduralItemNode } from '../../procedural-items/node' +import { proceduralFootprint } from '../../procedural-items/query' +import { nodeRegistry } from '../../registry/registry' +import type { FloorPlacedConfig, FloorPlacedFootprint } from '../../registry/types' +import type { + AnyNode, + AnyNodeId, + BlockNode, + CabinetModuleNode, + CabinetNode, + ColumnNode, + DuctTerminalNode, + HvacEquipmentNode, + ItemNode, + ShelfNode, + StairNode, +} from '../../schema' +import { getScaledDimensions } from '../../schema/nodes/item' +import { getStairFloorPlacedFootprints } from '../../systems/stair/stair-floor-footprints' + +// How each built-in kind stands on its floor: the `floorPlaced` capability its node definition +// declares (the definitions reference these very objects), kept in core so a host that loads no +// node definitions (the MCP lanes) elects a node's support exactly as the editor does. + +type Nodes = Readonly> +type Vec3 = [number, number, number] + +const yaw = (rotation: number): Vec3 => [0, rotation, 0] + +const ROUND_CROSS_SECTIONS = new Set([ + 'round', + 'octagonal', + 'sixteen-sided', +]) + +/** A column's plan half-extents: its shaft, or its widest brace. */ +export function columnFootprintHalf(n: ColumnNode): { halfX: number; halfZ: number } { + if (n.source) return { halfX: n.width / 2, halfZ: n.depth / 2 } + if (n.supportStyle === 'vertical') { + if (ROUND_CROSS_SECTIONS.has(n.crossSection)) return { halfX: n.radius, halfZ: n.radius } + if (n.crossSection === 'square') return { halfX: n.width / 2, halfZ: n.width / 2 } + return { halfX: n.width / 2, halfZ: n.depth / 2 } + } + return { + halfX: + Math.max(n.width, n.braceWidth ?? 0, n.braceBottomSpread ?? 0, n.braceTopSpread ?? 0) / 2, + halfZ: Math.max(n.depth, n.braceDepth ?? 0) / 2, + } +} + +/** A block's local bounds from its topology. */ +export function blockBounds(node: BlockNode): { size: Vec3; center: Vec3 } { + const positions = node.topology.vertices.map((vertex) => vertex.position) + if (positions.length === 0) return { size: [0, 0, 0], center: [0, 0, 0] } + const min = [0, 1, 2].map((axis) => Math.min(...positions.map((p) => p[axis] ?? 0))) + const max = [0, 1, 2].map((axis) => Math.max(...positions.map((p) => p[axis] ?? 0))) + return { + size: [0, 1, 2].map((axis) => (max[axis] ?? 0) - (min[axis] ?? 0)) as Vec3, + center: [0, 1, 2].map((axis) => ((min[axis] ?? 0) + (max[axis] ?? 0)) / 2) as Vec3, + } +} + +const BLOCK_ON_FLOOR_MAX_BOTTOM = 0.1 +const BLOCK_ON_FLOOR_MIN_TOP = 0.01 + +/** + * Floor collision is for blocks standing on the floor. Soffits, vaults, gutters and mantels hang + * above floor placements, and foundation pads sit under the floor, so neither blocks furniture + * nor gets refused when moved. + */ +export function blockRestsOnFloor(node: BlockNode): boolean { + const { size, center } = blockBounds(node) + const bottom = node.position[1] + center[1] - size[1] / 2 + const top = node.position[1] + center[1] + size[1] / 2 + return bottom <= BLOCK_ON_FLOOR_MAX_BOTTOM && top > BLOCK_ON_FLOOR_MIN_TOP +} + +function blockFootprintPosition(node: BlockNode, center: Vec3): Vec3 { + const cos = Math.cos(node.rotation) + const sin = Math.sin(node.rotation) + return [ + node.position[0] + center[0] * cos + center[2] * sin, + node.position[1], + node.position[2] - center[0] * sin + center[2] * cos, + ] +} + +function clampShelfDim(value: unknown, lo: number, hi: number, fallback: number): number { + const v = typeof value === 'number' && Number.isFinite(value) ? value : fallback + return Math.min(Math.max(v, lo), hi) +} + +/** A shelf with every dimension held inside the range the shelf tool allows. */ +export function sanitizeShelfDimensions(node: ShelfNode): ShelfNode { + return { + ...node, + width: clampShelfDim(node.width, 0.3, 3.0, 1.2), + depth: clampShelfDim(node.depth, 0.1, 1.0, 0.3), + thickness: clampShelfDim(node.thickness, 0.01, 0.1, 0.04), + height: clampShelfDim(node.height, 0.05, 2.5, 0.9), + rows: Math.round(clampShelfDim(node.rows, 1, 8, 1)), + columns: Math.round(clampShelfDim(node.columns, 1, 6, 1)), + } +} + +type CabinetHeightFields = Pick< + CabinetNode, + 'showPlinth' | 'plinthHeight' | 'carcassHeight' | 'withCountertop' | 'countertopThickness' +> + +/** A cabinet's height from the floor: plinth, carcass and countertop. */ +export function totalCabinetHeight(node: CabinetHeightFields) { + return ( + (node.showPlinth ? node.plinthHeight : 0) + + node.carcassHeight + + (node.withCountertop ? node.countertopThickness : 0) + ) +} + +/** A module's height, with a top cabinet or trim above it. */ +export function cabinetModuleTotalHeight(node: CabinetModuleNode): number { + return ( + totalCabinetHeight(node) + + (node.topFinish === 'top-cabinet' || node.topFinish === 'trim' ? node.topFinishHeight : 0) + ) +} + +/** A cabinet nested in another stands on that one, not on the floor. */ +export function hasCabinetParentId(node: Pick): boolean { + const parentId = node.parentId + return ( + typeof parentId === 'string' && + (parentId.startsWith('cabinet_') || parentId.startsWith('cabinet-module_')) + ) +} + +function composedPose(parent: Vec3, parentYaw: number, child: readonly number[]): Vec3 { + const cos = Math.cos(parentYaw) + const sin = Math.sin(parentYaw) + const [x = 0, y = 0, z = 0] = child + return [parent[0] + x * cos + z * sin, parent[1] + y, parent[2] - x * sin + z * cos] +} + +function appendCabinetFootprints( + run: CabinetNode, + nodes: Nodes, + parentPosition: Vec3, + parentYaw: number, + footprints: FloorPlacedFootprint[], +) { + const runPosition = composedPose(parentPosition, parentYaw, run.position) + const runYaw = parentYaw + run.rotation + const children = (run.children ?? []).map((id) => nodes[id as AnyNodeId]) + const modules = children.filter( + (child): child is CabinetModuleNode => child?.type === 'cabinet-module', + ) + for (const module of modules) + footprints.push({ + position: composedPose(runPosition, runYaw, module.position), + dimensions: [module.width, cabinetModuleTotalHeight(module), module.depth], + rotation: yaw(runYaw + module.rotation), + }) + if (!modules.length) + footprints.push({ + position: runPosition, + dimensions: [run.width, totalCabinetHeight(run), run.depth], + rotation: yaw(runYaw), + }) + for (const child of children) + if (child?.type === 'cabinet') + appendCabinetFootprints(child, nodes, runPosition, runYaw, footprints) +} + +/** A cabinet run's footprints: one per module, through any runs nested in it. */ +export function cabinetFloorPlacedFootprints( + node: CabinetNode, + nodes?: Nodes, +): FloorPlacedFootprint[] { + if (!nodes) + return [ + { + position: [...node.position], + dimensions: [node.width, totalCabinetHeight(node), node.depth], + rotation: yaw(node.rotation), + }, + ] + const footprints: FloorPlacedFootprint[] = [] + appendCabinetFootprints(node, nodes, [0, 0, 0], 0, footprints) + return footprints +} + +type BuiltInFloorPlacedKind = + | 'item' + | 'column' + | 'block' + | 'shelf' + | 'stair' + | 'spawn' + | 'duct-terminal' + | 'hvac-equipment' + | 'procedural-item' + | 'cabinet' + | 'cabinet-module' + +export const BUILT_IN_FLOOR_PLACED: Readonly> = { + item: { + footprint: (node) => { + const item = node as ItemNode + return { dimensions: getScaledDimensions(item), rotation: item.rotation } + }, + applies: (node) => !(node as ItemNode).asset.attachTo, + collides: true, + }, + column: { + footprint: (node) => { + const column = node as ColumnNode + const { halfX, halfZ } = columnFootprintHalf(column) + // Column stores Y rotation as a scalar; the slab-overlap query expects the full Euler tuple. + return { dimensions: [halfX * 2, column.height, halfZ * 2], rotation: yaw(column.rotation) } + }, + collides: true, + }, + block: { + footprint: (node) => { + const block = node as BlockNode + const { size, center } = blockBounds(block) + return { + dimensions: size, + position: blockFootprintPosition(block, center), + rotation: yaw(block.rotation), + } + }, + collides: (node) => blockRestsOnFloor(node as BlockNode), + }, + shelf: { + footprint: (node) => { + const shelf = sanitizeShelfDimensions(node as ShelfNode) + return { dimensions: [shelf.width, shelf.height, shelf.depth], rotation: shelf.rotation } + }, + collides: true, + }, + stair: { + footprints: (node, ctx) => + ctx ? getStairFloorPlacedFootprints(node as StairNode, ctx.nodes) : [], + }, + spawn: { + footprint: () => ({ dimensions: [0.6, 1.8, 0.6], rotation: [0, 0, 0] }), + }, + 'duct-terminal': { + footprint: (node) => { + const terminal = node as DuctTerminalNode + return { dimensions: [terminal.width, 0, terminal.depth], rotation: yaw(terminal.rotation) } + }, + applies: (node) => (node as DuctTerminalNode).mount === 'floor', + }, + 'hvac-equipment': { + footprint: (node) => { + const unit = node as HvacEquipmentNode + return { dimensions: [unit.width, unit.height, unit.depth], rotation: yaw(unit.rotation) } + }, + }, + 'procedural-item': { + footprint: (node) => proceduralFootprint(node as unknown as ProceduralItemNode), + applies: (node) => !(node as unknown as ProceduralItemNode).recipe.mounting, + collides: true, + }, + cabinet: { + applies: (node) => !hasCabinetParentId(node as CabinetNode), + footprints: (node, ctx) => cabinetFloorPlacedFootprints(node as CabinetNode, ctx?.nodes), + collides: true, + }, + 'cabinet-module': { + applies: (node) => !hasCabinetParentId(node as CabinetModuleNode), + footprint: (node) => { + const module = node as CabinetModuleNode + return { + dimensions: [module.width, cabinetModuleTotalHeight(module), module.depth], + rotation: yaw(module.rotation), + } + }, + collides: true, + }, +} + +/** + * A kind's `floorPlaced` capability: the one its loaded definition declares, else the built-in + * kind's, so support is elected the same with or without node definitions. + */ +export function floorPlacedOf(type: string): FloorPlacedConfig | undefined { + return ( + nodeRegistry.get(type)?.capabilities?.floorPlaced ?? + (BUILT_IN_FLOOR_PLACED as Readonly>)[type] + ) +} diff --git a/packages/core/src/schema/geometry-source.ts b/packages/core/src/schema/geometry-source.ts index 583986cfac..02346b15e5 100644 --- a/packages/core/src/schema/geometry-source.ts +++ b/packages/core/src/schema/geometry-source.ts @@ -60,6 +60,28 @@ export const GeometryScriptParamSpec = z.object({ }) export type GeometryScriptParamSpec = z.infer +const planPoint = z.tuple([finite, finite]) +const planRing = z.array(planPoint).min(3) + +/** + * What a build occupies in plan, height band by height band, for the usage checks (passages, + * pockets, wall protrusions): `y0`..`y1` in the artifact's frame and the plan outlines (x, z) of + * everything it has in that band, traced from a conservative raster of its meshes, so an outline + * is never inside the build and at most `tolerance` metres outside it. Written by the compiler + * only when usage checks are on, so it is absent from older artifacts. + */ +export const GeometryShape = z.object({ + tolerance: finite, + bands: z.array( + z.object({ + y0: finite, + y1: finite, + polygons: z.array(z.object({ outer: planRing, holes: z.array(planRing).optional() })), + }), + ), +}) +export type GeometryShape = z.infer + /** * What the compiler read from the script's output, by naming convention: * `part:` objects, `slot_` materials, `anchor:` empties, lights @@ -149,6 +171,7 @@ export const GeometryArtifactManifest = z.object({ .optional(), cutout: z.boolean().default(false), collider: z.boolean().default(false), + shape: GeometryShape.optional(), triangles: z.number().int().nonnegative(), /** * Built for a room's floor or a wall face: the share of it (less its holes) the build covers, diff --git a/packages/core/src/schema/index.ts b/packages/core/src/schema/index.ts index 45789540a6..03e1314068 100644 --- a/packages/core/src/schema/index.ts +++ b/packages/core/src/schema/index.ts @@ -71,6 +71,7 @@ export { GeometryScriptParamSpec, GeometryScriptParamValue, GeometryScriptSource, + GeometryShape, isGeometryScriptMimeType, LightGlow, LightSpot, diff --git a/packages/core/src/spatial/usage-field/beds.ts b/packages/core/src/spatial/usage-field/beds.ts new file mode 100644 index 0000000000..e1c879bbe3 --- /dev/null +++ b/packages/core/src/spatial/usage-field/beds.ts @@ -0,0 +1,379 @@ +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { area, intersection, type Ring } from '../../lib/polygon-boolean' +import type { ItemNode, ZoneNode } from '../../schema' +import type { UsageIssue } from './findings' +import { m, nameOf, quote, unique } from './labels' +import { type Obstacle, obstaclesInBand, rayHit } from './obstacles' +import { boxesMeet, isBed, ringBox, roomAt } from './pieces' +import type { Prism, UsageShapes } from './types' +import type { Nodes } from './walls' + +export type BedClass = 'single' | 'double' | 'queen' | 'king' +/** The footprint's short side (frame included) that makes a class, m: a retailer's Australian mattress widths plus a frame of 10 to 20 cm. */ +export const BED_CLASS_FROM_M: [BedClass, number][] = [ + ['king', 1.75], + ['queen', 1.5], + ['double', 1.2], + ['single', 0], +] +/** A bed of each class as a footprint with its frame and headboard (width, length), m. */ +const BED_FOOTPRINT_M: Record = { + king: [1.95, 2.15], + queen: [1.65, 2.15], + double: [1.5, 2.1], + single: [1.1, 2.05], +} +/** A person gets by with this much on a side or at the foot (one unit of passage); UK M4(2) asks 0.75 m, the Scottish draft 0.80 m beside the bed. */ +export const BED_ACCESS_M = 0.6 +/** The room's short side under which a bed is small for it, from a retailer's recommended minimum rooms (3.0 x 4.0 m queen, 3.2 x 4.2 m king), m. */ +export const BED_ROOM_SHORT_M: Partial> = { queen: 3.0, king: 3.2 } +const FEET_FROM_M = 0.03 +const FEET_TO_M = 0.7 +const RAY_MAX_M = 3 + +export type BedMeasure = { + id: string + name: string + levelId: string + room: { id: string; name: string } | null + widthM: number + lengthM: number + sizeClass: BedClass + /** Free space beside the bed (median over the foot-ward three quarters of its sides) and at its foot, m. */ + left: number + right: number + foot: number + roomShortSideM: number | null + at: [number, number] +} + +export const bedClassOf = (width: number): BedClass => + BED_CLASS_FROM_M.find(([, from]) => width >= from)![0] + +const median = (values: number[]) => + [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)] ?? RAY_MAX_M + +/** The smallest rectangle round an outline (180 directions): its centre, its axes, its long and short side. */ +function boundingRectangle(points: Ring) { + let best: { u0: number; u1: number; v0: number; v1: number; c: number; s: number } | null = null + let bestArea = Number.POSITIVE_INFINITY + for (let k = 0; k < 180; k++) { + const a = (k * Math.PI) / 180 + const c = Math.cos(a) + const s = Math.sin(a) + let u0 = Number.POSITIVE_INFINITY + let u1 = Number.NEGATIVE_INFINITY + let v0 = Number.POSITIVE_INFINITY + let v1 = Number.NEGATIVE_INFINITY + for (const [x, z] of points) { + const u = x * c + z * s + const v = -x * s + z * c + u0 = Math.min(u0, u) + u1 = Math.max(u1, u) + v0 = Math.min(v0, v) + v1 = Math.max(v1, v) + } + const size = (u1 - u0) * (v1 - v0) + if (size < bestArea) { + bestArea = size + best = { u0, u1, v0, v1, c, s } + } + } + const r = best! + const du = r.u1 - r.u0 + const dv = r.v1 - r.v0 + const at = (u: number, v: number): [number, number] => [u * r.c - v * r.s, u * r.s + v * r.c] + const longIsU = du >= dv + return { + centre: at((r.u0 + r.u1) / 2, (r.v0 + r.v1) / 2), + long: longIsU ? ([r.c, r.s] as [number, number]) : ([-r.s, r.c] as [number, number]), + across: longIsU ? ([-r.s, r.c] as [number, number]) : ([r.c, r.s] as [number, number]), + length: Math.max(du, dv), + width: Math.min(du, dv), + } +} + +/** One bed's size class and free space, from its own prisms and those of its level (the bed itself may be a candidate that is not in the scene). */ +export function measureBedPrisms( + nodes: Nodes, + levelId: string, + bed: { id: string; name: string }, + own: Prism[], + prisms: Prism[], +): BedMeasure | null { + if (!own.length) return null + const floor = Math.min(...own.map((prism) => prism.z0)) + const outline = own + .filter((prism) => prism.z0 < floor + 0.9) + .flatMap((prism) => prism.outer as Ring) + if (outline.length < 3) return null + const rect = boundingRectangle(outline) + const band = { z0: floor + FEET_FROM_M, z1: floor + FEET_TO_M } + // what lies on or under the bed (bedding, a throw) is not an obstacle beside it + const overlapsBed = (prism: Prism) => + own.some( + (piece) => + boxesMeet(ringBox(piece.outer), ringBox(prism.outer)) && + area( + intersection( + { outer: piece.outer, holes: piece.holes }, + { outer: prism.outer, holes: prism.holes }, + ), + ) > 1e-4, + ) + const others = obstaclesInBand( + prisms, + band, + undefined, + (prism) => prism.nodeId === bed.id || overlapsBed(prism), + ) + const wallObstacles = obstaclesInBand( + prisms.filter((prism) => prism.kind === 'wall'), + band, + ) + const ends: [number, number][] = [ + [ + rect.centre[0] + (rect.long[0] * rect.length) / 2, + rect.centre[1] + (rect.long[1] * rect.length) / 2, + ], + [ + rect.centre[0] - (rect.long[0] * rect.length) / 2, + rect.centre[1] - (rect.long[1] * rect.length) / 2, + ], + ] + const wallGap = (p: [number, number]) => + Math.min(...wallObstacles.map((o) => rayDistance(o, p)), Number.POSITIVE_INFINITY) + const headFirst = wallGap(ends[0]!) <= wallGap(ends[1]!) + const head = headFirst ? ends[0]! : ends[1]! + const foot = headFirst ? ends[1]! : ends[0]! + const out2: [number, number] = [foot[0] - head[0], foot[1] - head[1]] + const outLen = Math.hypot(out2[0], out2[1]) || 1 + const toFoot: [number, number] = [out2[0] / outLen, out2[1] / outLen] + const steps = Math.max(4, Math.round(rect.length / 0.05)) + const along = (t: number): [number, number] => [ + foot[0] - toFoot[0] * rect.length * t, + foot[1] - toFoot[1] * rect.length * t, + ] + const sideRays = (sign: 1 | -1) => { + const dir: [number, number] = [rect.across[0] * sign, rect.across[1] * sign] + const hits: number[] = [] + for (let i = 0; i <= Math.round(steps * 0.75); i++) { + const p = along(i / steps) + hits.push( + rayHit( + [p[0] + dir[0] * (rect.width / 2), p[1] + dir[1] * (rect.width / 2)], + dir, + others, + RAY_MAX_M, + ), + ) + } + return median(hits) + } + const footHits: number[] = [] + for (let i = 0; i <= 20; i++) { + const across = (i / 20 - 0.5) * rect.width + footHits.push( + rayHit( + [foot[0] + rect.across[0] * across, foot[1] + rect.across[1] * across], + toFoot, + others, + RAY_MAX_M, + ), + ) + } + const room = roomAt(nodes, levelId, rect.centre) + const zone = room ? (nodes[room.id] as ZoneNode) : null + const bounds = zone ? ringBox(zone.polygon as Ring) : null + return { + id: bed.id, + name: bed.name, + levelId, + room, + widthM: Math.round(rect.width * 100) / 100, + lengthM: Math.round(rect.length * 100) / 100, + sizeClass: bedClassOf(rect.width), + left: Math.round(sideRays(1) * 100) / 100, + right: Math.round(sideRays(-1) * 100) / 100, + foot: Math.round(median(footHits) * 100) / 100, + roomShortSideM: bounds + ? Math.round(Math.min(bounds[2] - bounds[0], bounds[3] - bounds[1]) * 100) / 100 + : null, + at: [Math.round(rect.centre[0] * 100) / 100, Math.round(rect.centre[1] * 100) / 100], + } +} + +/** What leaves a bed tight: the foot under 0.60 m, no side at 0.60 m, a king with one. */ +export function bedTightness(bed: BedMeasure): string[] { + const sides = [bed.left, bed.right].filter((side) => side >= BED_ACCESS_M).length + const reasons: string[] = [] + if (bed.foot < BED_ACCESS_M) reasons.push(`${m(bed.foot)} m at its foot`) + if (sides === 0) + reasons.push(`no side with ${m(BED_ACCESS_M)} m (${m(bed.left)} and ${m(bed.right)} m)`) + else if (bed.sizeClass === 'king' && sides < 2) + reasons.push(`a king with ${m(Math.min(bed.left, bed.right))} m on one side`) + return reasons +} + +/** Every bed of the scene with its size class and the free space round it, measured on the real shapes of the feet band. */ +export function measureBeds(nodes: Nodes, shapes: UsageShapes): BedMeasure[] { + const out: BedMeasure[] = [] + for (const level of shapes.levels) { + const prisms = level.prisms.filter( + (prism) => + !(nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode)), + ) + for (const node of Object.values(nodes)) { + if (!isBed(node)) continue + const own = prisms.filter((prism) => prism.nodeId === node.id) + const bed = measureBedPrisms( + nodes, + level.levelId, + { id: node.id, name: nameOf(nodes, node.id) }, + own, + prisms, + ) + if (bed) out.push(bed) + } + } + return out +} + +/** The distance from a point to an obstacle's outline. */ +function rayDistance(o: Obstacle, p: [number, number]): number { + let best = Number.POSITIVE_INFINITY + for (let k = 0; k < o.edges.length; k += 4) { + const ax = o.edges[k]! + const az = o.edges[k + 1]! + const ex = o.edges[k + 2]! - ax + const ez = o.edges[k + 3]! - az + const l2 = ex * ex + ez * ez + const t = l2 ? Math.max(0, Math.min(1, ((p[0] - ax) * ex + (p[1] - az) * ez) / l2)) : 0 + best = Math.min(best, Math.hypot(p[0] - ax - ex * t, p[1] - az - ez * t)) + } + return best +} + +/** + * A queen or a king bed's room, read the way a person would: free space at the foot, on each side, + * and the room against the size. Guides; never refuses. Tight: the foot under 0.60 m; a king with + * fewer than two sides at 0.60 m; a bed with no side at 0.60 m. Small for its size (information): + * the room's short side under a retailer's recommended minimum. + */ +export function bedIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { + const out: UsageIssue[] = [] + for (const bed of measureBeds(nodes, shapes)) { + if (bed.sizeClass === 'single') continue + const reasons = bedTightness(bed) + const where = bed.room ? ` in ${quote(bed.room.name)}` : '' + const base = { + nodeIds: unique([bed.room?.id, bed.id]), + place: { room: bed.room?.name ?? '', roomId: bed.room?.id ?? bed.levelId, at: bed.at }, + obstacles: [], + approximate: false, + } + if (reasons.length) + out.push({ + ...base, + type: 'usage_bed_clearance', + message: `${quote(bed.name)} (a ${bed.sizeClass}, ${m(bed.widthM)} x ${m(bed.lengthM)} m)${where} leaves ${reasons.join(' and ')}: tight.`, + severity: 'warning', + valueM: Math.min(bed.foot, Math.max(bed.left, bed.right)), + thresholdM: BED_ACCESS_M, + }) + const recommended = BED_ROOM_SHORT_M[bed.sizeClass] + if (recommended && bed.roomShortSideM !== null && bed.roomShortSideM < recommended) + out.push({ + ...base, + type: 'usage_bed_clearance', + message: `${quote(bed.name)} is a ${bed.sizeClass}${where}, a room ${m(bed.roomShortSideM)} m on its short side: retailers recommend ${m(recommended)} m or more for a ${bed.sizeClass}.`, + severity: 'info', + valueM: bed.roomShortSideM, + thresholdM: recommended, + }) + } + return out +} + +/** + * The largest bed class a room can take: one with its head on a wall, 0.60 m at its foot and on at + * least one side (two for a king), clear of every piece and wall. A pure read for placement. + */ +export function bedFit(nodes: Nodes, shapes: UsageShapes, zoneId: string): BedClass | null { + const zone = nodes[zoneId] as ZoneNode | undefined + if (zone?.type !== 'zone') return null + const level = shapes.levels.find((l) => l.levelId === zone.parentId) + if (!level) return null + const polygon = zone.polygon as Ring + const floorY = Math.min(...level.floors.map((f) => f.y), Number.POSITIVE_INFINITY) + const band = { + z0: (Number.isFinite(floorY) ? floorY : 0) + FEET_FROM_M, + z1: (Number.isFinite(floorY) ? floorY : 0) + FEET_TO_M, + } + const blockers = obstaclesInBand( + level.prisms.filter( + (prism) => + !(nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode)), + ), + band, + ) + const centre: [number, number] = [ + polygon.reduce((s, p) => s + p[0], 0) / polygon.length, + polygon.reduce((s, p) => s + p[1], 0) / polygon.length, + ] + for (const [cls] of BED_CLASS_FROM_M) { + const [width, length] = BED_FOOTPRINT_M[cls] + for (let edge = 0; edge < polygon.length; edge++) { + const a = polygon[edge]! + const b = polygon[(edge + 1) % polygon.length]! + const run = Math.hypot(b[0] - a[0], b[1] - a[1]) + if (run < width) continue + const along: [number, number] = [(b[0] - a[0]) / run, (b[1] - a[1]) / run] + let inward: [number, number] = [-along[1], along[0]] + if ((centre[0] - a[0]) * inward[0] + (centre[1] - a[1]) * inward[1] < 0) + inward = [-inward[0], -inward[1]] + const sidesNeeded = cls === 'king' ? 2 : 1 + for (let s = width / 2; s <= run - width / 2 + 1e-9; s += 0.1) { + // the bed against the wall (its back at the wall face: 8 cm off the room's edge), then the strips round it + const at = (u: number, v: number): [number, number] => [ + a[0] + along[0] * (s + u) + inward[0] * (0.08 + v), + a[1] + along[1] * (s + u) + inward[1] * (0.08 + v), + ] + const rect = (u0: number, u1: number, v0: number, v1: number): Ring => [ + at(u0, v0), + at(u1, v0), + at(u1, v1), + at(u0, v1), + ] + const free = (ring: Ring) => { + const box = ringBox(ring) + return !blockers.some( + (o) => + boxesMeet(box, o.aabb) && + area(intersection(ring, { outer: o.prism.outer, holes: o.prism.holes })) > 0.005, + ) + } + const inside = (ring: Ring) => ring.every((p) => pointIn(p, polygon)) + const body = rect(-width / 2, width / 2, 0, length) + const foot = rect(-width / 2, width / 2, length, length + BED_ACCESS_M) + const left = rect(-width / 2 - BED_ACCESS_M, -width / 2, 0, length * 0.75) + const right = rect(width / 2, width / 2 + BED_ACCESS_M, 0, length * 0.75) + if (!(inside(body) && free(body) && inside(foot) && free(foot))) continue + const openSides = [left, right].filter((r) => inside(r) && free(r)).length + if (openSides >= sidesNeeded) return cls + } + } + } + return null +} + +function pointIn(p: [number, number], ring: Ring): boolean { + let inside = false + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, zi] = ring[i]! + const [xj, zj] = ring[j]! + if (zi > p[1] !== zj > p[1] && p[0] < ((xj - xi) * (p[1] - zi)) / (zj - zi) + xi) + inside = !inside + } + return inside +} diff --git a/packages/core/src/spatial/usage-field/blocked.ts b/packages/core/src/spatial/usage-field/blocked.ts new file mode 100644 index 0000000000..feca7524a6 --- /dev/null +++ b/packages/core/src/spatial/usage-field/blocked.ts @@ -0,0 +1,228 @@ +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { resolveLevelId } from '../../lib/node-ancestry' +import { area, intersection, type Ring } from '../../lib/polygon-boolean' +import type { DoorNode, ItemNode, WallNode, WindowNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { getWallLocalFaceZ } from '../../systems/wall/wall-frame' +import { TOLERANCE_M, type UsageIssue } from './findings' +import { cm, nameOf, quote, unique } from './labels' +import { + boxesMeet, + isBed, + isFoliage, + isPiecePrism, + itemText, + narrowestExtent, + ringBox, + roomAt, +} from './pieces' +import type { Prism, UsageShapes } from './types' +import type { Nodes } from './walls' + +/** How far in front of the glass a piece blocks the window: a curtain's depth (m). */ +export const WINDOW_BLOCK_M = 0.15 +/** And the strip beyond it, read as information (m). */ +export const WINDOW_NEAR_M = 0.3 +/** A piece blocks a window from this height above the sill: below it, a sideboard under the sill is fine (m). */ +export const WINDOW_ABOVE_SILL_M = 0.3 +/** Of the window's width, a piece must cover this share to block it. */ +export const WINDOW_COVER = 0.25 +/** A piece this deep in a curtain or blind envelope is in the curtains (m). */ +export const ENVELOPE_M = 0.05 + +const MIN_AREA_M2 = 0.01 +/** What is set at a window by design: a shower, a bath or a tub (its glass or rim is no curtain), a bedside piece or a lamp (its top is a shade, not a wall). */ +const SET_AT_WINDOW = + /shower|bath|(?:^|[^a-z])tub(?![a-z])|bedside|night ?stand|(?:^|[^a-z])lamp(?![a-z])/i +/** What hangs at a window: a free piece named for one is a window treatment that was never put on the window. */ +const CURTAIN = /curtain|drape|blind|shutter|sheer|pelmet|valance/i +export const isSetAtWindow = (text: string): boolean => SET_AT_WINDOW.test(text) + +type Frame = { + wall: WallNode + tx: number + tz: number + nx: number + nz: number + faceZ: number + sign: 1 | -1 +} + +const point = (frame: Frame, along: number, out: number): [number, number] => { + const [sx, sz] = frame.wall.start + return [ + sx + frame.tx * along + frame.nx * (frame.faceZ + frame.sign * out), + sz + frame.tz * along + frame.nz * (frame.faceZ + frame.sign * out), + ] +} + +function roomSides(wall: WallNode): Frame[] { + const [sx, sz] = wall.start + const [ex, ez] = wall.end + const length = Math.hypot(ex - sx, ez - sz) + if (length < 1e-6) return [] + const tx = (ex - sx) / length + const tz = (ez - sz) / length + const base = { wall, tx, tz, nx: -tz, nz: tx } + const sides: Frame[] = [] + // the faces a wall calls exterior are not a room's: a partition (both faces interior) is judged on both + if (wall.frontSide !== 'exterior') + sides.push({ ...base, faceZ: getWallLocalFaceZ(wall, 'a'), sign: 1 }) + if (wall.backSide !== 'exterior') + sides.push({ ...base, faceZ: getWallLocalFaceZ(wall, 'b'), sign: -1 }) + return sides +} + +/** + * What stands in front of an opening. A window: a piece whose top is at least 30 cm above its sill, + * within 15 cm of the glass across a quarter of its width, blocks it (a low sideboard under the sill + * does not); within 30 cm it is information, unless it covers the whole glass, its width and up to its head, + * or is a curtain or blind that stands free (one hosted on the window is its treatment, read as its envelope); a piece 5 cm deep + * in its curtain or blind envelope is in the curtains. A door's swing is read by `doorSwingIssues`. + */ +export function blockedOpeningIssues( + nodes: Nodes, + shapes: UsageShapes, + /** A piece that is not in the scene (yet): only the windows it would stand in front of are read, on its level. */ + candidate?: { levelId: string; prisms: Prism[] }, +): UsageIssue[] { + const out: UsageIssue[] = [] + // a piece of several bands, or a window with two panes, is one finding: the worst reading of each pair + const worst = new Map() + const keep = (key: string, issue: UsageIssue, rank: number) => { + const known = worst.get(key) + if (!known || rank > known.rank) worst.set(key, { issue, rank }) + } + const elevations = getLevelElevations(nodes as never) + for (const level of shapes.levels) { + if (candidate && level.levelId !== candidate.levelId) continue + const baseY = elevations.get(level.levelId)?.baseY ?? 0 + const prisms = level.prisms.filter( + (prism) => + !(nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode)), + ) + const pieces = candidate + ? candidate.prisms + : prisms.filter((prism) => isPiecePrism(prism) && !isFoliage(nodes, prism.nodeId)) + const pieceBoxes = new Map( + pieces.map((prism) => [prism, ringBox(prism.outer)]), + ) + for (const node of Object.values(nodes)) { + if ((node.type !== 'window' && node.type !== 'door') || node.visible === false) continue + const opening = node as WindowNode | DoorNode + const wall = nodes[opening.parentId ?? ''] as WallNode | undefined + if (wall?.type !== 'wall' || resolveLevelId(wall, nodes as never) !== level.levelId) continue + const half = (opening.width ?? 0.9) / 2 + const along = opening.position[0] + const frames = prisms.filter( + (prism) => + prism.nodeId === opening.id && + (prism.kind === 'window-frame' || prism.kind === 'jamb' || prism.kind === 'door-head'), + ) + const glazed = frames.filter((prism) => prism.kind !== 'sill') + const head = frames.length ? Math.max(...frames.map((prism) => prism.z1)) : baseY + 2.1 + const sill = + opening.type === 'door' + ? baseY + : glazed.length + ? Math.min(...glazed.map((prism) => prism.z0)) + : baseY + opening.position[1] - (opening.height ?? 1.2) / 2 + for (const frame of roomSides(wall)) { + const label = quote(nameOf(nodes, opening.id)) + const middle = point(frame, along, 0.4) + const room = roomAt(nodes, level.levelId, middle) + if (opening.type === 'window') { + const zone: Ring = [ + point(frame, along - half, 0), + point(frame, along + half, 0), + point(frame, along + half, WINDOW_NEAR_M), + point(frame, along - half, WINDOW_NEAR_M), + ] + const zoneBox = ringBox(zone) + const envelopes = prisms.filter( + (prism) => prism.kind === 'treatment' && prism.nodeId === opening.id, + ) + for (const piece of pieces) { + if (piece.z1 < sill + WINDOW_ABOVE_SILL_M || piece.z0 > head) continue + if (piece.host?.wallId === wall.id) continue + if (isSetAtWindow(itemText(nodes, piece.nodeId))) continue + if (!boxesMeet(pieceBoxes.get(piece)!, zoneBox)) continue + const meet = intersection({ outer: piece.outer, holes: piece.holes }, zone) + if (area(meet) < MIN_AREA_M2) continue + let nearest = Number.POSITIVE_INFINITY + let low = Number.POSITIVE_INFINITY + let high = Number.NEGATIVE_INFINITY + for (const part of meet) + for (const [x, z] of part.outer) { + const [sx, sz] = wall.start + nearest = Math.min( + nearest, + ((x - sx) * frame.nx + (z - sz) * frame.nz - frame.faceZ) * frame.sign, + ) + const u = (x - sx) * frame.tx + (z - sz) * frame.tz + low = Math.min(low, u) + high = Math.max(high, u) + } + const cover = + Math.max(0, Math.min(high, along + half) - Math.max(low, along - half)) / (2 * half) + if (cover < WINDOW_COVER) continue + nearest = Math.max(0, nearest) + const who = quote(nameOf(nodes, piece.nodeId)) + const tall = piece.z1 - sill >= WINDOW_ABOVE_SILL_M + // a bed head against a window is a design choice, not a defect + const warning = tall && nearest <= WINDOW_BLOCK_M && !isBed(nodes[piece.nodeId]) + // past a curtain's depth, a piece not hosted on the window still shuts it when it is a curtain or blind, or covers all of the glass (its width, and up to its head) + const shuts = + tall && + nearest > WINDOW_BLOCK_M && + !isBed(nodes[piece.nodeId]) && + (CURTAIN.test(itemText(nodes, piece.nodeId)) || + (cover >= 1 - TOLERANCE_M / (2 * half) && piece.z1 >= head - TOLERANCE_M)) + const deepIn = envelopes.reduce((deepest, envelope) => { + if (Math.min(piece.z1, envelope.z1) - Math.max(piece.z0, envelope.z0) < 0.02) + return deepest + const inside = intersection( + { outer: piece.outer, holes: piece.holes }, + { outer: envelope.outer, holes: envelope.holes }, + ) + return area(inside) < MIN_AREA_M2 + ? deepest + : Math.max(deepest, narrowestExtent(inside)) + }, 0) + const inCurtains = deepIn >= ENVELOPE_M + const approximate = + piece.shape === 'approx' || + (inCurtains && envelopes.some((e) => e.shape === 'approx')) + keep( + `${opening.id}|${frame.sign}|${piece.nodeId}`, + { + type: 'usage_opening_blocked', + message: inCurtains + ? `${who} stands ${cm(deepIn)} deep in the curtains or blinds of ${label}${room ? ` in ${quote(room.name)}` : ''} (the window is covered over ${Math.round(cover * 100)} % of its width).` + : `${who} stands ${cm(nearest)} from the glass of ${label}${room ? ` in ${quote(room.name)}` : ''}, ${Math.round((piece.z1 - sill) * 100)} cm above its sill, over ${Math.round(cover * 100)} % of its width${shuts ? ', and is not hosted on the window' : ''}.`, + severity: warning || shuts || inCurtains ? 'warning' : 'info', + nodeIds: unique([room?.id, opening.id, piece.nodeId]), + valueM: Math.round((inCurtains ? deepIn : nearest) * 1000) / 1000, + thresholdM: inCurtains ? ENVELOPE_M : shuts ? WINDOW_NEAR_M : WINDOW_BLOCK_M, + place: { room: room?.name ?? '', roomId: room?.id ?? level.levelId, at: middle }, + obstacles: [ + { + nodeId: piece.nodeId, + name: nameOf(nodes, piece.nodeId), + kind: piece.kind, + shape: piece.shape, + movable: false, + }, + ], + approximate, + }, + (warning || shuts || inCurtains ? 100 : 0) + (inCurtains ? deepIn : 1 - nearest), + ) + } + } + } + } + } + out.push(...[...worst.values()].map(({ issue }) => issue)) + return out +} diff --git a/packages/core/src/spatial/usage-field/blocking.test.ts b/packages/core/src/spatial/usage-field/blocking.test.ts new file mode 100644 index 0000000000..8ca6aa0501 --- /dev/null +++ b/packages/core/src/spatial/usage-field/blocking.test.ts @@ -0,0 +1,423 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + DoorNode, + ItemNode, + LevelNode, + SlabNode, + WallNode, + WindowNode, + ZoneNode, +} from '../../schema' +import { usageIssues } from './findings' +import type { Nodes } from './walls' + +const SHA = 'c'.repeat(64) + +const scene = (extra: AnyNode[]): Nodes => + Object.fromEntries( + [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), + ...extra, + ].map((node) => [node.id, node]), + ) as Nodes +const wall = ( + id: string, + start: [number, number], + end: [number, number], + children: string[] = [], + extra: Record = {}, +) => WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.1, children, ...extra }) +const zone = (id: string, name: string, polygon: [number, number][]) => + ZoneNode.parse({ id, parentId: 'level_1', name, polygon, spaceRole: 'room' }) +const slab = (polygon: [number, number][], holes: [number, number][][] = []) => + SlabNode.parse({ id: 'slab_1', parentId: 'level_1', polygon, holes, elevation: 0.05 }) +const door = (id: string, wallId: string, along: number, extra: Record = {}) => + DoorNode.parse({ + id, + parentId: wallId, + wallId, + position: [along, 1.05, 0], + width: 0.9, + height: 2.1, + // A frame inside the wall's thickness: one as deep as the wall puts the door, not the wall, at + // the room's edge, which these figures are drawn without. + frameDepth: 0.07, + name: id, + ...extra, + }) + +/** A script-made piece with a stored solid outline (tolerance 9 mm: exact), centred on (x, z). */ +const piece = ( + id: string, + name: string, + category: string, + x: number, + z: number, + width: number, + depth: number, + height: number, + extra: Record = {}, +) => + ItemNode.parse({ + id, + parentId: 'level_1', + position: [x, 0, z], + name, + asset: { + id, + name, + category, + thumbnail: '/t.webp', + src: `artifact://${SHA}`, + dimensions: [width, height, depth], + }, + source: { + kind: 'script', + script: SHA, + artifact: SHA, + manifest: { + bounds: { min: [-width / 2, 0, -depth / 2], max: [width / 2, height, depth / 2] }, + triangles: 12, + shape: { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: height, + polygons: [ + { + outer: [ + [-width / 2, -depth / 2], + [width / 2, -depth / 2], + [width / 2, depth / 2], + [-width / 2, depth / 2], + ], + }, + ], + }, + ], + }, + }, + }, + ...extra, + }) + +const run = (nodes: Nodes, type: string) => + usageIssues(nodes, { cell: 0.05, entranceDoorId: 'door_1' }).filter( + (issue) => issue.type === type, + ) + +describe('a slit in the floor is stepped over', () => { + /** A 6 x 4 floor entered by a door in its south wall, the Study at its north end; the slab has `holes`. */ + const floor = (holes: [number, number][][]) => + scene([ + slab( + [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + holes, + ), + wall('wall_s', [0, 0], [6, 0], ['door_1']), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + door('door_1', 'wall_s', 3), + zone('zone_1', 'Entry', [ + [0, 0], + [6, 0], + [6, 1.5], + [0, 1.5], + ]), + zone('zone_2', 'Study', [ + [0, 2.5], + [6, 2.5], + [6, 4], + [0, 4], + ]), + ]) + const across = (z0: number, z1: number, x0 = 0.05, x1 = 5.95): [number, number][] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], + ] + + /** What the floor's passage findings say bounds them. */ + const bounds = (holes: [number, number][][]) => + run(floor(holes), 'usage_passage_narrow').flatMap((f) => f.obstacles.map((o) => o.kind)) + + test('a hole 0.8 m wide that leaves 0.45 m at each end of the floor is an obstacle that bounds a passage', () => { + expect(bounds([across(1.6, 2.4, 0.5, 5.5)])).toContain('void') + }) + + test('a slit 3 mm wide across the room is no obstacle, a 5 m one at 3 degrees neither', () => { + expect(bounds([across(1.9985, 2.0015)])).not.toContain('void') + const slope = Math.tan((3 * Math.PI) / 180) * 5.9 + const slanted: [number, number][] = [ + [0.05, 1.5], + [5.95, 1.5 + slope], + [5.95, 1.503 + slope], + [0.05, 1.503], + ] + expect(bounds([slanted])).not.toContain('void') + }) + + test('a triangle 1 m long and 0.3 mm wide, as a room boundary leaves in a floor plate, is no obstacle', () => { + const sliver: [number, number][] = [ + [1, 2], + [2.05, 1.95], + [2.05, 1.9497], + ] + expect(bounds([sliver])).not.toContain('void') + }) +}) + +describe('usage_entry_narrow: what closes off part of a room', () => { + const entry = (nodes: Nodes) => run(nodes, 'usage_entry_narrow') + + /** A `w` x 3 room, `Kitchen`, with a doorway 0.9 m wide in its south wall at x = 1.5. */ + const kitchen = (extra: AnyNode[], w = 3) => + scene([ + slab([ + [-0.3, -0.3], + [w + 0.3, -0.3], + [w + 0.3, 3.3], + [-0.3, 3.3], + ]), + wall('wall_s', [0, 0], [w, 0], ['door_1']), + wall('wall_e', [w, 0], [w, 3]), + wall('wall_n', [w, 3], [0, 3]), + wall('wall_w', [0, 3], [0, 0]), + door('door_1', 'wall_s', Math.min(1.5, w / 2)), + zone('zone_1', 'Kitchen', [ + [0, 0], + [w, 0], + [w, 3], + [0, 3], + ]), + ...extra, + ]) + /** 0.7 x 0.7 m, its front 0.25 m from the south wall's face in front of the doorway: 0.22 m left to go in, at the corner by the jamb. */ + const fridge = (extra: Record = {}, name = 'Fridge', category = 'fridge') => + piece('item_fridge', name, category, 1.5, 0.6, 0.7, 0.7, 1.8, extra) + + test('a free piece in front of the doorway that leaves about 0.2 m is a warning naming it, the room and what is on the other side of the pinch', () => { + const found = entry(kitchen([fridge()])) + expect(found).toHaveLength(1) + expect(found[0]).toMatchObject({ + type: 'usage_entry_narrow', + severity: 'warning', + thresholdM: 0.9, + approximate: false, + }) + expect(found[0]!.valueM).toBeGreaterThan(0.15) + expect(found[0]!.valueM).toBeLessThan(0.25) + expect(found[0]!.message).toBe( + '“Fridge” leaves 0.22 m to enter “Kitchen”, between it and “Wall s” (below 0.90 m).', + ) + expect(found[0]!.nodeIds).toEqual(['zone_1', 'item_fridge', 'wall_s', 'door_1']) + expect(found[0]!.place.room).toBe('Kitchen') + }) + + test('a piece that leaves a passage and more says nothing', () => { + expect( + entry(kitchen([piece('item_f', 'Fridge', 'fridge', 1.5, 1.4, 0.7, 0.7, 1.8)])), + ).toHaveLength(0) + }) + + test('what is built to stand there stays quiet: a fixture, built-in joinery, a piece on a wall, foliage, a piece on another piece', () => { + expect(entry(kitchen([fridge({}, 'Vanity', 'cabinet-base')]))).toHaveLength(0) + expect(entry(kitchen([fridge({}, 'Toilet', 'sanitary')]))).toHaveLength(0) + expect(entry(kitchen([fridge({}, 'Built-in robe', 'wardrobe')]))).toHaveLength(0) + expect(entry(kitchen([fridge({}, 'Potted fern', 'decor')]))).toHaveLength(0) + const onWall = fridge() + onWall.asset = { ...onWall.asset, attachTo: 'wall' } + expect(entry(kitchen([onWall]))).toHaveLength(0) + const onTable = fridge({ parentId: 'item_table' }) + expect( + entry(kitchen([piece('item_table', 'Table', 'table', 4, 4, 0.1, 0.1, 0.1), onTable])), + ).toHaveLength(0) + }) + + test('a room narrower than a passage is judged on its doorway only', () => { + expect(entry(kitchen([fridge()], 0.85))).toHaveLength(0) + }) + + test('an open edge between two rooms is an entrance: the way into the second room past a piece 0.2 m from the end of the wall', () => { + const open = scene([ + slab([ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 3.3], + [-0.3, 3.3], + ]), + wall('wall_s', [0, 0], [6, 0]), + wall('wall_e', [6, 0], [6, 3]), + wall('wall_n', [6, 3], [0, 3]), + wall('wall_w', [0, 3], [0, 0]), + wall('wall_mid_a', [3, 0], [3, 1]), + wall('wall_mid_b', [3, 3], [3, 2.2]), + zone('zone_a', 'Hall', [ + [0, 0], + [3, 0], + [3, 3], + [0, 3], + ]), + zone('zone_b', 'Study', [ + [3, 0], + [6, 0], + [6, 3], + [3, 3], + ]), + piece('item_desk', 'Desk', 'desk', 3.5, 1.6, 0.8, 0.8, 0.75), + ]) + const found = entry(open) + expect(found.map((f) => f.place.room)).toEqual(['Study']) + expect(found[0]!.message).toContain('“Desk” leaves') + expect(found[0]!.severity).toBe('warning') + }) + + test('an approximate fridge closing the way in is a warning with its uncertainty preserved', () => { + const rough = ItemNode.parse({ + id: 'item_fridge', + parentId: 'level_1', + position: [1.5, 0, 0.6], + name: 'Fridge', + asset: { + id: 'fridge', + name: 'Fridge', + category: 'fridge', + thumbnail: '/t.webp', + src: 'asset://fridge', + dimensions: [0.7, 1.8, 0.7], + }, + }) + const found = entry(kitchen([rough])) + expect(found).toHaveLength(1) + expect(found[0]).toMatchObject({ severity: 'warning', approximate: true }) + const roomDefects = run(kitchen([rough]), 'usage_pocket') + expect(roomDefects.length).toBeGreaterThan(0) + expect(roomDefects.every((issue) => issue.severity === 'warning')).toBe(true) + }) + + test('approximate cupboards leaving a 1.3 m turning space inform: a turning circle measures the room', () => { + const cupboards = [ + [0.45, 1.5, 0.8, 2.8], + [2.55, 1.5, 0.8, 2.8], + [1.5, 0.45, 2.8, 0.8], + [1.5, 2.55, 2.8, 0.8], + ].map(([x, z, width, depth], index) => + ItemNode.parse({ + ...fridge(), + id: `item_cupboard${index}`, + source: undefined, + position: [x, 0, z], + asset: { ...fridge().asset, dimensions: [width, 1.8, depth] }, + }), + ) + expect(run(kitchen(cupboards), 'usage_turning_narrow')).toContainEqual( + expect.objectContaining({ severity: 'info', approximate: true }), + ) + }) +}) + +describe('usage_opening_blocked: a free piece in front of a window', () => { + const blocked = (nodes: Nodes) => run(nodes, 'usage_opening_blocked') + + /** A 4 x 4 bedroom whose south wall (room face at z = 0.05) carries a window 1.6 m wide, sill at 0.9 m. */ + const bedroom = (extra: AnyNode[], hosted: string[] = []) => + scene([ + slab([ + [-0.3, -0.3], + [4.3, -0.3], + [4.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [4, 0], ['window_1', ...hosted]), + wall('wall_e', [4, 0], [4, 4]), + wall('wall_n', [4, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + WindowNode.parse({ + id: 'window_1', + parentId: 'wall_s', + wallId: 'wall_s', + position: [2, 1.5, 0], + width: 1.6, + height: 1.2, + name: 'Bed 3 window', + }), + zone('zone_1', 'Bed 3', [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ]), + ...extra, + ]) + /** Its front face 0.17 m from the glass, as the curtains of the run were. */ + const curtains = (width: number, name = 'Bed 3 curtains') => + piece('item_c', name, 'curtain', 2, 0.05 + 0.17 + 0.05, width, 0.1, 1.28) + + test('curtains standing free 0.17 m from the glass over all of it are a warning that names them and the window', () => { + const found = blocked(bedroom([curtains(1.64)])) + expect(found).toHaveLength(1) + expect(found[0]).toMatchObject({ severity: 'warning', thresholdM: 0.3, approximate: false }) + expect(found[0]!.message).toBe( + '“Bed 3 curtains” stands 17 cm from the glass of “Bed 3 window” in “Bed 3”, 38 cm above its sill, over 100 % of its width, and is not hosted on the window.', + ) + expect(found[0]!.nodeIds).toEqual(['zone_1', 'window_1', 'item_c']) + }) + + test('a free curtain over a part of the glass is a warning too, and a wardrobe across all of it and up past its head', () => { + expect(blocked(bedroom([curtains(0.5)]))).toMatchObject([{ severity: 'warning' }]) + const wardrobe = piece('item_w', 'Wardrobe', 'wardrobe', 2, 0.05 + 0.2 + 0.3, 1.6, 0.6, 2.2) + expect(blocked(bedroom([wardrobe]))).toMatchObject([{ severity: 'warning' }]) + }) + + test('an approximate free curtain covering the window is still a warning', () => { + const curtain = curtains(1.64) + delete curtain.source + expect(blocked(bedroom([curtain]))).toMatchObject([ + { severity: 'warning', approximate: true, nodeIds: ['zone_1', 'window_1', 'item_c'] }, + ]) + }) + + test('a piece that covers part of the glass, a sofa back, a bed head and a low piece stay information or nothing', () => { + const narrow = piece('item_n', 'Wardrobe', 'wardrobe', 2, 0.05 + 0.2 + 0.3, 0.8, 0.6, 2) + expect(blocked(bedroom([narrow]))).toMatchObject([{ severity: 'info' }]) + // a sofa's back across all of the glass, 0.4 m above the sill, is a design choice + const sofa = piece('item_f', 'Sofa', 'sofa', 2, 0.05 + 0.2 + 0.3, 1.8, 0.6, 1.3) + expect(blocked(bedroom([sofa]))).toMatchObject([{ severity: 'info' }]) + const bed = piece('item_b', 'Bed', 'bed', 2, 0.05 + 0.2 + 0.3, 1.6, 0.6, 1.2) + expect(blocked(bedroom([bed]))).toMatchObject([{ severity: 'info' }]) + const sideboard = piece('item_s', 'Sideboard', 'sideboard', 2, 0.05 + 0.2 + 0.25, 1.6, 0.5, 0.8) + expect(blocked(bedroom([sideboard]))).toHaveLength(0) + }) + + test('curtains hosted on the window wall say nothing', () => { + const hosted = ItemNode.parse({ + id: 'item_h', + parentId: 'wall_s', + wallId: 'wall_s', + position: [2, 1.5, 0], + side: 'front', + name: 'Bed 3 curtains', + asset: { + id: 'curtain', + name: 'Bed 3 curtains', + category: 'curtain', + thumbnail: '/t.webp', + src: 'asset://curtain', + dimensions: [1.64, 1.28, 0.1], + attachTo: 'wall-side', + }, + }) + expect(blocked(bedroom([hosted], ['item_h']))).toHaveLength(0) + }) +}) diff --git a/packages/core/src/spatial/usage-field/boxes.test.ts b/packages/core/src/spatial/usage-field/boxes.test.ts new file mode 100644 index 0000000000..9dca870aed --- /dev/null +++ b/packages/core/src/spatial/usage-field/boxes.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + CabinetModuleNode, + CabinetNode, + ColumnNode, + LevelNode, + ShelfNode, + SlabNode, +} from '../../schema' +import { boxBodies } from './boxes' +import type { Prism } from './types' +import type { Nodes } from './walls' + +function scene(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const bounds = (prisms: Prism[]) => { + const points = prisms.flatMap((p) => p.outer) + const xs = points.map(([x]) => x) + const zs = points.map(([, z]) => z) + return { x0: Math.min(...xs), x1: Math.max(...xs), z0: Math.min(...zs), z1: Math.max(...zs) } +} + +const prismsOf = (nodes: Nodes, id: string) => + boxBodies(nodes).nodes.find((n) => n.nodeId === id)?.prisms ?? [] + +describe('footprint boxes', () => { + test('a column is its box, from the floor to its height', () => { + const column = ColumnNode.parse({ + id: 'column_1', + parentId: 'level_1', + position: [2, 0, 3], + height: 2.6, + }) + const prisms = prismsOf(scene([column]), 'column_1') + expect(prisms).toHaveLength(1) + expect(prisms[0]!.kind).toBe('column') + expect([prisms[0]!.z0, prisms[0]!.z1]).toEqual([0, 2.6]) + expect(prisms[0]!.shape).toBe('approx') + const b = bounds(prisms) + expect((b.x0 + b.x1) / 2).toBeCloseTo(2, 6) + expect((b.z0 + b.z1) / 2).toBeCloseTo(3, 6) + }) + + test('it stands on the slab under it', () => { + const slab = SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ], + elevation: 0.2, + }) + const column = ColumnNode.parse({ + id: 'column_1', + parentId: 'level_1', + position: [2, 0, 3], + height: 2.6, + }) + expect(prismsOf(scene([slab, column]), 'column_1')[0]!.z0).toBeCloseTo(0.2, 6) + }) + + test('a cabinet run is one box per module, and a nested run is not counted twice', () => { + const run = CabinetNode.parse({ + id: 'cabinet_1', + parentId: 'level_1', + position: [1, 0, 1], + children: ['cabinet-module_1', 'cabinet-module_2'], + }) + const a = CabinetModuleNode.parse({ + id: 'cabinet-module_1', + parentId: run.id, + position: [-0.3, 0, 0], + width: 0.6, + depth: 0.6, + }) + const b = CabinetModuleNode.parse({ + id: 'cabinet-module_2', + parentId: run.id, + position: [0.3, 0, 0], + width: 0.6, + depth: 0.6, + }) + const nodes = scene([run, a, b]) + expect(prismsOf(nodes, 'cabinet_1')).toHaveLength(2) + expect(prismsOf(nodes, 'cabinet-module_1')).toHaveLength(0) + const all = boxBodies(nodes).nodes.flatMap((n) => n.prisms) + expect(all.every((p) => p.kind === 'cabinet')).toBe(true) + const b0 = bounds(all) + expect(b0.x1 - b0.x0).toBeCloseTo(1.2, 6) + expect(b0.z1 - b0.z0).toBeCloseTo(0.6, 6) + }) + + test('a wall cabinet hangs at the height its run is placed at', () => { + const run = CabinetNode.parse({ + id: 'cabinet_1', + parentId: 'level_1', + position: [1, 1.4, 1], + runTier: 'wall', + children: ['cabinet-module_1'], + }) + const module = CabinetModuleNode.parse({ + id: 'cabinet-module_1', + parentId: run.id, + position: [0, 0, 0], + width: 0.85, + depth: 0.32, + }) + const [prism] = prismsOf(scene([run, module]), 'cabinet_1') + expect(prism!.z0).toBeCloseTo(1.4, 6) + expect(prism!.z1).toBeGreaterThan(prism!.z0 + 0.5) + }) + + test('a shelf is its box', () => { + const shelf = ShelfNode.parse({ + id: 'shelf_1', + parentId: 'level_1', + position: [1, 0, 1], + width: 1, + depth: 0.3, + height: 1.8, + }) + const [prism] = prismsOf(scene([shelf]), 'shelf_1') + expect(prism!.kind).toBe('shelf') + expect(prism!.z1 - prism!.z0).toBeCloseTo(1.8, 6) + }) + + test('a hidden node is left out', () => { + const column = ColumnNode.parse({ id: 'column_1', parentId: 'level_1', visible: false }) + expect(boxBodies(scene([column])).nodes).toHaveLength(0) + }) +}) diff --git a/packages/core/src/spatial/usage-field/boxes.ts b/packages/core/src/spatial/usage-field/boxes.ts new file mode 100644 index 0000000000..4d91c5a573 --- /dev/null +++ b/packages/core/src/spatial/usage-field/boxes.ts @@ -0,0 +1,94 @@ +import { floorPlacedOf } from '../../hooks/spatial-grid/built-in-floor-placed' +import { getFloorPlacedFootprints } from '../../hooks/spatial-grid/floor-placed-footprints' +import { resolveLevelId } from '../../lib/node-ancestry' +import type { AnyNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { floorUnder, isHidden, type SupportCache } from './support' +import type { Prism, PrismKind, Ring, Skipped } from './types' +import type { Nodes } from './walls' + +/** The standing kinds read as the box the editor itself keeps them off each other by. */ +const BOX_KINDS: Readonly> = { + cabinet: 'cabinet', + 'cabinet-module': 'cabinet', + shelf: 'shelf', + column: 'column', + block: 'other', + 'hvac-equipment': 'other', + 'procedural-item': 'other', +} + +export type NodePrisms = { nodeId: string; levelId: string | null; prisms: Prism[] } + +const yawOf = (rotation: unknown): number => + typeof rotation === 'number' ? rotation : Array.isArray(rotation) ? (rotation[1] ?? 0) : 0 + +/** + * Cabinets, shelves, columns, furniture and the like as the footprint boxes their `floorPlaced` + * capability declares, on the floor under them. Every one is approximate: a plinth, a handle, a + * round shaft or a mitred end is not in a box. + */ +export function boxBodies(nodes: Nodes): { nodes: NodePrisms[]; skipped: Skipped[] } { + const out: NodePrisms[] = [] + const skipped: Skipped[] = [] + const elevations = getLevelElevations(nodes as never) + const support: SupportCache = new Map() + for (const node of Object.values(nodes) as AnyNode[]) { + const kind = BOX_KINDS[node.type] + if (!kind || isHidden(node, nodes)) continue + try { + const config = floorPlacedOf(node.type) + if (!config || (config.applies && !config.applies(node))) continue + const footprints = getFloorPlacedFootprints(config, node, { nodes }) + if (footprints.length === 0) continue + const levelId = resolveLevelId(node, nodes as Record) + const baseY = elevations.get(levelId)?.baseY ?? 0 + const first = footprints[0]! + const origin = (node as { position?: [number, number, number] }).position ?? [0, 0, 0] + const floor = floorUnder( + node as AnyNode & { supportSlabId?: string }, + { + position: [first.position?.[0] ?? origin[0], 0, first.position?.[2] ?? origin[2]], + dimensions: first.dimensions, + rotation: first.rotation, + }, + nodes, + levelId, + support, + ) + const prisms: Prism[] = [] + for (const [index, footprint] of footprints.entries()) { + const [w, h, d] = footprint.dimensions + if (!(h > 0) || !(w > 0) || !(d > 0)) continue + const at = footprint.position ?? origin + const yaw = yawOf(footprint.rotation) + const cos = Math.cos(yaw) + const sin = Math.sin(yaw) + const ring: Ring = ( + [ + [-w / 2, -d / 2], + [w / 2, -d / 2], + [w / 2, d / 2], + [-w / 2, d / 2], + ] as [number, number][] + ).map(([x, z]) => [at[0] + x * cos + z * sin, at[2] - x * sin + z * cos]) + const z0 = baseY + floor + at[1] + prisms.push({ + id: `${node.id}#box${footprints.length > 1 ? `.${index}` : ''}`, + nodeId: node.id, + kind, + z0, + z1: z0 + h, + outer: ring, + holes: [], + shape: 'approx', + why: `a ${node.type} as its footprint box`, + }) + } + out.push({ nodeId: node.id, levelId, prisms }) + } catch (error) { + skipped.push({ nodeId: node.id, why: error instanceof Error ? error.message : String(error) }) + } + } + return { nodes: out, skipped } +} diff --git a/packages/core/src/spatial/usage-field/cases.test.ts b/packages/core/src/spatial/usage-field/cases.test.ts new file mode 100644 index 0000000000..4d7cbaf97a --- /dev/null +++ b/packages/core/src/spatial/usage-field/cases.test.ts @@ -0,0 +1,403 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + DoorNode, + FenceNode, + ItemNode, + LevelNode, + SlabNode, + StairNode, + WallNode, + WindowNode, + ZoneNode, +} from '../../schema' +import { usageIssues } from './findings' +import type { Nodes } from './walls' + +/** + * The defects the 26 October audit found and the counter-check on the rendered meshes confirmed, + * as small scenes: each is a rule the check must keep, not a stored house. + */ +const SHA = 'b'.repeat(64) + +const wall = ( + id: string, + start: [number, number], + end: [number, number], + children: string[] = [], + level = 'level_1', +) => WallNode.parse({ id, parentId: level, start, end, thickness: 0.1, children }) +const zone = (id: string, name: string, polygon: [number, number][], level = 'level_1') => + ZoneNode.parse({ id, parentId: level, name, polygon }) +const slab = ( + id: string, + level: string, + polygon: [number, number][], + extra: Record = {}, +) => SlabNode.parse({ id, parentId: level, polygon, elevation: 0.05, ...extra }) +const door = (id: string, wallId: string, at: number, width: number, name?: string) => + DoorNode.parse({ + id, + parentId: wallId, + wallId, + position: [at, 1.05, 0], + width, + height: 2.1, + ...(name ? { name } : {}), + }) + +function scene(levels: number, extra: AnyNode[]): Nodes { + const ids = Array.from({ length: levels }, (_, i) => `level_${i + 1}`) + return Object.fromEntries( + [ + BuildingNode.parse({ id: 'building_1', children: ids }), + ...ids.map((id, i) => + LevelNode.parse({ id, parentId: 'building_1', level: i, children: [] }), + ), + ...extra, + ].map((node) => [node.id, node]), + ) as Nodes +} + +/** A script-made object with a stored outline: a solid box, or a foliage cloud, in the artifact's frame. */ +const shaped = ( + id: string, + name: string, + x: number, + z: number, + width: number, + depth: number, + height: number, +) => + ItemNode.parse({ + id, + parentId: 'level_1', + position: [x, 0, z], + name, + asset: { + id, + name, + category: 'decor', + thumbnail: '/t.webp', + src: `artifact://${SHA}`, + dimensions: [width, height, depth], + }, + source: { + kind: 'script', + script: SHA, + artifact: SHA, + manifest: { + bounds: { min: [-width / 2, 0, -depth / 2], max: [width / 2, height, depth / 2] }, + triangles: 12, + shape: { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: height, + polygons: [ + { + outer: [ + [-width / 2, -depth / 2], + [width / 2, -depth / 2], + [width / 2, depth / 2], + [-width / 2, depth / 2], + ], + }, + ], + }, + ], + }, + }, + }, + }) + +const find = (nodes: Nodes, type: string, room?: string, entranceDoorId = 'door_front') => + usageIssues(nodes, { cell: 0.02, entranceDoorId }).filter( + (i) => i.type === type && (!room || i.place.room === room), + ) + +// A 6 m wide, 3.5 m deep hall entered from the south, with a room behind its north wall. +function hall(extra: AnyNode[], backDoor = 0.9) { + return scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 7.3], + [-0.3, 7.3], + ]), + wall('wall_s', [0, 0], [6, 0], ['door_front']), + door('door_front', 'wall_s', 5, 1, 'Front door'), + wall('wall_e', [6, 0], [6, 7]), + wall('wall_w', [0, 7], [0, 0]), + wall('wall_top', [6, 7], [0, 7]), + wall('wall_n', [0, 3.5], [6, 3.5], ['door_back']), + door('door_back', 'wall_n', 1.2, backDoor, 'Laundry door'), + zone('zone_hall', 'Hall', [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.45], + [0.05, 3.45], + ]), + zone('zone_laundry', 'Laundry', [ + [0.05, 3.55], + [5.95, 3.55], + [5.95, 6.95], + [0.05, 6.95], + ]), + ...extra, + ]) +} + +describe('the audit’s defects, as small scenes', () => { + test('a stair set against a wall leaves a strip the laundry door opens onto', () => { + // the stair body fills the hall but a 0.45 m strip along the north wall, where the laundry door is + const stair = StairNode.parse({ + id: 'stair_1', + parentId: 'level_1', + name: 'Staircase', + position: [2.5, 0, 0], + width: 4, + totalRise: 2.7, + stepCount: 15, + fillToFloor: true, + }) + const found = find(hall([stair], 0.9), 'usage_passage_narrow', 'Laundry') + expect(found).toHaveLength(1) + expect(found[0]!.valueM).toBeGreaterThan(0.2) + expect(found[0]!.valueM).toBeLessThan(0.6) + // the disc that makes the 0.45 m touches the stair alone (the nearest wall is 0.55 m from that spot), so the finding names the stair, not a wall 1.45 m from it + expect(found[0]!.obstacles.map((o) => o.kind)).toEqual(['stair']) + expect(found[0]!.severity).toBe('warning') + }) + + test('a door is passed between its jambs: 0.85 m in the wall is 0.75 m to walk through', () => { + const found = find(hall([], 0.85), 'usage_passage_narrow', 'Laundry') + expect(found).toHaveLength(1) + expect(found[0]!.valueM).toBeCloseTo(0.75, 2) + expect(found[0]!.thresholdM).toBe(0.8) + expect(found[0]!.obstacles.map((o) => o.kind)).toEqual(['jamb', 'jamb']) + }) + + test('foliage that fills the foot of a stair closes the way to it', () => { + const stair = StairNode.parse({ + id: 'stair_1', + parentId: 'level_1', + name: 'Staircase', + position: [1.2, 0, 1.0], + width: 1.0, + totalRise: 2.7, + stepCount: 15, + fillToFloor: true, + toLevelId: 'level_2', + fromLevelId: 'level_1', + }) + // a tree in a pot 0.9 m across, set in front of the first step, 0.15 m from the east wall + const plant = shaped('item_plant', 'Olive tree', 1.2, 0.5, 0.9, 0.9, 1.6) + const bare = find(hall([stair]), 'usage_passage_narrow', 'Foot of Staircase') + const blocked = find(hall([stair, plant]), 'usage_passage_narrow', 'Foot of Staircase') + expect(bare).toHaveLength(0) + expect(blocked).toHaveLength(1) + expect(blocked[0]!.valueM).toBeLessThan(0.3) + expect(blocked[0]!.obstacles.map((o) => o.name)).toContain('Olive tree') + expect(blocked[0]!.message).toContain('the foot of “Staircase”') + }) + + test('a window sill that juts into a corridor narrows the way to the room behind', () => { + const nodes = scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [8.3, -0.3], + [8.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [8, 0], ['door_front']), + door('door_front', 'wall_s', 0.8, 1, 'Front door'), + // the corridor's north wall carries a window with a deep sill facing the corridor, and the door to the study + wall('wall_c', [0, 2], [8, 2], ['window_1', 'door_study']), + WindowNode.parse({ + id: 'window_1', + parentId: 'wall_c', + wallId: 'wall_c', + position: [4, 1.2, 0], + width: 1.2, + height: 1.2, + sillDepth: 0.3, + rotation: [0, Math.PI, 0], + }), + door('door_study', 'wall_c', 7, 0.9, 'Study door'), + wall('wall_e', [8, 0], [8, 4]), + wall('wall_w', [0, 4], [0, 0]), + wall('wall_top', [8, 4], [0, 4]), + zone('zone_corridor', 'Corridor', [ + [0.05, 0.05], + [7.95, 0.05], + [7.95, 1.95], + [0.05, 1.95], + ]), + zone('zone_study', 'Study', [ + [0.05, 2.05], + [7.95, 2.05], + [7.95, 3.95], + [0.05, 3.95], + ]), + // a chest along the south wall: 0.6 m is left between its face and the sill + shaped('item_1', 'Chest', 4, 0.55, 3, 1.0, 1.4), + ]) + const found = find(nodes, 'usage_passage_narrow', 'Study') + expect(found).toHaveLength(1) + expect(found[0]!.valueM).toBeCloseTo(0.6, 1) + expect(found[0]!.obstacles.map((o) => o.kind).sort()).toEqual(['item', 'sill']) + }) + + // Guards are read part by part; other fence styles use an approximate strip along the centreline. + const cagedStair = (fenceStyle: 'guard' | 'privacy') => { + // level 2: a stairwell with a guard on every side but a short one that the stair’s own rail closes + const stair = StairNode.parse({ + id: 'stair_1', + parentId: 'level_1', + name: 'Staircase', + position: [1.5, 0, 0.3], + width: 1.0, + totalRise: 2.7, + stepCount: 15, + fillToFloor: false, + fromLevelId: 'level_1', + toLevelId: 'level_2', + railingMode: 'both', + railingStyle: 'metal', + }) + const upper = [ + slab( + 'slab_2', + 'level_2', + [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + { + holes: [ + [ + [1.0, 0.25], + [2.0, 0.25], + [2.0, 3.6], + [1.0, 3.6], + ], + ], + }, + ), + wall('wall_s2', [0, 0], [6, 0], [], 'level_2'), + wall('wall_e2', [6, 0], [6, 4], [], 'level_2'), + wall('wall_n2', [6, 4], [0, 4], [], 'level_2'), + wall('wall_w2', [0, 4], [0, 0], [], 'level_2'), + zone( + 'zone_up', + 'Landing', + [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ], + 'level_2', + ), + // guards round the opening, closing the end of the flight + FenceNode.parse({ + id: 'fence_a', + parentId: 'level_2', + start: [1.0, 3.6], + end: [2.0, 3.6], + style: fenceStyle, + height: 1.05, + }), + FenceNode.parse({ + id: 'fence_b', + parentId: 'level_2', + start: [1.0, 0.25], + end: [1.0, 3.6], + style: fenceStyle, + height: 1.05, + }), + FenceNode.parse({ + id: 'fence_c', + parentId: 'level_2', + start: [2.0, 0.25], + end: [2.0, 3.6], + style: fenceStyle, + height: 1.05, + }), + FenceNode.parse({ + id: 'fence_d', + parentId: 'level_2', + start: [1.0, 3.6], + end: [2.0, 3.6], + style: fenceStyle, + height: 1.05, + }), + ] + const nodes = scene(2, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [6, 0], ['door_front']), + door('door_front', 'wall_s', 4, 1, 'Front door'), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + zone('zone_hall', 'Hall', [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ]), + stair, + ...upper, + ]) + const issues = usageIssues(nodes, { cell: 0.02, entranceDoorId: 'door_front' }) + return issues.filter((i) => i.type === 'usage_pocket') + } + + test('a floor whose stair arrival is caged by its own guard has no way out, a warning', () => { + const pocket = cagedStair('guard') + expect(pocket).toHaveLength(1) + expect(pocket[0]!.message).toContain('no 0.60 m way out from the stair arrival') + expect(pocket[0]!.place.room).toBe('Landing') + expect(pocket[0]!.severity).toBe('warning') + }) + + test('the same cage drawn by approximate fence strips still warns that there is no way out', () => { + const pocket = cagedStair('privacy') + expect(pocket).toHaveLength(1) + expect(pocket[0]).toMatchObject({ severity: 'warning', approximate: true }) + }) + + test('a well kept house says nothing', () => { + const quiet = scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [6, 0], ['door_front']), + door('door_front', 'wall_s', 3, 1.2, 'Front door'), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + zone('zone_room', 'Living room', [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ]), + shaped('item_1', 'Sofa', 1.5, 3.4, 2.0, 0.9, 0.8), + ]) + expect(usageIssues(quiet, { cell: 0.02, entranceDoorId: 'door_front' })).toEqual([]) + }) +}) diff --git a/packages/core/src/spatial/usage-field/catalogue-shapes.ts b/packages/core/src/spatial/usage-field/catalogue-shapes.ts new file mode 100644 index 0000000000..54e88b38f1 --- /dev/null +++ b/packages/core/src/spatial/usage-field/catalogue-shapes.ts @@ -0,0 +1,2018 @@ +// Generated by scripts/usage-shape/bake-catalogue-shapes.ts (private-editor). Do not edit. +// biome-ignore-all lint/suspicious/noApproximativeNumericConstant: outline coordinates are data +import type { GeometryShape } from '../../schema' + +export const CATALOGUE_SHAPES: Readonly> = { + 'system/bathroom-sink': { + tolerance: 0.045, + bands: [ + { + y0: 0, + y1: 0.039, + polygons: [ + { + outer: [ + [0.715, -0.336], + [0.81, -0.336], + [0.81, 0.294], + [-1.015, 0.294], + [-1.015, -0.321], + [-0.985, -0.201], + [-0.58, -0.201], + [-0.58, -0.321], + [-0.55, -0.201], + [0.26, -0.201], + [0.26, -0.321], + [0.285, -0.201], + [0.695, -0.201], + ], + }, + ], + }, + { + y0: 0.039, + y1: 0.671, + polygons: [ + { + outer: [ + [0.715, -0.336], + [0.81, -0.336], + [0.81, 0.294], + [-1.015, 0.294], + [-1.015, -0.321], + ], + holes: [ + [ + [-0.98, -0.196], + [-0.985, 0.259], + [-0.58, 0.259], + [-0.58, -0.196], + ], + [ + [-0.545, -0.196], + [-0.55, 0.259], + [0.26, 0.259], + [0.26, -0.196], + ], + [ + [0.29, -0.196], + [0.285, 0.259], + [0.695, 0.259], + [0.695, -0.196], + ], + ], + }, + ], + }, + { + y0: 0.671, + y1: 0.966, + polygons: [ + { + outer: [ + [-1.015, -0.336], + [0.81, -0.336], + [0.81, 0.294], + [-1.015, 0.294], + ], + }, + ], + }, + ], + }, + 'system/bathtub': { + tolerance: 0.015, + bands: [ + { + y0: 0, + y1: 0.059, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.171, 0.556], + [-1.169, 0.556], + ], + }, + ], + }, + { + y0: 0.059, + y1: 0.078, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.171, 0.556], + [-1.169, 0.556], + ], + holes: [ + [ + [-0.239, -0.219], + [-0.489, -0.184], + [-0.574, -0.134], + [-0.614, -0.064], + [-0.614, 0.046], + [-0.579, 0.111], + [-0.494, 0.166], + [-0.219, 0.201], + [0.271, 0.196], + [0.516, 0.161], + [0.591, 0.116], + [0.636, 0.041], + [0.636, -0.064], + [0.606, -0.124], + [0.511, -0.189], + [0.276, -0.219], + ], + ], + }, + { + outer: [ + [-0.569, -0.069], + [-0.519, -0.054], + [-0.514, -0.024], + [-0.539, 0.006], + [-0.589, -0.009], + [-0.594, -0.039], + ], + }, + ], + }, + { + y0: 0.078, + y1: 0.098, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.171, 0.556], + [-1.169, 0.556], + ], + holes: [ + [ + [-0.224, -0.274], + [-0.509, -0.239], + [-0.629, -0.159], + [-0.674, -0.079], + [-0.674, 0.056], + [-0.619, 0.156], + [-0.514, 0.216], + [-0.239, 0.251], + [0.261, 0.251], + [0.496, 0.221], + [0.531, 0.216], + [0.636, 0.156], + [0.696, 0.056], + [0.686, -0.099], + [0.631, -0.184], + [0.536, -0.239], + [0.256, -0.274], + ], + ], + }, + ], + }, + { + y0: 0.098, + y1: 0.156, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.166, 0.551], + [-1.169, 0.551], + ], + holes: [ + [ + [-0.244, -0.304], + [-0.519, -0.269], + [-0.644, -0.194], + [-0.699, -0.094], + [-0.689, 0.091], + [-0.639, 0.176], + [-0.524, 0.246], + [-0.254, 0.281], + [0.276, 0.281], + [0.546, 0.246], + [0.661, 0.176], + [0.721, 0.071], + [0.716, -0.104], + [0.661, -0.199], + [0.546, -0.269], + [0.271, -0.304], + ], + ], + }, + ], + }, + { + y0: 0.156, + y1: 0.293, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.166, 0.551], + [-1.169, 0.551], + ], + holes: [ + [ + [-0.264, -0.334], + [-0.544, -0.299], + [-0.679, -0.214], + [-0.744, -0.094], + [-0.744, 0.071], + [-0.684, 0.186], + [-0.544, 0.276], + [-0.239, 0.316], + [0.261, 0.316], + [0.566, 0.276], + [0.706, 0.186], + [0.766, 0.071], + [0.766, -0.094], + [0.711, -0.199], + [0.566, -0.299], + [0.291, -0.334], + ], + ], + }, + ], + }, + { + y0: 0.293, + y1: 0.41, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.161, 0.546], + [-1.164, 0.551], + ], + holes: [ + [ + [-0.254, -0.359], + [-0.584, -0.314], + [-0.709, -0.234], + [-0.774, -0.124], + [-0.784, 0.081], + [-0.719, 0.206], + [-0.584, 0.291], + [-0.264, 0.336], + [0.286, 0.336], + [0.591, 0.296], + [0.741, 0.206], + [0.806, 0.081], + [0.796, -0.124], + [0.746, -0.219], + [0.606, -0.314], + [0.281, -0.359], + ], + ], + }, + ], + }, + { + y0: 0.41, + y1: 0.488, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.156, 0.546], + [-1.164, 0.546], + ], + holes: [ + [ + [-0.274, -0.374], + [-0.609, -0.329], + [-0.754, -0.234], + [-0.824, -0.099], + [-0.824, 0.081], + [-0.774, 0.176], + [-0.744, 0.221], + [-0.609, 0.306], + [-0.284, 0.351], + [0.306, 0.351], + [0.611, 0.311], + [0.766, 0.221], + [0.846, 0.081], + [0.846, -0.099], + [0.806, -0.179], + [0.766, -0.244], + [0.631, -0.329], + [0.301, -0.374], + ], + ], + }, + ], + }, + { + y0: 0.488, + y1: 0.507, + polygons: [ + { + outer: [ + [-1.169, -0.554], + [1.171, -0.554], + [1.156, 0.526], + [-1.159, 0.531], + ], + }, + ], + }, + { + y0: 0.507, + y1: 0.527, + polygons: [ + { + outer: [ + [0.061, -0.519], + [0.091, -0.514], + [0.101, -0.494], + [0.076, -0.459], + [0.336, -0.459], + [0.701, -0.404], + [0.856, -0.299], + [0.946, -0.129], + [0.946, 0.111], + [0.856, 0.276], + [0.701, 0.381], + [0.341, 0.436], + [-0.319, 0.436], + [-0.679, 0.381], + [-0.849, 0.261], + [-0.924, 0.111], + [-0.924, -0.129], + [-0.839, -0.294], + [-0.679, -0.404], + [-0.314, -0.459], + [0.061, -0.459], + [0.016, -0.474], + [0.021, -0.489], + [0.041, -0.484], + [0.046, -0.514], + ], + holes: [ + [ + [-0.274, -0.389], + [-0.634, -0.339], + [-0.784, -0.239], + [-0.854, -0.104], + [-0.854, 0.086], + [-0.809, 0.171], + [-0.779, 0.226], + [-0.624, 0.321], + [-0.284, 0.366], + [0.306, 0.366], + [0.646, 0.321], + [0.801, 0.226], + [0.876, 0.086], + [0.876, -0.104], + [0.836, -0.184], + [0.791, -0.254], + [0.656, -0.339], + [0.301, -0.389], + ], + ], + }, + ], + }, + { + y0: 0.527, + y1: 0.546, + polygons: [ + { + outer: [ + [0.061, -0.519], + [0.091, -0.514], + [0.091, -0.464], + [0.026, -0.464], + [0.016, -0.484], + [0.041, -0.484], + [0.046, -0.514], + ], + }, + { + outer: [ + [-0.309, -0.439], + [0.331, -0.439], + [0.681, -0.389], + [0.851, -0.279], + [0.866, -0.239], + [0.841, -0.274], + [0.671, -0.369], + [0.311, -0.414], + [-0.289, -0.414], + [-0.649, -0.369], + [-0.819, -0.274], + [-0.844, -0.239], + [-0.829, -0.279], + [-0.659, -0.389], + ], + }, + { + outer: [ + [-0.844, 0.216], + [-0.819, 0.251], + [-0.649, 0.346], + [-0.294, 0.391], + [0.316, 0.391], + [0.646, 0.351], + [0.826, 0.261], + [0.861, 0.216], + [0.866, 0.226], + [0.851, 0.256], + [0.686, 0.366], + [0.336, 0.416], + [-0.314, 0.416], + [-0.664, 0.366], + [-0.829, 0.256], + ], + }, + ], + }, + { + y0: 0.546, + y1: 0.566, + polygons: [ + { + outer: [ + [0.061, -0.519], + [0.091, -0.514], + [0.091, -0.464], + [0.026, -0.464], + [0.016, -0.484], + [0.041, -0.484], + [0.046, -0.514], + ], + }, + ], + }, + { + y0: 0.566, + y1: 0.605, + polygons: [ + { + outer: [ + [0.061, -0.519], + [0.151, -0.469], + [0.171, -0.429], + [0.126, -0.429], + [0.051, -0.464], + [0.046, -0.479], + [0.026, -0.464], + [0.016, -0.484], + [0.041, -0.484], + ], + }, + ], + }, + { + y0: 0.605, + y1: 0.683, + polygons: [ + { + outer: [ + [0.021, -0.489], + [0.041, -0.484], + [0.031, -0.464], + [0.016, -0.474], + ], + }, + ], + }, + { + y0: 0.683, + y1: 0.702, + polygons: [ + { + outer: [ + [0.021, -0.489], + [0.041, -0.484], + [0.031, -0.464], + [0.016, -0.474], + ], + }, + { + outer: [ + [0.026, -0.329], + [0.041, -0.319], + [0.031, -0.299], + [0.016, -0.309], + ], + }, + ], + }, + { + y0: 0.702, + y1: 0.722, + polygons: [ + { + outer: [ + [0.021, -0.489], + [0.041, -0.484], + [0.031, -0.464], + [0.016, -0.474], + ], + }, + { + outer: [ + [0.026, -0.334], + [0.041, -0.324], + [0.036, -0.304], + [0.016, -0.309], + ], + }, + ], + }, + { + y0: 0.722, + y1: 0.742, + polygons: [ + { + outer: [ + [0.021, -0.489], + [0.041, -0.484], + [0.031, -0.459], + [0.016, -0.464], + ], + }, + { + outer: [ + [0.026, -0.339], + [0.041, -0.329], + [0.036, -0.309], + [0.016, -0.314], + ], + }, + ], + }, + { + y0: 0.742, + y1: 0.761, + polygons: [ + { + outer: [ + [0.021, -0.484], + [0.041, -0.474], + [0.031, -0.314], + [0.016, -0.319], + ], + }, + ], + }, + { + y0: 0.761, + y1: 0.781, + polygons: [ + { + outer: [ + [0.021, -0.469], + [0.041, -0.449], + [0.031, -0.319], + [0.016, -0.324], + ], + }, + ], + }, + ], + }, + 'system/fridge': { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: 0.06, + polygons: [ + { + outer: [ + [-0.341, -0.306], + [0.344, -0.306], + [0.344, 0.309], + [-0.341, 0.309], + ], + }, + ], + }, + { + y0: 0.06, + y1: 1.858, + polygons: [ + { + outer: [ + [-0.341, -0.306], + [0.344, -0.306], + [0.344, 0.294], + [0.349, 0.294], + [0.349, 0.359], + [0.209, 0.369], + [0.209, 0.374], + [0.159, 0.374], + [0.159, 0.379], + [-0.161, 0.379], + [-0.161, 0.374], + [-0.211, 0.374], + [-0.211, 0.369], + [-0.346, 0.359], + [-0.346, 0.294], + [-0.341, 0.294], + ], + }, + ], + }, + { + y0: 1.858, + y1: 1.918, + polygons: [ + { + outer: [ + [-0.346, -0.306], + [0.349, -0.306], + [0.349, 0.389], + [0.269, 0.394], + [0.269, 0.399], + [0.219, 0.399], + [0.219, 0.404], + [0.169, 0.404], + [0.169, 0.409], + [-0.171, 0.409], + [-0.171, 0.404], + [-0.221, 0.404], + [-0.221, 0.399], + [-0.271, 0.399], + [-0.271, 0.394], + [-0.346, 0.389], + ], + }, + ], + }, + ], + }, + 'system/shower-square': { + tolerance: 0.015, + bands: [ + { + y0: 0, + y1: 0.04, + polygons: [ + { + outer: [ + [-0.785, -0.001], + [-0.015, -0.001], + [0, 0.014], + [0, 0.764], + [-0.015, 0.789], + [-0.05, 0.804], + [-0.75, 0.804], + [-0.785, 0.789], + [-0.8, 0.764], + [-0.8, 0.014], + ], + }, + ], + }, + { + y0: 0.04, + y1: 0.1, + polygons: [ + { + outer: [ + [-0.785, -0.001], + [-0.015, -0.001], + [0, 0.014], + [0, 0.764], + [-0.015, 0.789], + [-0.05, 0.804], + [-0.75, 0.804], + [-0.785, 0.789], + [-0.8, 0.764], + [-0.8, 0.014], + ], + holes: [ + [ + [-0.71, 0.064], + [-0.735, 0.084], + [-0.725, 0.709], + [-0.695, 0.729], + [-0.09, 0.724], + [-0.07, 0.694], + [-0.065, 0.084], + [-0.085, 0.064], + ], + ], + }, + { + outer: [ + [-0.43, 0.394], + [-0.375, 0.404], + [-0.38, 0.464], + [-0.445, 0.459], + [-0.45, 0.419], + ], + }, + ], + }, + { + y0: 0.1, + y1: 0.12, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.02, -0.001], + [0, 0.014], + [0, 0.759], + [-0.025, 0.794], + [-0.765, 0.799], + [-0.79, 0.779], + [-0.8, 0.014], + ], + holes: [ + [ + [-0.7, 0.059], + [-0.74, 0.094], + [-0.725, 0.709], + [-0.7, 0.729], + [-0.09, 0.724], + [-0.07, 0.699], + [-0.065, 0.079], + [-0.095, 0.059], + ], + ], + }, + ], + }, + { + y0: 0.12, + y1: 0.88, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + ], + }, + { + y0: 0.88, + y1: 0.9, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.565, -0.001], + [-0.255, -0.001], + [-0.255, 0.124], + [-0.56, 0.129], + ], + }, + { + outer: [ + [-0.43, 0.149], + [-0.385, 0.154], + [-0.38, 0.234], + [-0.415, 0.239], + [-0.445, 0.224], + ], + }, + ], + }, + { + y0: 0.9, + y1: 0.96, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.565, -0.001], + [-0.255, -0.001], + [-0.255, 0.139], + [-0.375, 0.144], + [-0.36, 0.229], + [-0.445, 0.239], + [-0.46, 0.209], + [-0.445, 0.144], + [-0.565, 0.139], + ], + }, + ], + }, + { + y0: 0.96, + y1: 0.98, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.565, -0.001], + [-0.255, -0.001], + [-0.255, 0.129], + [-0.56, 0.134], + ], + }, + { + outer: [ + [-0.43, 0.144], + [-0.38, 0.149], + [-0.375, 0.234], + [-0.43, 0.239], + [-0.445, 0.219], + [-0.48, 0.214], + [-0.475, 0.189], + [-0.44, 0.179], + ], + }, + ], + }, + { + y0: 0.98, + y1: 1.04, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.39, 0.074], + [-0.395, 0.114], + [-0.43, 0.109], + ], + }, + { + outer: [ + [-0.525, 0.179], + [-0.455, 0.184], + [-0.435, 0.204], + [-0.45, 0.219], + [-0.53, 0.224], + [-0.555, 0.199], + ], + }, + ], + }, + { + y0: 1.04, + y1: 1.08, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.39, 0.074], + [-0.395, 0.114], + [-0.43, 0.109], + ], + }, + { + outer: [ + [-0.55, 0.179], + [-0.5, 0.184], + [-0.5, 0.219], + [-0.56, 0.219], + ], + }, + ], + }, + { + y0: 1.08, + y1: 1.54, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.39, 0.074], + [-0.395, 0.114], + [-0.43, 0.109], + ], + }, + ], + }, + { + y0: 1.54, + y1: 1.62, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.39, 0.074], + [-0.395, 0.114], + [-0.43, 0.109], + ], + }, + { + outer: [ + [-0.44, 0.259], + [-0.355, 0.264], + [-0.305, 0.289], + [-0.255, 0.344], + [-0.235, 0.399], + [-0.235, 0.469], + [-0.255, 0.524], + [-0.305, 0.579], + [-0.355, 0.604], + [-0.43, 0.609], + [-0.505, 0.584], + [-0.545, 0.549], + [-0.58, 0.484], + [-0.585, 0.414], + [-0.56, 0.339], + [-0.5, 0.279], + ], + }, + ], + }, + { + y0: 1.62, + y1: 1.66, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.39, 0.074], + [-0.395, 0.114], + [-0.43, 0.109], + ], + }, + { + outer: [ + [-0.41, 0.389], + [-0.38, 0.399], + [-0.365, 0.429], + [-0.39, 0.474], + [-0.43, 0.474], + [-0.45, 0.454], + [-0.445, 0.404], + ], + }, + ], + }, + { + y0: 1.66, + y1: 1.7, + polygons: [ + { + outer: [ + [-0.78, -0.001], + [-0.76, -0.001], + [-0.76, 0.749], + [-0.74, 0.764], + [-0.01, 0.764], + [-0.01, 0.779], + [-0.745, 0.779], + [-0.775, 0.759], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.385, 0.084], + [-0.405, 0.119], + [-0.435, 0.094], + ], + }, + { + outer: [ + [-0.42, 0.409], + [-0.39, 0.414], + [-0.39, 0.454], + [-0.43, 0.449], + ], + }, + ], + }, + { + y0: 1.7, + y1: 1.74, + polygons: [ + { + outer: [ + [-0.8, -0.001], + [-0.735, -0.001], + [-0.725, 0.709], + [-0.7, 0.729], + [-0.02, 0.729], + [-0.02, 0.804], + [-0.75, 0.804], + [-0.785, 0.789], + [-0.8, 0.764], + ], + }, + { + outer: [ + [-0.42, 0.069], + [-0.385, 0.084], + [-0.39, 0.129], + [-0.405, 0.139], + [-0.435, 0.109], + ], + }, + { + outer: [ + [-0.415, 0.389], + [-0.385, 0.409], + [-0.385, 0.439], + [-0.405, 0.459], + [-0.435, 0.434], + ], + }, + ], + }, + { + y0: 1.74, + y1: 1.78, + polygons: [ + { + outer: [ + [-0.8, -0.001], + [-0.735, -0.001], + [-0.725, 0.709], + [-0.7, 0.729], + [-0.02, 0.729], + [-0.02, 0.804], + [-0.75, 0.804], + [-0.785, 0.789], + [-0.8, 0.764], + ], + }, + { + outer: [ + [-0.415, 0.079], + [-0.385, 0.099], + [-0.385, 0.429], + [-0.405, 0.449], + [-0.435, 0.424], + [-0.435, 0.104], + ], + }, + ], + }, + { + y0: 1.78, + y1: 1.8, + polygons: [ + { + outer: [ + [-0.8, -0.001], + [-0.735, 0.004], + [-0.725, 0.714], + [-0.705, 0.729], + [-0.025, 0.729], + [-0.01, 0.744], + [-0.015, 0.799], + [-0.765, 0.799], + [-0.79, 0.779], + ], + }, + { + outer: [ + [-0.41, 0.114], + [-0.39, 0.124], + [-0.385, 0.164], + [-0.385, 0.364], + [-0.4, 0.409], + [-0.43, 0.394], + [-0.43, 0.129], + ], + }, + ], + }, + ], + }, + 'system/stove': { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: 0.118, + polygons: [ + { + outer: [ + [-0.399, -0.275], + [-0.344, -0.275], + [-0.344, -0.22], + [-0.399, -0.22], + ], + }, + { + outer: [ + [0.341, -0.275], + [0.396, -0.275], + [0.396, -0.22], + [0.341, -0.22], + ], + }, + { + outer: [ + [-0.399, 0.22], + [-0.344, 0.22], + [-0.344, 0.275], + [-0.399, 0.275], + ], + }, + { + outer: [ + [0.341, 0.22], + [0.396, 0.22], + [0.396, 0.275], + [0.341, 0.275], + ], + }, + ], + }, + { + y0: 0.118, + y1: 0.63, + polygons: [ + { + outer: [ + [-0.464, -0.32], + [0.456, -0.32], + [0.456, 0.335], + [0.426, 0.335], + [0.421, 0.34], + [0.421, 0.385], + [0.361, 0.385], + [0.361, 0.335], + [0.296, 0.335], + [0.286, 0.35], + [-0.394, 0.35], + [-0.404, 0.335], + [-0.464, 0.335], + ], + }, + ], + }, + { + y0: 0.63, + y1: 0.67, + polygons: [ + { + outer: [ + [-0.464, -0.32], + [0.456, -0.32], + [0.456, 0.335], + [0.296, 0.335], + [0.286, 0.35], + [0.251, 0.35], + [0.251, 0.43], + [-0.364, 0.43], + [-0.364, 0.35], + [-0.394, 0.35], + [-0.404, 0.335], + [-0.464, 0.335], + ], + holes: [ + [ + [-0.339, 0.35], + [-0.344, 0.35], + [-0.344, 0.4], + [0.231, 0.4], + [0.231, 0.35], + ], + ], + }, + ], + }, + { + y0: 0.67, + y1: 0.788, + polygons: [ + { + outer: [ + [-0.464, -0.32], + [0.456, -0.32], + [0.456, 0.335], + [0.296, 0.335], + [0.296, 0.385], + [0.241, 0.385], + [0.241, 0.35], + [0.196, 0.35], + [0.196, 0.385], + [0.136, 0.385], + [0.136, 0.35], + [0.031, 0.35], + [0.031, 0.385], + [-0.029, 0.385], + [-0.029, 0.35], + [-0.074, 0.35], + [-0.074, 0.385], + [-0.129, 0.385], + [-0.129, 0.35], + [-0.239, 0.35], + [-0.239, 0.385], + [-0.294, 0.385], + [-0.294, 0.35], + [-0.339, 0.35], + [-0.339, 0.385], + [-0.399, 0.385], + [-0.399, 0.34], + [-0.404, 0.335], + [-0.419, 0.335], + [-0.419, 0.34], + [-0.464, 0.335], + ], + }, + ], + }, + { + y0: 0.788, + y1: 0.827, + polygons: [ + { + outer: [ + [-0.464, -0.325], + [0.456, -0.325], + [0.456, 0.34], + [-0.464, 0.34], + ], + }, + ], + }, + { + y0: 0.827, + y1: 0.847, + polygons: [ + { + outer: [ + [-0.449, -0.305], + [0.446, -0.305], + [0.446, -0.15], + [0.451, -0.15], + [0.451, -0.135], + [0.446, -0.135], + [0.446, 0.325], + [-0.449, 0.325], + ], + holes: [ + [ + [-0.424, -0.285], + [-0.429, -0.285], + [-0.429, -0.15], + [-0.334, -0.15], + [-0.334, -0.165], + [-0.324, -0.175], + [-0.314, -0.175], + [-0.314, -0.18], + [-0.274, -0.175], + [-0.264, -0.165], + [-0.264, -0.15], + [-0.174, -0.15], + [-0.174, -0.285], + [-0.294, -0.285], + [-0.294, -0.185], + [-0.304, -0.185], + [-0.304, -0.285], + ], + [ + [-0.134, -0.285], + [-0.139, -0.285], + [-0.139, -0.15], + [-0.049, -0.15], + [-0.044, -0.17], + [-0.024, -0.175], + [-0.024, -0.18], + [0.016, -0.175], + [0.026, -0.145], + [0.036, -0.145], + [0.036, -0.15], + [0.121, -0.15], + [0.121, -0.285], + [-0.004, -0.285], + [-0.004, -0.185], + [-0.019, -0.185], + [-0.019, -0.285], + ], + [ + [0.161, -0.285], + [0.156, -0.285], + [0.156, -0.15], + [0.246, -0.15], + [0.246, -0.145], + [0.256, -0.145], + [0.261, -0.17], + [0.281, -0.175], + [0.281, -0.18], + [0.321, -0.175], + [0.331, -0.145], + [0.346, -0.145], + [0.346, -0.15], + [0.426, -0.15], + [0.426, -0.285], + [0.301, -0.285], + [0.301, -0.185], + [0.286, -0.185], + [0.286, -0.285], + ], + [ + [0.031, -0.14], + [0.026, -0.14], + [0.016, -0.11], + [-0.009, -0.105], + [-0.004, -0.1], + [-0.004, 0.015], + [0.121, 0.015], + [0.121, -0.135], + [0.036, -0.135], + ], + [ + [0.251, -0.14], + [0.246, -0.135], + [0.156, -0.135], + [0.156, 0.015], + [0.286, 0.015], + [0.286, -0.1], + [0.291, -0.105], + [0.266, -0.11], + [0.261, -0.125], + [0.256, -0.125], + [0.256, -0.14], + ], + [ + [0.336, -0.14], + [0.331, -0.14], + [0.321, -0.11], + [0.296, -0.105], + [0.301, -0.1], + [0.301, 0.015], + [0.426, 0.015], + [0.426, -0.135], + [0.346, -0.135], + [0.346, -0.14], + ], + [ + [-0.424, -0.135], + [-0.429, -0.135], + [-0.429, 0.015], + [-0.304, 0.015], + [-0.304, -0.105], + [-0.324, -0.11], + [-0.334, -0.12], + [-0.334, -0.135], + ], + [ + [-0.259, -0.135], + [-0.264, -0.135], + [-0.264, -0.12], + [-0.274, -0.11], + [-0.294, -0.105], + [-0.294, 0.015], + [-0.174, 0.015], + [-0.174, -0.135], + ], + [ + [-0.134, -0.135], + [-0.139, -0.135], + [-0.139, 0.015], + [-0.019, 0.015], + [-0.019, -0.1], + [-0.014, -0.105], + [-0.039, -0.11], + [-0.049, -0.135], + ], + [ + [-0.424, 0.03], + [-0.429, 0.03], + [-0.429, 0.15], + [-0.334, 0.15], + [-0.329, 0.125], + [-0.304, 0.12], + [-0.304, 0.03], + ], + [ + [-0.289, 0.03], + [-0.294, 0.03], + [-0.294, 0.12], + [-0.269, 0.125], + [-0.264, 0.15], + [-0.174, 0.15], + [-0.174, 0.03], + ], + [ + [-0.134, 0.03], + [-0.139, 0.03], + [-0.139, 0.15], + [-0.049, 0.15], + [-0.044, 0.13], + [-0.019, 0.12], + [-0.019, 0.03], + ], + [ + [0.001, 0.03], + [-0.004, 0.03], + [-0.004, 0.115], + [-0.009, 0.12], + [0.016, 0.125], + [0.026, 0.15], + [0.121, 0.15], + [0.121, 0.03], + ], + [ + [0.161, 0.03], + [0.156, 0.03], + [0.156, 0.15], + [0.256, 0.15], + [0.261, 0.13], + [0.286, 0.12], + [0.286, 0.03], + ], + [ + [0.306, 0.03], + [0.301, 0.03], + [0.301, 0.115], + [0.296, 0.12], + [0.321, 0.125], + [0.331, 0.15], + [0.426, 0.15], + [0.426, 0.03], + ], + [ + [-0.339, 0.16], + [-0.344, 0.165], + [-0.429, 0.165], + [-0.429, 0.305], + [-0.304, 0.305], + [-0.304, 0.2], + [-0.294, 0.2], + [-0.294, 0.305], + [-0.174, 0.305], + [-0.174, 0.165], + [-0.264, 0.165], + [-0.274, 0.19], + [-0.309, 0.195], + [-0.309, 0.19], + [-0.329, 0.185], + ], + [ + [0.031, 0.16], + [0.026, 0.16], + [0.021, 0.18], + [0.011, 0.19], + [0.001, 0.19], + [0.001, 0.195], + [-0.024, 0.195], + [-0.024, 0.19], + [-0.044, 0.185], + [-0.049, 0.165], + [-0.139, 0.165], + [-0.139, 0.305], + [-0.019, 0.305], + [-0.019, 0.2], + [-0.004, 0.2], + [-0.004, 0.305], + [0.121, 0.305], + [0.121, 0.165], + [0.036, 0.165], + ], + [ + [0.251, 0.16], + [0.246, 0.165], + [0.156, 0.165], + [0.156, 0.305], + [0.286, 0.305], + [0.286, 0.2], + [0.301, 0.2], + [0.301, 0.305], + [0.426, 0.305], + [0.426, 0.165], + [0.346, 0.165], + [0.346, 0.16], + [0.331, 0.16], + [0.331, 0.17], + [0.326, 0.17], + [0.326, 0.18], + [0.316, 0.19], + [0.281, 0.195], + [0.281, 0.19], + [0.261, 0.185], + [0.261, 0.17], + ], + ], + }, + ], + }, + ], + }, + 'system/toilet': { + tolerance: 0.015, + bands: [ + { + y0: 0, + y1: 0.139, + polygons: [ + { + outer: [ + [-0.113, -0.001], + [0.112, -0.001], + [0.112, 0.099], + [0.017, 0.099], + [0.017, 0.224], + [0.037, 0.224], + [0.097, 0.364], + [0.062, 0.454], + [-0.058, 0.454], + [-0.093, 0.374], + [-0.043, 0.239], + [-0.018, 0.224], + [-0.018, 0.099], + [-0.113, 0.099], + ], + }, + ], + }, + { + y0: 0.139, + y1: 0.159, + polygons: [ + { + outer: [ + [-0.118, -0.001], + [0.117, -0.001], + [0.117, 0.099], + [0.017, 0.099], + [0.017, 0.224], + [0.037, 0.219], + [0.107, 0.354], + [0.107, 0.394], + [0.062, 0.454], + [-0.058, 0.454], + [-0.108, 0.369], + [-0.098, 0.314], + [-0.043, 0.229], + [-0.018, 0.224], + [-0.018, 0.099], + [-0.118, 0.099], + ], + }, + ], + }, + { + y0: 0.159, + y1: 0.179, + polygons: [ + { + outer: [ + [-0.123, -0.001], + [0.127, -0.001], + [0.127, 0.099], + [0.017, 0.099], + [0.017, 0.209], + [0.052, 0.194], + [0.067, 0.259], + [0.122, 0.349], + [0.117, 0.419], + [0.062, 0.479], + [-0.068, 0.474], + [-0.123, 0.364], + [-0.113, 0.289], + [-0.053, 0.199], + [-0.018, 0.209], + [-0.018, 0.099], + [-0.123, 0.099], + ], + }, + ], + }, + { + y0: 0.179, + y1: 0.198, + polygons: [ + { + outer: [ + [-0.133, -0.001], + [0.132, -0.001], + [0.132, 0.099], + [0.017, 0.099], + [0.017, 0.184], + [0.072, 0.179], + [0.102, 0.294], + [0.137, 0.349], + [0.127, 0.444], + [0.057, 0.504], + [-0.058, 0.504], + [-0.108, 0.464], + [-0.113, 0.394], + [-0.138, 0.359], + [-0.123, 0.259], + [-0.068, 0.174], + [-0.018, 0.184], + [-0.018, 0.099], + [-0.133, 0.099], + ], + }, + ], + }, + { + y0: 0.198, + y1: 0.218, + polygons: [ + { + outer: [ + [-0.138, -0.001], + [0.142, -0.001], + [0.142, 0.099], + [0.017, 0.099], + [0.017, 0.164], + [0.067, 0.164], + [0.082, 0.149], + [0.097, 0.169], + [0.152, 0.349], + [0.132, 0.474], + [0.062, 0.524], + [-0.063, 0.524], + [-0.128, 0.474], + [-0.148, 0.364], + [-0.133, 0.234], + [-0.083, 0.149], + [-0.063, 0.164], + [-0.018, 0.164], + [-0.018, 0.099], + [-0.138, 0.099], + ], + }, + ], + }, + { + y0: 0.218, + y1: 0.238, + polygons: [ + { + outer: [ + [-0.148, -0.001], + [0.147, -0.001], + [0.147, 0.099], + [0.017, 0.099], + [0.017, 0.139], + [0.082, 0.139], + [0.097, 0.124], + [0.112, 0.144], + [0.162, 0.334], + [0.147, 0.479], + [0.057, 0.544], + [-0.058, 0.544], + [-0.143, 0.484], + [-0.158, 0.299], + [-0.138, 0.189], + [-0.098, 0.124], + [-0.078, 0.139], + [-0.018, 0.139], + [-0.018, 0.099], + [-0.148, 0.099], + ], + }, + ], + }, + { + y0: 0.238, + y1: 0.258, + polygons: [ + { + outer: [ + [-0.153, -0.001], + [0.152, -0.001], + [0.152, 0.099], + [0.112, 0.099], + [0.142, 0.144], + [0.157, 0.209], + [0.167, 0.359], + [0.152, 0.479], + [0.062, 0.549], + [-0.058, 0.549], + [-0.148, 0.484], + [-0.163, 0.384], + [-0.158, 0.234], + [-0.148, 0.159], + [-0.113, 0.099], + [-0.153, 0.099], + ], + holes: [ + [ + [-0.098, 0.099], + [-0.093, 0.114], + [-0.018, 0.114], + [-0.018, 0.099], + ], + [ + [0.022, 0.099], + [0.017, 0.114], + [0.102, 0.104], + ], + ], + }, + ], + }, + { + y0: 0.258, + y1: 0.317, + polygons: [ + { + outer: [ + [-0.173, -0.001], + [0.177, -0.001], + [0.177, 0.099], + [0.162, 0.099], + [0.182, 0.339], + [0.167, 0.474], + [0.157, 0.499], + [0.067, 0.564], + [-0.063, 0.564], + [-0.163, 0.494], + [-0.178, 0.374], + [-0.163, 0.169], + ], + }, + { + outer: [ + [-0.013, 0.589], + [-0.008, 0.589], + [-0.003, 0.589], + [0.002, 0.589], + [0.007, 0.589], + [0.012, 0.589], + [0.012, 0.594], + [0.007, 0.594], + [0.007, 0.599], + [0.002, 0.599], + [-0.003, 0.599], + [-0.008, 0.599], + [-0.008, 0.594], + [-0.013, 0.594], + ], + }, + ], + }, + { + y0: 0.317, + y1: 0.377, + polygons: [ + { + outer: [ + [-0.188, -0.031], + [0.192, -0.031], + [0.202, 0.469], + [0.127, 0.574], + [0.007, 0.599], + [-0.128, 0.574], + [-0.193, 0.484], + ], + }, + ], + }, + { + y0: 0.377, + y1: 0.397, + polygons: [ + { + outer: [ + [-0.163, -0.111], + [0.162, -0.111], + [0.162, -0.031], + [0.192, -0.031], + [0.202, 0.469], + [0.127, 0.574], + [0.007, 0.599], + [-0.128, 0.574], + [-0.198, 0.474], + [-0.193, -0.006], + [-0.188, -0.031], + [-0.163, -0.031], + ], + }, + ], + }, + { + y0: 0.397, + y1: 0.417, + polygons: [ + { + outer: [ + [-0.163, -0.111], + [0.167, -0.111], + [0.167, 0.084], + [-0.163, 0.084], + ], + }, + { + outer: [ + [-0.183, 0.094], + [0.182, 0.094], + [0.187, 0.474], + [0.117, 0.564], + [-0.118, 0.564], + [-0.183, 0.479], + ], + }, + ], + }, + { + y0: 0.417, + y1: 0.437, + polygons: [ + { + outer: [ + [-0.163, -0.111], + [0.167, -0.111], + [0.167, 0.084], + [-0.163, 0.084], + ], + }, + { + outer: [ + [-0.163, 0.094], + [0.162, 0.094], + [0.172, 0.469], + [0.147, 0.504], + [-0.143, 0.504], + [-0.158, 0.489], + ], + }, + ], + }, + { + y0: 0.437, + y1: 0.754, + polygons: [ + { + outer: [ + [-0.188, -0.111], + [0.192, -0.111], + [0.192, 0.084], + [-0.188, 0.084], + ], + }, + ], + }, + { + y0: 0.754, + y1: 0.814, + polygons: [ + { + outer: [ + [-0.208, -0.116], + [0.212, -0.116], + [0.212, 0.094], + [-0.208, 0.094], + ], + }, + ], + }, + ], + }, + 'system/washing-machine': { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: 0.757, + polygons: [ + { + outer: [ + [-0.299, -0.253], + [0.301, -0.253], + [0.301, 0.257], + [0.206, 0.257], + [0.206, 0.272], + [0.181, 0.272], + [0.181, 0.277], + [-0.174, 0.277], + [-0.174, 0.272], + [-0.199, 0.272], + [-0.199, 0.257], + [-0.299, 0.257], + ], + }, + ], + }, + { + y0: 0.757, + y1: 0.857, + polygons: [ + { + outer: [ + [-0.299, -0.253], + [0.301, -0.253], + [0.301, 0.257], + [0.226, 0.257], + [0.226, 0.262], + [0.181, 0.262], + [0.181, 0.257], + [0.166, 0.257], + [0.166, 0.262], + [0.126, 0.262], + [0.126, 0.257], + [0.111, 0.257], + [0.111, 0.262], + [0.071, 0.262], + [0.071, 0.257], + [-0.299, 0.257], + ], + }, + ], + }, + ], + }, +} diff --git a/packages/core/src/spatial/usage-field/catalogue.ts b/packages/core/src/spatial/usage-field/catalogue.ts new file mode 100644 index 0000000000..1d2073c289 --- /dev/null +++ b/packages/core/src/spatial/usage-field/catalogue.ts @@ -0,0 +1,15 @@ +import type { GeometryShape } from '../../schema' +import { CATALOGUE_SHAPES } from './catalogue-shapes' + +const CATALOGUE_MODEL = /\/items\/([^/]+\/[^/]+)\/model\.glb(?:\?.*)?$/ + +/** A library model's key (`system/toilet`) from the URL its item points at, whatever the host serves it from. */ +export function catalogueKey(src: string): string | null { + return CATALOGUE_MODEL.exec(src)?.[1] ?? null +} + +/** What a library model occupies in plan, in its GLB's own frame, as baked by `bake-catalogue-shapes.ts`. */ +export function catalogueShape(src: string): GeometryShape | undefined { + const key = catalogueKey(src) + return key ? CATALOGUE_SHAPES[key] : undefined +} diff --git a/packages/core/src/spatial/usage-field/clash.ts b/packages/core/src/spatial/usage-field/clash.ts new file mode 100644 index 0000000000..f25a287586 --- /dev/null +++ b/packages/core/src/spatial/usage-field/clash.ts @@ -0,0 +1,211 @@ +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { area, intersection, type Ring } from '../../lib/polygon-boolean' +import type { ItemNode } from '../../schema' +import type { UsageIssue } from './findings' +import { cm, nameOf, quote, unique } from './labels' +import { + boxesMeet, + hosts, + isBuildingElement, + isFoliage, + isPiecePrism, + itemText, + narrowestExtent, + ringBox, + roomAt, +} from './pieces' +import type { Prism, UsageShapes } from './types' +import type { Nodes } from './walls' + +/** Two shapes that overlap by less than this are touching, not clashing (the outlines' own tolerance is 2 cm). */ +export const CLASH_INFO_M = 0.02 +/** From this depth a clash is a warning; between the two it is information. */ +export const CLASH_WARNING_M = 0.08 +/** A clash smaller than this in plan is a sliver (m²). */ +export const CLASH_MIN_AREA_M2 = 0.002 +/** A wall-fixed piece (a cabinet, a wall unit) may sink this far into a wall: it is scribed to it. */ +export const SCRIBE_M = 0.05 +const MIN_HEIGHT_OVERLAP_M = 0.02 +/** A piece this thin (a rug, a mat) is a covering, not something a piece stands in. */ +const FLAT_COVERING_M = 0.03 +/** A chair tucked under its table overlaps it by up to this much (m). */ +const TUCKED_M = 0.15 +const BUILT_IN = + /oven|hob\b|cook ?top|cooker|stove|range|washing|washer|dryer|dishwasher|sink|fridge|refrigerator/i +const SEAT = /(?:^|[^a-z])(?:chair|stool)(?![a-z])/i +const TABLE = /(?:^|[^a-z])(?:table|desk)(?![a-z])/i + +export const OBSTACLE_KINDS = new Set([ + 'wall', + 'jamb', + 'door-head', + 'threshold', + 'window-frame', + 'sill', + 'stair', + 'stair-rail', + 'guard', +]) + +type Pair = { + a: Prism + b: Prism + depth: number + area: number + at: [number, number] + zFrom: number + zTo: number +} + +const WHAT: Record = { + wall: 'the wall', + jamb: 'the frame of', + 'door-head': 'the frame of', + threshold: 'the threshold of', + 'window-frame': 'the frame of', + sill: 'the sill of', + stair: 'the stair', + 'stair-rail': 'the railing of', + guard: 'the guard', +} + +export function wallFixed(nodes: Nodes, prism: Prism): boolean { + if (prism.kind === 'cabinet' || prism.host) return true + const node = nodes[prism.nodeId] + const attach = node?.type === 'item' ? (node as ItemNode).asset?.attachTo : undefined + return attach === 'wall' || attach === 'wall-side' +} + +/** + * How deep two prisms stand in each other, or null: the same node, a host and what it carries, a wall + * and what is fixed to it, a contact, a sliver, a column that runs up into the piece above it, and a + * wall-fixed piece scribed to its wall are not clashes. + */ +export function pairClash( + nodes: Nodes, + a: Prism, + b: Prism, +): Pick | null { + if (a.nodeId === b.nodeId) return null + if (hosts(nodes, a.nodeId, b.nodeId) || hosts(nodes, b.nodeId, a.nodeId)) return null + if (a.host?.wallId === b.nodeId || b.host?.wallId === a.nodeId) return null + const z0 = Math.max(a.z0, b.z0) + const z1 = Math.min(a.z1, b.z1) + if (z1 - z0 < MIN_HEIGHT_OVERLAP_M) return null + const meet = intersection({ outer: a.outer, holes: a.holes }, { outer: b.outer, holes: b.holes }) + const size = area(meet) + if (size < CLASH_MIN_AREA_M2) return null + const depth = narrowestExtent(meet) + if (depth < CLASH_INFO_M) return null + // a column that runs up into the piece above it (a beam) is joined to it, not clashing + const column = a.kind === 'column' ? a : b.kind === 'column' ? b : null + if (column && z1 >= column.z1 - 0.05) return null + if (b.kind === 'wall' && wallFixed(nodes, a) && depth <= SCRIBE_M) return null + if (Math.min(a.z1 - a.z0, b.z1 - b.z0) <= FLAT_COVERING_M) return null + // a cabinet run is drawn as its box; the oven, hob or machine built into it is inside it by design + for (const [run, other] of [ + [a, b], + [b, a], + ] as const) + if ( + run.kind === 'cabinet' && + run.shape === 'approx' && + BUILT_IN.test(itemText(nodes, other.nodeId)) + ) + return null + if (depth <= TUCKED_M) + for (const [seat, table] of [ + [a, b], + [b, a], + ] as const) + if (SEAT.test(itemText(nodes, seat.nodeId)) && TABLE.test(itemText(nodes, table.nodeId))) + return null + const ring = meet[0]!.outer as Ring + return { + depth, + area: size, + at: [ + ring.reduce((sum, p) => sum + p[0], 0) / ring.length, + ring.reduce((sum, p) => sum + p[1], 0) / ring.length, + ], + zFrom: z0, + zTo: z1, + } +} + +/** + * A piece of furniture or a fixture that stands inside something solid: another piece, a wall body, a + * door or window frame or sill, a stair or a guard (a curtain or a blind is read with its opening). Read on the real outlines, so a + * contact (under 2 cm), a piece resting on another, a rug, foliage, a building element (trim, soffit, + * pier, beam) and a wall-fixed piece scribed to its wall (5 cm) stay quiet. From 2 cm it is information, + * from 8 cm a warning, with approximate outlines still labeled as such. + */ +export function clashIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { + const out: UsageIssue[] = [] + for (const level of shapes.levels) { + const prisms = level.prisms.filter( + (prism) => + !(nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode)), + ) + const pieces = prisms.filter( + (prism) => + isPiecePrism(prism) && + !isFoliage(nodes, prism.nodeId) && + !isBuildingElement(nodes, prism.nodeId), + ) + const others = prisms.filter( + (prism) => + (isPiecePrism(prism) || OBSTACLE_KINDS.has(prism.kind)) && + !isFoliage(nodes, prism.nodeId) && + !isBuildingElement(nodes, prism.nodeId), + ) + const boxes = new Map() + const box = (prism: Prism) => { + const known = boxes.get(prism) + if (known) return known + const fresh = ringBox(prism.outer) + boxes.set(prism, fresh) + return fresh + } + const found = new Map() + for (const a of pieces) { + for (const b of others) { + if (isPiecePrism(b) && b.nodeId < a.nodeId) continue + if (!boxesMeet(box(a), box(b))) continue + const clash = pairClash(nodes, a, b) + if (!clash) continue + const key = `${a.nodeId}|${b.nodeId}|${b.kind}` + const prior = found.get(key) + if (!prior || clash.depth > prior.depth) found.set(key, { a, b, ...clash }) + else prior.area += clash.area + } + } + for (const { a, b, depth, area: size, at } of found.values()) { + const approximate = a.shape === 'approx' || b.shape === 'approx' + const room = roomAt(nodes, level.levelId, at) + const who = quote(nameOf(nodes, a.nodeId)) + const target = isPiecePrism(b) + ? `${quote(nameOf(nodes, b.nodeId))}` + : `${WHAT[b.kind] ?? 'the'} ${quote(nameOf(nodes, b.nodeId))}` + const severity = depth >= CLASH_WARNING_M ? 'warning' : 'info' + out.push({ + type: 'usage_clash', + message: `${who} ${isPiecePrism(b) ? 'overlaps' : 'stands'} ${cm(depth)} ${isPiecePrism(b) ? 'of' : 'into'} ${target}${room ? ` in ${quote(room.name)}` : ''}${size >= 0.1 || approximate ? ` (${[size >= 0.1 ? `${Math.round(size * 1e4)} cm² in plan` : '', approximate ? 'approximate shape' : ''].filter(Boolean).join(', ')})` : ''}.`, + severity, + nodeIds: unique([room?.id, a.nodeId, b.nodeId]), + valueM: Math.round(depth * 1000) / 1000, + thresholdM: CLASH_WARNING_M, + place: { room: room?.name ?? '', roomId: room?.id ?? level.levelId, at }, + obstacles: [a, b].map((prism) => ({ + nodeId: prism.nodeId, + name: nameOf(nodes, prism.nodeId), + kind: prism.kind, + shape: prism.shape, + movable: false, + })), + approximate, + }) + } + } + return out +} diff --git a/packages/core/src/spatial/usage-field/door-stairs.ts b/packages/core/src/spatial/usage-field/door-stairs.ts new file mode 100644 index 0000000000..23ee153176 --- /dev/null +++ b/packages/core/src/spatial/usage-field/door-stairs.ts @@ -0,0 +1,151 @@ +import { CODE_PROFILES, type CodeProfile, codeProfileOf } from '../../building/code-profile' +import { area, difference, intersection, type Polygon, type Ring } from '../../lib/polygon-boolean' +import type { StairNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { + resolveStairWalkingSurfaces, + type StairWalkingSurface, +} from '../../systems/stair/stair-clearance' +import type { UsageIssue } from './findings' +import { m, nameOf, quote, unique } from './labels' +import { roomAt } from './pieces' +import { + doorFrame, + FRAME_M, + hingeOf, + hungOf, + leafDirection, + SWEEP_STEP_DEG, + swingDoors, +} from './swings' +import type { UsageShapes } from './types' +import type { Nodes } from './walls' + +/** A tread this far under the threshold or less is steps the leaf is read against; further down it is another storey's. */ +const BAND_M = 0.6 +/** Less of the sweep than this over a tread is the leaf grazing its edge (m2). */ +const MIN_OVERLAP_M2 = 0.01 +/** How far from the wall's centre line the room behind or ahead of a door is looked for (m). */ +const ROOM_PROBE_M = 0.4 +/** A floor within this far above the door's own still carries it (a slab's finish). */ +const FLOOR_ABOVE_M = 0.25 + +/** The ground a leaf covers while it opens: a fan from the hinge, closed to 90 degrees, as long as the leaf. */ +function sweptFan( + hinge: [number, number], + length: number, + direction: (theta: number) => [number, number], +): Ring { + const ring: Ring = [hinge] + for (let a = 0; a <= 90; a += SWEEP_STEP_DEG) { + const [dx, dz] = direction((a * Math.PI) / 180) + ring.push([hinge[0] + dx * length, hinge[1] + dz * length]) + } + return ring +} + +/** + * A door whose leaf swings over steps. Both texts the checks read say it: a floor or landing is not + * required at the top of an interior flight "provided that a door does not swing over the stairs" + * (R311.7.6), and a landing at an exterior door may be 7-3/4 in below the threshold, or a flight of two + * risers need no top landing, only where the door does not swing over it (R311.3.1, R311.3.2). So the + * leaf's sweep is read against the treads and landings of every stair that lie more than 1-1/2 in below + * the door's own floor; ground the door's level covers (a slab, a landing at the threshold) is not steps. + * The text says nothing of a door swinging over a flat landing: that is a design preference (Architect + * Pro's `door_over_landing` keeps both landings clear), not this check. + * + * It is a code's rule. With no `site.metadata.codeProfile` a finding is information that names the US + * IRC it used; with `irc-2021` it is a warning; a profile with no row for it reports nothing. + */ +export function doorOverStairIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { + const profile = codeProfileOf(nodes) + const applied: CodeProfile = profile ?? CODE_PROFILES['irc-2021'] + const row = applied.thresholds.doorThresholdDrop + if (!row) return [] + + const stairs: { stair: StairNode; surfaces: StairWalkingSurface[] }[] = [] + for (const node of Object.values(nodes)) { + if (node.type !== 'stair') continue + try { + stairs.push({ stair: node, surfaces: resolveStairWalkingSurfaces(node, nodes as never) }) + } catch { + // a stair whose surfaces cannot be read (its detail is over budget) has nothing to sweep against + } + } + if (stairs.length === 0) return [] + + const elevations = getLevelElevations(nodes as never) + const out: UsageIssue[] = [] + for (const level of shapes.levels) { + const baseY = elevations.get(level.levelId)?.baseY ?? 0 + const steps = stairs + .map(({ stair, surfaces }) => ({ + stair, + surfaces: surfaces.filter( + (surface) => surface.top <= baseY - row.value && surface.top >= baseY - BAND_M, + ), + })) + .filter(({ surfaces }) => surfaces.length > 0) + if (steps.length === 0) continue + const floors: Polygon[] = shapes.levels + .flatMap((other) => other.floors) + .filter((floor) => floor.y >= baseY - row.value && floor.y <= baseY + FLOOR_ABOVE_M) + .map((floor) => ({ outer: floor.outer, holes: floor.holes })) + + for (const door of swingDoors(nodes, level.levelId)) { + const hung = hungOf(door) + const frame = doorFrame(nodes, door) + const hinge = hingeOf(nodes, door, hung) + const fan = sweptFan(hinge, 2 * frame.half - FRAME_M, (theta) => + leafDirection(frame, hung, theta), + ) + // the room the door belongs to is the one behind the leaf; failing that, the one it swings into + const centre: [number, number] = [ + frame.sx + frame.tx * frame.along, + frame.sz + frame.tz * frame.along, + ] + const beside = (side: number): [number, number] => [ + centre[0] + frame.nx * hung.swing * side * ROOM_PROBE_M, + centre[1] + frame.nz * hung.swing * side * ROOM_PROBE_M, + ] + const room = + roomAt(nodes, level.levelId, beside(-1)) ?? roomAt(nodes, level.levelId, beside(1)) + for (const { stair, surfaces } of steps) { + let over = 0 + let nearest = Number.NEGATIVE_INFINITY + for (const surface of surfaces) { + const swept = intersection(fan, surface.region) + if (swept.length === 0) continue + const bare = area(floors.length ? difference(swept, floors) : swept) + if (bare < MIN_OVERLAP_M2) continue + over += bare + nearest = Math.max(nearest, surface.top) + } + if (over === 0) continue + const drop = baseY - nearest + const name = nameOf(nodes, door.id) + const stairName = nameOf(nodes, stair.id) + out.push({ + type: 'usage_door_over_stair', + message: `${quote(name)}${room ? ` in ${quote(room.name)}` : ''} swings over the steps of ${quote(stairName)}: its leaf passes over ${m(over)} m² of treads, the nearest ${m(drop)} m below the threshold, where ${applied.label} (${row.section}) wants a floor or landing for the leaf to open onto${profile ? '' : ', and this project names no code'}. Swing it the other way, hinge it on the other side, or give the stair a landing as deep as the door is wide.`, + severity: profile ? 'warning' : 'info', + nodeIds: unique([room?.id, door.id, stair.id]), + valueM: Math.round(drop * 1000) / 1000, + thresholdM: row.value, + place: { room: room?.name ?? '', roomId: room?.id ?? level.levelId, at: hinge }, + obstacles: [ + { nodeId: stair.id, name: stairName, kind: 'stair', shape: 'exact', movable: false }, + ], + approximate: false, + code: { + profile: applied.id, + cite: row.cite, + source: row.source, + byDefault: profile === null, + }, + }) + } + } + } + return out +} diff --git a/packages/core/src/spatial/usage-field/engine.test.ts b/packages/core/src/spatial/usage-field/engine.test.ts new file mode 100644 index 0000000000..a88bcbc359 --- /dev/null +++ b/packages/core/src/spatial/usage-field/engine.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, BuildingNode, DoorNode, LevelNode, SlabNode, WallNode } from '../../schema' +import { BucketIndex, bakeGrid, cellOf, cellX, cellZ, makeGrid } from './field' +import { BODY_BAND, buildField, floorGroups } from './level-field' +import { obstaclesInBand, signedDistance } from './obstacles' +import { pathTo, refinePassage, travel, widestPath } from './path' +import { usageShapes } from './shapes' +import type { Nodes } from './walls' + +function house(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const wall = ( + id: string, + start: [number, number], + end: [number, number], + children: string[] = [], +) => WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.1, children }) + +// A 6 x 4 m shell with a partition at x = 3 and a 0.9 m door in it, on a slab that reaches 0.3 m +// past the shell so the doorway of the south wall has floor to walk out onto. +function twoRooms(partitionDoor = 0.9) { + const door = DoorNode.parse({ + id: 'door_1', + parentId: 'wall_p', + wallId: 'wall_p', + position: [2, 1.05, 0], + width: partitionDoor, + height: 2.1, + }) + return house([ + SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + elevation: 0.05, + }), + wall('wall_s', [0, 0], [6, 0]), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + wall('wall_p', [3, 0], [3, 4], ['door_1']), + door, + ]) +} + +describe('the clearance field', () => { + const shapes = usageShapes(twoRooms()) + const [group] = floorGroups(shapes) + const field = buildField(shapes, group!, BODY_BAND, 0.02) + + test('the floor group stands at the slab surface and the band above it', () => { + expect(group!.y).toBeCloseTo(0.05, 6) + expect(field.band.z0).toBeCloseTo(0.08, 6) + expect(field.band.z1).toBeCloseTo(2.05, 6) + }) + + test('clearance at the middle of a room is the distance to the nearest wall face', () => { + // west room: 0.05..2.95 wide and 0.05..3.95 deep: the middle is 1.45 from both partition and west wall + const c = cellOf(field.grid, 1.5, 2) + expect(field.F[c]).toBeCloseTo(1.45, 1) + expect(field.free[c]).toBe(1) + const inWall = cellOf(field.grid, 3, 3.5) + expect(field.F[inWall]).toBeLessThan(0) + expect(field.free[inWall]).toBe(0) + }) + + test('the bucket index answers exactly what a scan of every obstacle does', () => { + const index = new BucketIndex(field.obstacles, group!.domain) + for (const [x, z] of [ + [1, 1], + [2.95, 2], + [3.04, 0.2], + [4.5, 3.9], + [6.1, 4.1], + [-0.2, 2], + ] as const) { + const brute = Math.min(...field.obstacles.map((o) => signedDistance(o.edges, x, z))) + expect(index.query(x, z).d).toBeCloseTo(brute, 9) + } + }) + + test('the tiled bake equals the exact field cell for cell', () => { + const g = makeGrid(group!.domain, 0.1) + const baked = bakeGrid(g, field.obstacles) + for (let j = 0; j < g.H; j += 7) + for (let i = 0; i < g.W; i += 5) { + const brute = Math.min( + ...field.obstacles.map((o) => signedDistance(o.edges, cellX(g, i), cellZ(g, j))), + ) + expect(Math.abs(baked.F[j * g.W + i]! - brute)).toBeLessThan(1e-5) + } + }) + + test('only prisms meeting the band are obstacles: a door head above it is not, a jamb is', () => { + const kinds = new Set(field.obstacles.map((o) => o.prism.kind)) + expect(kinds.has('jamb')).toBe(true) + expect(kinds.has('door-head')).toBe(false) + expect( + obstaclesInBand( + shapes.levels.flatMap((l) => l.prisms), + { z0: 3, z1: 4 }, + ), + ).toHaveLength(0) + }) +}) + +describe('paths through the field', () => { + test('the widest path to the far room goes through the door and its width is the clear door', () => { + const shapes = usageShapes(twoRooms(0.9)) + const [group] = floorGroups(shapes) + const field = buildField(shapes, group!, BODY_BAND, 0.02) + const source = cellOf(field.grid, 1.5, 2) + const target = cellOf(field.grid, 4.5, 2) + const { B, P } = widestPath(field.grid, field.F, field.floor, [source]) + expect(B[target]).toBeGreaterThan(0.39) + const path = pathTo(P, field.F, target) + // the grid bottleneck is within a cell of the clear width between the jambs (0.9 less two frame members of 0.05) + expect(Math.abs(2 * field.F[path.cells[path.narrowest]!]! - 0.8)).toBeLessThan(0.05) + const refined = refinePassage( + field.grid, + field.F, + field.index, + path, + (cell) => cell === source, + (x, z) => Math.hypot(x - 4.5, z - 2) < 0.2, + ) + expect(refined.width).toBeGreaterThan(0.79) + expect(refined.width).toBeLessThan(0.81) + expect(refined.at[0]).toBeCloseTo(3, 1) + }) + + test('a doorway too narrow for the unit leaves the far room out of reach', () => { + const shapes = usageShapes(twoRooms(0.6)) + const [group] = floorGroups(shapes) + const field = buildField(shapes, group!, BODY_BAND, 0.02) + const pass = new Uint8Array(field.free.length) + for (let c = 0; c < pass.length; c++) pass[c] = field.floor[c] && field.F[c]! >= 0.3 ? 1 : 0 + const reach = travel(field.grid, pass, [cellOf(field.grid, 1.5, 2)]) + expect(reach[cellOf(field.grid, 1.5, 3)]).toBeGreaterThan(0) + // 0.6 m door: 0.5 m between the jambs: a clearance of 0.25, below the unit's 0.30 + expect(reach[cellOf(field.grid, 4.5, 2)]).toBe(Number.POSITIVE_INFINITY) + }) + + test('travel distance is the metric length of the way', () => { + const shapes = usageShapes(twoRooms(0.9)) + const [group] = floorGroups(shapes) + const field = buildField(shapes, group!, BODY_BAND, 0.05) + const pass = new Uint8Array(field.free.length) + for (let c = 0; c < pass.length; c++) pass[c] = field.floor[c] && field.F[c]! >= 0.3 ? 1 : 0 + const from = cellOf(field.grid, 1, 2) + const reach = travel(field.grid, pass, [from]) + // straight along the room: 1 -> 2.5 is 1.5 m, the 16-neighbour metric overestimates by at most 8% + const there = reach[cellOf(field.grid, 2.5, 2)]! + expect(there).toBeGreaterThan(1.49) + expect(there).toBeLessThan(1.5 * 1.08) + }) +}) diff --git a/packages/core/src/spatial/usage-field/entry-way.ts b/packages/core/src/spatial/usage-field/entry-way.ts new file mode 100644 index 0000000000..dac7e72637 --- /dev/null +++ b/packages/core/src/spatial/usage-field/entry-way.ts @@ -0,0 +1,262 @@ +import { floorsOf } from '../../agent-operations/circulation-spaces' +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { area, containsPoint, intersection } from '../../lib/polygon-boolean' +import type { DoorNode, ItemNode, WallNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { getWallThickness } from '../../systems/wall/wall-footprint' +import { getWallLocalFaceZ } from '../../systems/wall/wall-frame' +import { CLASH_INFO_M, CLASH_MIN_AREA_M2, wallFixed } from './clash' +import { DOOR_M, PASSAGE_M, type UsageIssue } from './findings' +import { m, nameOf, quote, unique } from './labels' +import { doorwayRing } from './openings' +import { + boxesMeet, + isBuildingElement, + isFoliage, + isPiecePrism, + narrowestExtent, + ringBox, +} from './pieces' +import { doorFrame, FIXTURE } from './swings' +import type { Prism, Ring, UsageShapes } from './types' +import { levelWalls, type Nodes } from './walls' +import { wayIn } from './way-in' + +type Point = [number, number] +type Entrance = { ring: Ring; at: Point; door?: DoorNode } + +/** Where a doorway is looked at from: this far to either side of the wall's middle (m). */ +const SIDE_M = 0.3 +/** A zone edge is sampled this often (m) to find where no wall stands on it. */ +const SAMPLE_M = 0.05 +/** Joinery made for the room: a built-in robe or a fitted unit is where it was designed to be. */ +const BUILT_IN = /built[- ]?in|fitted|joinery/i +/** A wall stands on a zone edge when its middle line is within half its thickness and this much (m). */ +const SCRIBE_M = 0.02 +/** An open edge is a passage of this half thickness across (m): a doorway's, a wall's half thickness and a centimetre. */ +const OPEN_HALF_M = 0.065 + +/** The segment's distance from a point. */ +function segmentDistance(p: Point, a: Point, b: Point): number { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const length2 = dx * dx + dz * dz + const t = + length2 < 1e-12 + ? 0 + : Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length2)) + return Math.hypot(p[0] - (a[0] + dx * t), p[1] - (a[1] + dz * t)) +} + +/** + * The stretches of a zone's boundary with no wall on them, a doorway's width or more: where the room is + * open to the one beside it. A ring across each, a wall's thickness deep, is the way in. + */ +function openEntrances( + walls: WallNode[], + zone: { polygon: Ring; holes: Ring[] }, + zones: { id: string; polygon: Ring; holes: Ring[] }[], + self: string, +): Entrance[] { + const out: Entrance[] = [] + const covered = (p: Point) => + walls.some( + (wall) => + segmentDistance(p, wall.start as Point, wall.end as Point) <= + getWallThickness(wall) / 2 + SCRIBE_M, + ) + for (const [i, a] of zone.polygon.entries()) { + const b = zone.polygon[(i + 1) % zone.polygon.length]! + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + if (length < DOOR_M) continue + const tx = (b[0] - a[0]) / length + const tz = (b[1] - a[1]) / length + const steps = Math.ceil(length / SAMPLE_M) + let from = -1 + const close = (last: number) => { + const s0 = (from * length) / steps + const s1 = (last * length) / steps + if (from >= 0 && s1 - s0 >= DOOR_M) { + const p0: Point = [a[0] + tx * s0, a[1] + tz * s0] + const p1: Point = [a[0] + tx * s1, a[1] + tz * s1] + const mid: Point = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2] + // a room beyond: the opening is a way between two rooms, not a gap in the outline + const beyond = [1, -1].some((side) => { + const q: Point = [mid[0] - tz * side * SIDE_M, mid[1] + tx * side * SIDE_M] + return ( + !containsPoint([{ outer: zone.polygon, holes: zone.holes }], q) && + zones.some( + (z) => z.id !== self && containsPoint([{ outer: z.polygon, holes: z.holes }], q), + ) + ) + }) + if (beyond) + out.push({ + ring: [ + [p0[0] - tz * OPEN_HALF_M, p0[1] + tx * OPEN_HALF_M], + [p1[0] - tz * OPEN_HALF_M, p1[1] + tx * OPEN_HALF_M], + [p1[0] + tz * OPEN_HALF_M, p1[1] - tx * OPEN_HALF_M], + [p0[0] + tz * OPEN_HALF_M, p0[1] - tx * OPEN_HALF_M], + ], + at: mid, + }) + } + from = -1 + } + for (let s = 0; s <= steps; s++) { + const p: Point = [a[0] + (tx * s * length) / steps, a[1] + (tz * s * length) / steps] + if (covered(p)) { + if (from >= 0) close(s - 1) + } else if (from < 0) from = s + } + if (from >= 0) close(steps) + } + return out +} + +/** The doors of a level that lead into a zone: a doorway of any kind but a vehicle's whose one side, and only one, is in the zone. */ +function doorEntrances( + nodes: Nodes, + doors: DoorNode[], + zone: { polygon: Ring; holes: Ring[] }, +): Entrance[] { + const out: Entrance[] = [] + for (const door of doors) { + const f = doorFrame(nodes, door) + const across = (getWallLocalFaceZ(f.wall, 'a') + getWallLocalFaceZ(f.wall, 'b')) / 2 + const side = (sign: number): Point => [ + f.sx + f.tx * f.along + f.nx * (across + sign * SIDE_M), + f.sz + f.tz * f.along + f.nz * (across + sign * SIDE_M), + ] + const inside = [1, -1].filter((sign) => + containsPoint([{ outer: zone.polygon, holes: zone.holes }], side(sign)), + ) + if (inside.length !== 1) continue + const ring = doorwayRing(f.wall, door) + if (!ring) continue + out.push({ + ring, + at: [f.sx + f.tx * f.along + f.nx * across, f.sz + f.tz * f.along + f.nz * across], + door, + }) + } + return out +} + +/** + * What closes off part of a room: from each entrance of a room (a doorway, or an open edge to the room + * beside it) the widest way to the room's open floor, with the pieces of furniture standing where they + * are. A way under a passage's width that a piece bounds is a finding that names the piece, the room and + * what is on the other side of the pinch. A leaf swinging open is `doorSwingIssues`'s, a doorway's own + * width and the walls' are the passage measure's: only a free-standing piece is named. What is built to + * stand there stays quiet: a kitchen run or anything on a wall, a fixture, built-in joinery, foliage, a + * building element, a rug, a piece on another piece. A room narrower than a passage is judged on its doorway only. + */ +export function entryIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { + const out: UsageIssue[] = [] + const floors = floorsOf(nodes).floors + const elevations = getLevelElevations(nodes as never) + for (const level of shapes.levels) { + const floor = floors.find((f) => f.id === level.levelId) + if (!floor) continue + const baseY = elevations.get(level.levelId)?.baseY ?? 0 + const isUnderlay = (prism: Prism) => + nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode) + const standing = (prism: Prism) => { + const node = nodes[prism.nodeId] + return ( + (prism.kind === 'item' || prism.kind === 'shelf') && + isPiecePrism(prism) && + !wallFixed(nodes, prism) && + !isUnderlay(prism) && + !isFoliage(nodes, prism.nodeId) && + !isBuildingElement(nodes, prism.nodeId) && + !FIXTURE.test(nameOf(nodes, prism.nodeId)) && + !BUILT_IN.test(nameOf(nodes, prism.nodeId)) && + nodes[node?.parentId ?? '']?.type !== 'item' + ) + } + const named = new Set(level.prisms.filter(standing).map((prism) => prism.id)) + if (named.size === 0) continue + const namedPrisms = level.prisms.filter((prism) => named.has(prism.id)) + const walls = levelWalls(nodes, level.levelId) + const wallIds = new Set(walls.map((wall) => wall.id)) + const doors = Object.values(nodes).filter( + (node): node is DoorNode => + node.type === 'door' && + node.visible !== false && + !String(node.doorType).startsWith('garage') && + wallIds.has(node.parentId ?? ''), + ) + const zones = floor.zones.filter((zone) => !zone.outdoor) + const found = new Map() + for (const zone of zones) { + if (narrowestExtent([{ outer: zone.polygon }]) < PASSAGE_M) continue + const zoneBox = ringBox(zone.polygon) + // a piece is in the room when it stands a contact's depth inside it: one against the wall on the other side is that room's + const here = new Set( + namedPrisms + .filter((prism) => { + if (!boxesMeet(ringBox(prism.outer), zoneBox)) return false + const meet = intersection( + { outer: prism.outer, holes: prism.holes }, + { outer: zone.polygon, holes: zone.holes }, + ) + return area(meet) >= CLASH_MIN_AREA_M2 && narrowestExtent(meet) >= CLASH_INFO_M + }) + .map((prism) => prism.id), + ) + if (here.size === 0) continue + const room = { id: zone.id, name: nameOf(nodes, zone.id) } + const entrances = [ + ...doorEntrances(nodes, doors, zone), + ...openEntrances(walls, zone, zones, zone.id), + ] + for (const entrance of entrances) { + const way = wayIn( + shapes, + level, + zone, + entrance.ring, + entrance.at, + baseY, + isUnderlay, + (prism) => here.has(prism.id), + ) + if (!way) continue + const subject = way.by.find((o) => here.has(o.prism.id))! + const other = way.by.find((o) => o !== subject) + const approximate = way.by.some((o) => o.prism.shape === 'approx') + const key = `${zone.id}|${subject.prism.nodeId}` + if ((found.get(key)?.width ?? Number.POSITIVE_INFINITY) <= way.width) continue + found.set(key, { + width: way.width, + issue: { + type: 'usage_entry_narrow', + message: `${quote(nameOf(nodes, subject.prism.nodeId))} leaves ${m(way.width)} m to enter ${quote(room.name)}, ${other ? `between it and ${quote(nameOf(nodes, other.prism.nodeId))}` : 'against it'} (below ${m(PASSAGE_M)} m).`, + severity: 'warning', + nodeIds: unique([ + room.id, + subject.prism.nodeId, + other?.prism.nodeId, + entrance.door?.id, + ]), + valueM: way.width, + thresholdM: PASSAGE_M, + place: { room: room.name, roomId: room.id, at: way.at }, + obstacles: way.by.map((o) => ({ + nodeId: o.prism.nodeId, + name: nameOf(nodes, o.prism.nodeId), + kind: o.prism.kind, + shape: o.prism.shape, + movable: false, + })), + approximate, + }, + }) + } + } + out.push(...[...found.values()].map(({ issue }) => issue)) + } + return out +} diff --git a/packages/core/src/spatial/usage-field/fences.test.ts b/packages/core/src/spatial/usage-field/fences.test.ts new file mode 100644 index 0000000000..eebbbefff3 --- /dev/null +++ b/packages/core/src/spatial/usage-field/fences.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, BuildingNode, FenceGateNode, FenceNode, LevelNode } from '../../schema' +import { fenceBodies } from './fences' +import type { Nodes } from './walls' + +function scene(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +describe('fences', () => { + test('a fence is a strip along its centreline from its support to its height', () => { + const fence = FenceNode.parse({ + id: 'fence_1', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + height: 1.8, + thickness: 0.08, + postSize: 0.1, + }) + const [shape] = fenceBodies(scene([fence])).fences + expect(shape!.prisms).toHaveLength(1) + const [prism] = shape!.prisms + expect([prism!.z0, prism!.z1]).toEqual([0, 1.8]) + const zs = prism!.outer.map(([, z]) => z) + expect(Math.max(...zs) - Math.min(...zs)).toBeCloseTo(0.1, 6) + expect(prism!.shape).toBe('approx') + }) + + test('a deck guard is read part by part: posts, cap, top rail, bottom rail and the infill as one strip', () => { + const fence = FenceNode.parse({ + id: 'fence_1', + parentId: 'level_1', + start: [0, 0], + end: [4, 0], + style: 'guard', + height: 1.05, + postSpacing: 1.6, + }) + const { prisms } = fenceBodies(scene([fence])).fences[0]! + const group = (name: string) => prisms.filter((p) => p.id.startsWith(`fence_1#${name}.`)) + expect(group('post')).toHaveLength(4) + expect(group('rail')).toHaveLength(2) + expect(group('base')).toHaveLength(1) + expect(group('infill')).toHaveLength(1) + expect(prisms.every((p) => p.shape === 'exact' && p.kind === 'guard')).toBe(true) + // the cap is 5.5 in wide, wider than the 0.1 post and the 0.08 strip a plain fence is + const cap = group('rail')[0]! + const zs = cap.outer.map(([, z]) => z) + expect(Math.max(...zs) - Math.min(...zs)).toBeCloseTo(5.5 * 0.0254, 6) + expect(cap.z1).toBeCloseTo(1.05, 9) + // the infill strip stands between the bottom rail and the top rail + const [infill] = group('infill') + expect(infill!.z0).toBeGreaterThan(group('base')[0]!.z0) + expect(infill!.z1).toBeLessThanOrEqual(cap.z0) + }) + + test('a gate takes its width out of the strip', () => { + const gate = FenceGateNode.parse({ + id: 'fence-gate_1', + parentId: 'fence_1', + center: 2, + width: 1, + }) + const fence = FenceNode.parse({ + id: 'fence_1', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + children: [gate.id], + }) + const { prisms } = fenceBodies(scene([fence, gate])).fences[0]! + expect(prisms).toHaveLength(2) + const xs = (i: number) => prisms[i]!.outer.map(([x]) => x) + expect(Math.max(...xs(0))).toBeCloseTo(1.5, 6) + expect(Math.min(...xs(1))).toBeCloseTo(2.5, 6) + expect(Math.max(...xs(1))).toBeCloseTo(6, 6) + }) + + test('a curved fence is a run of strips', () => { + const fence = FenceNode.parse({ + id: 'fence_1', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + curveOffset: 1, + }) + expect(fenceBodies(scene([fence])).fences[0]!.prisms.length).toBeGreaterThan(4) + }) +}) diff --git a/packages/core/src/spatial/usage-field/fences.ts b/packages/core/src/spatial/usage-field/fences.ts new file mode 100644 index 0000000000..14ef8ff103 --- /dev/null +++ b/packages/core/src/spatial/usage-field/fences.ts @@ -0,0 +1,307 @@ +import { resolveLevelId } from '../../lib/node-ancestry' +import type { AnyNode, FenceNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { sampleFenceCenterline } from '../../systems/fence/fence-centerline' +import { isSplineFence } from '../../systems/fence/fence-spline' +import { + fenceBlockCorners, + fenceBlockSegments, + fenceMiter, + type GuardBlock, + layoutGuardFence, +} from '../../systems/fence/guard-layout' +import { isCurvedWall } from '../../systems/wall/wall-curve' +import { floorUnder, isHidden, type SupportCache } from './support' +import type { Prism, Ring, Skipped } from './types' +import type { Nodes } from './walls' + +type Point = [number, number] + +/** Samples of a straight stretch carry no information: drop points less than 2 mm off the line around them. */ +function thinned(points: Point[]): Point[] { + const kept: Point[] = [points[0]!] + for (let i = 1; i < points.length - 1; i++) { + const a = kept.at(-1)! + const c = points[i + 1]! + const dx = c[0] - a[0] + const dz = c[1] - a[1] + const length = Math.hypot(dx, dz) + const off = + length < 1e-9 + ? 0 + : Math.abs((points[i]![0] - a[0]) * dz - (points[i]![1] - a[1]) * dx) / length + if (off > 0.002) kept.push(points[i]!) + } + kept.push(points.at(-1)!) + return kept +} +export type FencePrisms = { fenceId: string; levelId: string | null; prisms: Prism[] } + +/** A fence's span between arc lengths `from` and `to`, as the centreline points inside it. */ +function span(points: Point[], lengths: number[], from: number, to: number): Point[] { + const at = (s: number): Point => { + for (let i = 1; i < points.length; i++) + if (s <= lengths[i]! || i === points.length - 1) { + const run = lengths[i]! - lengths[i - 1]! + const t = + run > 1e-9 + ? (Math.min(Math.max(s, lengths[i - 1]!), lengths[i]!) - lengths[i - 1]!) / run + : 0 + return [ + points[i - 1]![0] + (points[i]![0] - points[i - 1]![0]) * t, + points[i - 1]![1] + (points[i]![1] - points[i - 1]![1]) * t, + ] + } + return points[0]! + } + const inside = points.filter((_, i) => lengths[i]! > from + 1e-9 && lengths[i]! < to - 1e-9) + return [at(from), ...inside, at(to)] +} + +type Corner = [number, number] + +/** The longest a run of a curved guard is drawn straight: the renderer's own. */ +const CURVE_SEGMENT_M = 0.18 + +/** The footprint of a box `w` x `d` centred on (x, z) and turned `rotationY` about the vertical axis, as the renderer turns it. */ +function box(x: number, z: number, w: number, d: number, rotationY: number): Ring { + const cos = Math.cos(rotationY) + const sin = Math.sin(rotationY) + return [ + [-w / 2, -d / 2], + [w / 2, -d / 2], + [w / 2, d / 2], + [-w / 2, d / 2], + ].map(([cx, cz]): Corner => [x + cx! * cos + cz! * sin, z - cx! * sin + cz! * cos]) +} + +/** The fences that share an end with this one, by end, as the renderer finds them for its corner mitres. */ +function cornerNeighbors( + fence: FenceNode, + nodes: Nodes, +): Partial> { + const found: Partial> = {} + for (const sibling of Object.values(nodes) as AnyNode[]) { + if (sibling.type !== 'fence' || sibling.id === fence.id || sibling.parentId !== fence.parentId) + continue + if (sibling.visible === false) continue + for (const endpoint of ['start', 'end'] as const) { + const point = fence[endpoint] + if ( + [sibling.start, sibling.end].some( + (other) => Math.hypot(point[0] - other[0], point[1] - other[1]) < 0.001, + ) && + !found[endpoint] + ) + found[endpoint] = sibling + } + } + return found +} + +/** + * A deck guard as the renderer builds it (`layoutGuardFence`, the same layout its meshes come from): + * every post, the cap rail and top rail, the bottom rail, and the infill, with the cap and rails + * mitred where a fence meets another. The infill is taken as one solid strip: balusters, cables and + * boards stand a hand apart and nothing a person carries goes between them. A pyramid post cap is + * drawn as its base. + */ +function guardPrisms( + fence: FenceNode, + neighbors: Partial>, + z0: number, +): Prism[] { + const layout = layoutGuardFence(fence) + const prisms: Prism[] = [] + const straight = !isSplineFence(fence) && !isCurvedWall(fence) + // a straight fence stands at one lift (the support at its start); a curved one follows the terrain + const follows = straight + ? undefined + : 'a curved guard follows the terrain: its heights are read at its start' + const common = { nodeId: fence.id, kind: 'guard' as const, holes: [] } + const add = (id: string, y0: number, y1: number, outer: Ring, approx?: string) => { + if (y1 - y0 > 1e-4) + prisms.push({ + id: `${fence.id}#${id}`, + ...common, + z0: z0 + y0, + z1: z0 + y1, + outer, + ...(approx || follows + ? { shape: 'approx' as const, why: approx ?? follows } + : { shape: 'exact' as const }), + }) + } + for (const [i, post] of layout.posts.entries()) { + const [x, y, z] = post.position + const [w, h, d] = post.scale + if (post.shape === 'pyramid') + add( + `post.${i}`, + y - h / 2, + y + h / 2, + box(x, z, w * Math.SQRT1_2, d * Math.SQRT1_2, post.rotationY), + 'a pyramid post cap, drawn as its base', + ) + else add(`post.${i}`, y - h / 2, y + h / 2, box(x, z, w, d, post.rotationY)) + } + // a run is one quad on a straight fence and a quad per short segment on a curved one + const run = (name: string, block: GuardBlock, mitre: boolean) => { + const segments: [number, number][] = straight + ? [[block.startT, block.endT]] + : fenceBlockSegments(fence, block.startT, block.endT, CURVE_SEGMENT_M) + for (const [k, [a, b]] of segments.entries()) { + const [startOuter, startInner, endOuter, endInner] = fenceBlockCorners( + fence, + a, + b, + block.depth, + ) + const corners = { startOuter, startInner, endOuter, endInner } + if (mitre) + for (const endpoint of ['start', 'end'] as const) { + const neighbor = neighbors[endpoint] + if ( + !neighbor || + Math.abs((endpoint === 'start' ? a : b) - (endpoint === 'start' ? 0 : 1)) > 1e-5 + ) + continue + for (const { side, reach, ux, uz } of fenceMiter( + fence, + endpoint, + neighbor, + block.depth, + ) ?? []) { + const key = `${endpoint}${side === 1 ? 'Outer' : 'Inner'}` as keyof typeof corners + corners[key] = [corners[key][0] + ux * reach, corners[key][1] + uz * reach] + } + } + add(`${name}.${k}`, block.centerY - block.height / 2, block.centerY + block.height / 2, [ + corners.startOuter, + corners.endOuter, + corners.endInner, + corners.startInner, + ]) + } + } + for (const [i, block] of layout.rail.entries()) run(`rail.${i}`, block, true) + for (const [i, block] of layout.base.entries()) run(`base.${i}`, block, true) + // the infill: one strip, as high as the infill is, as deep as its pieces are + const infill = layout.infill + if (infill.length) { + const y0 = Math.min(...infill.map((b) => b.centerY - b.height / 2)) + const y1 = Math.max(...infill.map((b) => b.centerY + b.height / 2)) + const first = infill[0]! + run( + 'infill', + { + startT: 0, + endT: 1, + centerY: (y0 + y1) / 2, + height: y1 - y0, + depth: first.depth, + split: true, + }, + false, + ) + } + return prisms +} + +/** + * A deck guard with nothing cut into it is read part by part (`guardPrisms`). Every other fence is + * a strip along its centreline, as wide as its thicker of thickness and post, from its support to + * its height, with a gate or an open passage taken out of it; the infill is not drawn (a picket + * fence is solid to a person) and the height does not follow terrain, so it is approximate. + */ +export function fenceBodies(nodes: Nodes): { fences: FencePrisms[]; skipped: Skipped[] } { + const out: FencePrisms[] = [] + const skipped: Skipped[] = [] + const elevations = getLevelElevations(nodes as never) + const support: SupportCache = new Map() + for (const node of Object.values(nodes) as AnyNode[]) { + if (node.type !== 'fence' || isHidden(node, nodes)) continue + const fence = node + try { + const points = thinned(sampleFenceCenterline(fence).map((p): Point => [p.x, p.y])) + if (points.length < 2) continue + const lengths = [0] + for (let i = 1; i < points.length; i++) + lengths.push( + lengths[i - 1]! + + Math.hypot(points[i]![0] - points[i - 1]![0], points[i]![1] - points[i - 1]![1]), + ) + const total = lengths.at(-1)! + const gaps = (fence.children ?? []) + .map((id) => nodes[id]) + .flatMap((child) => + child?.type === 'fence-gate' || child?.type === 'fence-opening' + ? [[child.center - child.width / 2, child.center + child.width / 2] as const] + : [], + ) + .sort((a, b) => a[0] - b[0]) + const spans: [number, number][] = [] + let from = 0 + for (const [start, end] of gaps) { + if (start > from) spans.push([from, Math.min(start, total)]) + from = Math.max(from, end) + } + if (from < total) spans.push([from, total]) + const levelId = resolveLevelId(fence, nodes as Record) + const baseY = elevations.get(levelId)?.baseY ?? 0 + const floor = floorUnder( + fence, + { + position: [points[0]![0], 0, points[0]![1]], + dimensions: [fence.thickness, fence.height, fence.thickness], + rotation: [0, 0, 0], + }, + nodes, + levelId, + support, + ) + const half = Math.max(fence.thickness, fence.postSize) / 2 + const z0 = baseY + floor + (fence.supportOffset ?? 0) + const prisms: Prism[] = [] + // a guard with nothing cut into it is read part by part; any other fence is a strip + if (fence.style === 'guard' && !fence.children?.length) { + prisms.push(...guardPrisms(fence, cornerNeighbors(fence, nodes), z0)) + } else { + for (const [index, [a, b]] of spans.entries()) { + const run = span(points, lengths, a, b) + for (let i = 1; i < run.length; i++) { + const [px, pz] = run[i - 1]! + const [qx, qz] = run[i]! + const length = Math.hypot(qx - px, qz - pz) + if (length < 1e-6) continue + const nx = ((pz - qz) / length) * half + const nz = ((qx - px) / length) * half + prisms.push({ + id: `${fence.id}#fence.${index}.${i}`, + nodeId: fence.id, + kind: 'other', + z0, + z1: z0 + fence.height, + outer: [ + [px + nx, pz + nz], + [qx + nx, qz + nz], + [qx - nx, qz - nz], + [px - nx, pz - nz], + ], + holes: [], + shape: 'approx', + why: 'a fence as a strip along its centreline', + }) + } + } + } + out.push({ fenceId: fence.id, levelId, prisms }) + } catch (error) { + skipped.push({ + nodeId: fence.id, + why: error instanceof Error ? error.message : String(error), + }) + } + } + return { fences: out, skipped } +} diff --git a/packages/core/src/spatial/usage-field/field.ts b/packages/core/src/spatial/usage-field/field.ts new file mode 100644 index 0000000000..de4942cbac --- /dev/null +++ b/packages/core/src/spatial/usage-field/field.ts @@ -0,0 +1,168 @@ +import { type Aabb, type Obstacle, obstacleDistance } from './obstacles' + +export type Grid = { + x0: number + z0: number + h: number + W: number + H: number +} + +export const cellX = (g: Grid, i: number) => g.x0 + (i + 0.5) * g.h +export const cellZ = (g: Grid, j: number) => g.z0 + (j + 0.5) * g.h +export const cellOf = (g: Grid, x: number, z: number) => { + const i = Math.floor((x - g.x0) / g.h) + const j = Math.floor((z - g.z0) / g.h) + return i < 0 || j < 0 || i >= g.W || j >= g.H ? -1 : j * g.W + i +} + +export function makeGrid(domain: Aabb, h: number): Grid { + return { + x0: domain[0], + z0: domain[1], + h, + W: Math.max(1, Math.round((domain[2] - domain[0]) / h)), + H: Math.max(1, Math.round((domain[3] - domain[1]) / h)), + } +} + +/** + * A uniform bucket index over obstacle boxes. A query widens ring by ring around the point and + * stops when no farther bucket can hold a nearer obstacle, so the answer is exact. + */ +export class BucketIndex { + private readonly buckets: Obstacle[][] + private readonly stamp: Uint32Array + private pass = 0 + private readonly nx: number + private readonly nz: number + + constructor( + obstacles: Obstacle[], + private readonly domain: Aabb, + private readonly cell = 0.5, + ) { + this.nx = Math.max(1, Math.ceil((domain[2] - domain[0]) / cell)) + this.nz = Math.max(1, Math.ceil((domain[3] - domain[1]) / cell)) + this.buckets = Array.from({ length: this.nx * this.nz }, () => []) + this.stamp = new Uint32Array(obstacles.length) + for (const obstacle of obstacles) { + const [i0, j0, i1, j1] = this.range(obstacle.aabb) + for (let j = j0; j <= j1; j++) + for (let i = i0; i <= i1; i++) this.buckets[j * this.nx + i]!.push(obstacle) + } + } + + private range(a: Aabb): Aabb { + const clamp = (v: number, n: number) => Math.max(0, Math.min(n - 1, v)) + const c = this.cell + return [ + clamp(Math.floor((a[0] - this.domain[0]) / c), this.nx), + clamp(Math.floor((a[1] - this.domain[1]) / c), this.nz), + clamp(Math.floor((a[2] - this.domain[0]) / c), this.nx), + clamp(Math.floor((a[3] - this.domain[1]) / c), this.nz), + ] + } + + /** Signed distance to the nearest obstacle (negative inside) and which it is; `skipNode` leaves one node out. */ + query(px: number, pz: number, skipNode?: string): { d: number; arg: number } { + let best = Number.POSITIVE_INFINITY + let arg = -1 + const c = this.cell + const bi = Math.max(0, Math.min(this.nx - 1, Math.floor((px - this.domain[0]) / c))) + const bj = Math.max(0, Math.min(this.nz - 1, Math.floor((pz - this.domain[1]) / c))) + const stamp = ++this.pass + const reach = Math.max(this.nx, this.nz) + for (let r = 0; r <= reach; r++) { + for (let j = bj - r; j <= bj + r; j++) { + if (j < 0 || j >= this.nz) continue + const edge = j === bj - r || j === bj + r + for (let i = bi - r; i <= bi + r; i += edge ? 1 : 2 * r || 1) { + if (i < 0 || i >= this.nx) continue + for (const obstacle of this.buckets[j * this.nx + i]!) { + if (this.stamp[obstacle.index] === stamp) continue + this.stamp[obstacle.index] = stamp + if (skipNode && obstacle.prism.nodeId === skipNode) continue + const v = obstacleDistance(obstacle, px, pz) + if (v < best) { + best = v + arg = obstacle.index + } + } + } + } + // everything not seen yet lies wholly outside the block of buckets searched + const bound = Math.min( + px - (this.domain[0] + (bi - r) * c), + this.domain[0] + (bi + r + 1) * c - px, + pz - (this.domain[1] + (bj - r) * c), + this.domain[1] + (bj + r + 1) * c - pz, + ) + if (best <= bound) break + } + return { d: best, arg } + } +} + +const TILE = 16 + +function aabbDistance(x0: number, z0: number, x1: number, z1: number, a: Aabb): number { + return Math.hypot(Math.max(a[0] - x1, x0 - a[2], 0), Math.max(a[1] - z1, z0 - a[3], 0)) +} + +export type Baked = { + /** Signed distance to the nearest obstacle at every cell centre (negative inside one). */ + F: Float32Array + /** The nearest obstacle's index, -1 where there is none. */ + A: Int32Array +} + +/** + * Bakes the clearance field in tiles: a tile tests only the obstacles that can still win in it + * (those within the tile's reach of the nearest one), which is exact, not an approximation. + */ +export function bakeGrid(g: Grid, obstacles: Obstacle[]): Baked { + const F = new Float32Array(g.W * g.H).fill(Number.POSITIVE_INFINITY) + const A = new Int32Array(g.W * g.H).fill(-1) + if (obstacles.length === 0) return { F, A } + const TW = Math.ceil(g.W / TILE) + const TH = Math.ceil(g.H / TILE) + for (let tj = 0; tj < TH; tj++) + for (let ti = 0; ti < TW; ti++) { + const i0 = ti * TILE + const j0 = tj * TILE + const i1 = Math.min(g.W, i0 + TILE) - 1 + const j1 = Math.min(g.H, j0 + TILE) - 1 + const x0 = cellX(g, i0) + const z0 = cellZ(g, j0) + const x1 = cellX(g, i1) + const z1 = cellZ(g, j1) + const mx = (x0 + x1) / 2 + const mz = (z0 + z1) / 2 + const radius = Math.hypot(x1 - x0, z1 - z0) / 2 + let bound = Number.POSITIVE_INFINITY + for (const o of obstacles) bound = Math.min(bound, obstacleDistance(o, mx, mz)) + bound += radius + const candidates = obstacles.filter( + (o) => aabbDistance(x0, z0, x1, z1, o.aabb) <= Math.max(bound, 0), + ) + for (let j = j0; j <= j1; j++) { + const pz = cellZ(g, j) + for (let i = i0; i <= i1; i++) { + const px = cellX(g, i) + let best = Number.POSITIVE_INFINITY + let arg = -1 + for (const o of candidates) { + const v = obstacleDistance(o, px, pz) + if (v < best) { + best = v + arg = o.index + } + } + F[j * g.W + i] = best + A[j * g.W + i] = arg + } + } + } + return { F, A } +} diff --git a/packages/core/src/spatial/usage-field/findings-more.test.ts b/packages/core/src/spatial/usage-field/findings-more.test.ts new file mode 100644 index 0000000000..93dcb4f23b --- /dev/null +++ b/packages/core/src/spatial/usage-field/findings-more.test.ts @@ -0,0 +1,575 @@ +import { describe, expect, test } from 'bun:test' +import { setCodeProfile } from '../../agent-operations/set-code-profile' +import { + type AnyNode, + BuildingNode, + DoorNode, + ItemNode, + LevelNode, + SiteNode, + SlabNode, + StairNode, + WallNode, + WindowNode, + ZoneNode, +} from '../../schema' +import { measureBeds } from './beds' +import { usageIssues } from './findings' +import { usageShapes } from './shapes' +import { OPENS_FULLY_DEG } from './swings' +import type { Nodes } from './walls' + +const SHA = 'c'.repeat(64) + +const scene = (levels: number, extra: AnyNode[], heights: number[] = []): Nodes => { + const ids = Array.from({ length: levels }, (_, i) => `level_${i + 1}`) + return Object.fromEntries( + [ + BuildingNode.parse({ id: 'building_1', children: ids }), + ...ids.map((id, i) => + LevelNode.parse({ + id, + parentId: 'building_1', + level: i, + children: [], + ...(heights[i] ? { height: heights[i] } : {}), + }), + ), + ...extra, + ].map((node) => [node.id, node]), + ) as Nodes +} +const wall = ( + id: string, + start: [number, number], + end: [number, number], + children: string[] = [], + thickness = 0.1, +) => WallNode.parse({ id, parentId: 'level_1', start, end, thickness, children }) +const zone = ( + id: string, + name: string, + polygon: [number, number][], + level = 'level_1', + extra: Record = {}, +) => ZoneNode.parse({ id, parentId: level, name, polygon, spaceRole: 'room', ...extra }) +const slab = ( + id: string, + level: string, + polygon: [number, number][], + extra: Record = {}, +) => SlabNode.parse({ id, parentId: level, polygon, elevation: 0.05, ...extra }) +const room = (w: number, d: number, level = 'level_1'): [number, number][] => [ + [0, 0], + [w, 0], + [w, d], + [0, d], +] + +/** A script-made piece with a stored solid outline (tolerance 9 mm: exact), centred on (x, z). */ +const piece = ( + id: string, + name: string, + category: string, + x: number, + z: number, + width: number, + depth: number, + height: number, + extra: Record = {}, +) => + ItemNode.parse({ + id, + parentId: 'level_1', + position: [x, 0, z], + name, + asset: { + id, + name, + category, + thumbnail: '/t.webp', + src: `artifact://${SHA}`, + dimensions: [width, height, depth], + }, + source: { + kind: 'script', + script: SHA, + artifact: SHA, + manifest: { + bounds: { min: [-width / 2, 0, -depth / 2], max: [width / 2, height, depth / 2] }, + triangles: 12, + shape: { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: height, + polygons: [ + { + outer: [ + [-width / 2, -depth / 2], + [width / 2, -depth / 2], + [width / 2, depth / 2], + [-width / 2, depth / 2], + ], + }, + ], + }, + ], + }, + }, + }, + ...extra, + }) + +const run = (nodes: Nodes, type: string) => + usageIssues(nodes, { cell: 0.05 }).filter((issue) => issue.type === type) + +/** A 4 x 4 room whose west wall is on x = 0 (0.1 m thick: its room face is at x = 0.05). */ +const closed = (extra: AnyNode[], heights: number[] = []) => + scene( + heights.length || 1, + [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [4.3, -0.3], + [4.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [4, 0]), + wall('wall_e', [4, 0], [4, 4]), + wall('wall_n', [4, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + zone('zone_1', 'Study', room(4, 4)), + ...extra, + ], + heights, + ) + +describe('usage_clash', () => { + test('deep overlaps on approximate bounds warn, while shallow contacts stay information', () => { + const cupboard = piece('item_w', 'Wardrobe', 'wardrobe', 0.25, 2, 0.6, 1.5, 2) + delete cupboard.source + expect(run(closed([cupboard]), 'usage_clash')).toContainEqual( + expect.objectContaining({ severity: 'warning', approximate: true }), + ) + cupboard.position[0] = 0.3 + expect(run(closed([cupboard]), 'usage_clash')).toContainEqual( + expect.objectContaining({ severity: 'info', approximate: true }), + ) + }) + + test('two pieces: an overlap is a clash, a piece resting on another, a rug under a table, and foliage are not', () => { + const sofa = piece('item_a', 'Sofa', 'sofa', 2, 2, 2, 0.9, 0.8) + const chair = piece('item_b', 'Armchair', 'armchair', 2.9, 2, 0.9, 0.9, 0.8) + const overlap = run(closed([sofa, chair]), 'usage_clash') + expect(overlap).toHaveLength(1) + expect(overlap[0]!.message).toContain('overlaps') + expect(overlap[0]).toMatchObject({ severity: 'warning' }) + const lamp = piece('item_l', 'Table lamp', 'decor', 2, 2, 0.3, 0.3, 0.4, { + position: [2, 0.8, 2], + }) + expect(run(closed([sofa, lamp]), 'usage_clash')).toHaveLength(0) + const rug = piece('item_r', 'Wool rug', 'rug', 2, 2, 2.5, 1.5, 0.01) + expect(run(closed([sofa, rug]), 'usage_clash')).toHaveLength(0) + const palm = piece('item_p', 'Potted palm', 'plant', 2.1, 2, 0.8, 0.8, 1.6) + expect(run(closed([sofa, palm]), 'usage_clash')).toHaveLength(0) + }) +}) + +describe('usage_opening_blocked', () => { + const windowed = (extra: AnyNode[]) => + scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [4.3, -0.3], + [4.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [4, 0], ['window_1']), + wall('wall_e', [4, 0], [4, 4]), + wall('wall_n', [4, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + WindowNode.parse({ + id: 'window_1', + parentId: 'wall_s', + wallId: 'wall_s', + position: [2, 1.5, 0], + width: 1.6, + height: 1.2, + name: 'South window', + }), + zone('zone_1', 'Bedroom', room(4, 4)), + ...extra, + ]) + // the south wall's room face is at z = 0.05; the window's sill is 0.9 m up + test('a wardrobe against the glass blocks it, a low sideboard under the sill and a piece beside it do not', () => { + const wardrobe = piece('item_a', 'Wardrobe', 'wardrobe', 2, 0.05 + 0.3, 1.2, 0.6, 2) + const found = run(windowed([wardrobe]), 'usage_opening_blocked') + expect(found).toHaveLength(1) + expect(found[0]).toMatchObject({ severity: 'warning' }) + expect(found[0]!.message).toContain('from the glass') + const sideboard = piece('item_b', 'Sideboard', 'sideboard', 2, 0.05 + 0.25, 1.2, 0.5, 0.8) + expect(run(windowed([sideboard]), 'usage_opening_blocked')).toHaveLength(0) + const beside = piece('item_c', 'Wardrobe', 'wardrobe', 3.5, 0.05 + 0.3, 0.6, 0.6, 2) + expect(run(windowed([beside]), 'usage_opening_blocked')).toHaveLength(0) + const far = piece('item_d', 'Wardrobe', 'wardrobe', 2, 1.5, 1.2, 0.6, 2) + expect(run(windowed([far]), 'usage_opening_blocked')).toHaveLength(0) + }) +}) + +describe('beds', () => { + const bed = ( + id: string, + x: number, + z: number, + width: number, + extra: Record = {}, + ) => piece(id, 'Bed', 'bed', x, z, width, 2.1, 0.5, extra) + // a bed with its head on the north wall (z = 3.95), centred at x + test('a king in a 3 m room is tight; a queen in a room that holds it is not', () => { + const small = scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [3.3, -0.3], + [3.3, 4.8], + [-0.3, 4.8], + ]), + wall('wall_s', [0, 0], [3, 0]), + wall('wall_e', [3, 0], [3, 4.5]), + wall('wall_n', [3, 4.5], [0, 4.5]), + wall('wall_w', [0, 4.5], [0, 0]), + zone('zone_1', 'Bedroom', [ + [0, 0], + [3, 0], + [3, 4.5], + [0, 4.5], + ]), + bed('item_k', 1.5, 4.45 - 1.05, 1.95), + ]) + const [king] = measureBeds(small, usageShapes(small)) + expect(king).toMatchObject({ sizeClass: 'king', room: { name: 'Bedroom' } }) + expect(king!.left).toBeLessThan(0.6) + expect(king!.right).toBeLessThan(0.6) + const tight = run(small, 'usage_bed_clearance') + expect( + tight.some((issue) => issue.severity === 'warning' && issue.message.includes('no side')), + ).toBe(true) + expect( + tight.some((issue) => issue.severity === 'info' && issue.message.includes('retailers')), + ).toBe(true) + const roomy = scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [5.3, -0.3], + [5.3, 5.3], + [-0.3, 5.3], + ]), + wall('wall_s', [0, 0], [5, 0]), + wall('wall_e', [5, 0], [5, 5]), + wall('wall_n', [5, 5], [0, 5]), + wall('wall_w', [0, 5], [0, 0]), + zone('zone_1', 'Bedroom', room(5, 5)), + bed('item_q', 2.5, 4.95 - 1.05, 1.65), + ]) + expect(run(roomy, 'usage_bed_clearance')).toHaveLength(0) + }) +}) + +describe('usage_door_swing', () => { + /** A 4 x 4 room whose south wall carries a door 0.9 m wide at `along` (hinged left, swinging into the room). */ + const doored = (along: number, extra: AnyNode[], door: Record = {}) => + scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [4.3, -0.3], + [4.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [4, 0], ['door_1']), + wall('wall_e', [4, 0], [4, 4]), + wall('wall_n', [4, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + DoorNode.parse({ + id: 'door_1', + parentId: 'wall_s', + wallId: 'wall_s', + position: [along, 1.05, 0], + width: 0.9, + height: 2.1, + name: 'Study door', + hingesSide: 'left', + swingDirection: 'inward', + ...door, + }), + zone('zone_1', 'Study', room(4, 4)), + ...extra, + ]) + const swings = (nodes: Nodes) => run(nodes, 'usage_door_swing') + + test('a door in the open swings fully and says nothing; a piece in the sweep stops it at an angle, and the message says how it would open', () => { + expect(swings(doored(2, []))).toHaveLength(0) + // the leaf from the left jamb (x 1.55) sweeps toward +x then into the room: a wardrobe at x 2.1 to 2.4 meets it + const wardrobe = piece('item_w', 'Wardrobe', 'wardrobe', 2.25, 0.5, 0.3, 0.3, 2) + const found = swings(doored(2, [wardrobe])) + expect(found).toHaveLength(1) + expect(found[0]).toMatchObject({ severity: 'warning', thresholdDeg: 90 }) + expect(found[0]!.valueDeg).toBeLessThan(85) + expect(found[0]!.message).toContain('“Wardrobe”') + // hung the other way (out of the room) it is clear + expect(found[0]!.message).toContain('opens fully if it swings the other way') + }) + + test('a door hung in the body of the wall that meets its jamb cannot open, and a flat leaf against a wall at 90 degrees is not a stop', () => { + // the opening starts 5 cm inside the west wall's body + const corner = swings(doored(0.4, [])) + expect(corner).toHaveLength(1) + expect(corner[0]!.valueDeg).toBe(0) + expect(corner[0]!.message).toContain('cannot open') + // hinged at the far jamb (x 0.85 + ...) the leaf folds back along the wall's face at 90 degrees: fine + expect(swings(doored(1.2, []))).toHaveLength(0) + }) + + test('a door at the foot of an up-flight meets the first treads, and swinging the other way is clear', () => { + // the Windsor shape: a flight climbing +z from z = 1, and a door in the wall across its foot + const foot = (swingDirection: 'inward' | 'outward') => + scene( + 1, + [ + StairNode.parse({ + id: 'stair_1', + parentId: 'level_1', + name: 'Return stair', + position: [2, 0, 1], + totalRise: 2.8, + stepCount: 14, + width: 1, + }), + WallNode.parse({ + id: 'wall_f', + parentId: 'level_1', + start: [0, 1], + end: [4, 1], + thickness: 0.1, + children: ['door_f'], + }), + DoorNode.parse({ + id: 'door_f', + parentId: 'wall_f', + wallId: 'wall_f', + position: [2, 1.05, 0], + width: 0.82, + height: 2.1, + name: 'Door 1', + hingesSide: 'left', + swingDirection, + }), + ], + [2.8], + ) + const found = swings(foot('inward')) + expect(found).toHaveLength(1) + expect(found[0]).toMatchObject({ severity: 'warning', approximate: false }) + expect(found[0]!.valueDeg).toBeLessThan(OPENS_FULLY_DEG) + expect(found[0]!.message).toContain('“Return stair” (a stair)') + expect(found[0]!.message).toContain('opens fully if it swings the other way') + expect(found[0]!.obstacles[0]).toMatchObject({ nodeId: 'stair_1', kind: 'stair' }) + expect(swings(foot('outward'))).toHaveLength(0) + }) + + describe('stopped leaves warn, whatever outline the blocker has', () => { + const cupboard = (at: [number, number], size: number) => + ItemNode.parse({ + id: 'item_b', + parentId: 'level_1', + position: [at[0], 0, at[1]], + name: 'Cupboard', + asset: { + id: 'c', + name: 'Cupboard', + category: 'cabinet', + thumbnail: '/t.webp', + src: '/items/a/model.glb', + dimensions: [size, 2, size], + }, + }) + + test('a leaf stopped early by a piece on an approximate outline is a warning, and the message says about', () => { + const [found] = swings(doored(2, [cupboard([2.25, 0.5], 0.3)])) + expect(found).toMatchObject({ severity: 'warning', approximate: true }) + expect(found?.valueDeg).toBeLessThan(60) + expect(found!.message).toContain(`opens to about ${found!.valueDeg}° and no further`) + }) + + test('an approximate stop between 60 and 80 degrees still warns that the door cannot open fully', () => { + const [found] = swings(doored(2, [cupboard([1.75, 0.8], 0.12)])) + expect(found).toMatchObject({ severity: 'warning', approximate: true }) + expect(found?.valueDeg).toBeGreaterThanOrEqual(60) + expect(found?.valueDeg).toBeLessThan(OPENS_FULLY_DEG) + }) + + test('a box round the door itself (a portal, trim the door stands in) is not what stops it', () => { + const portal = ItemNode.parse({ + id: 'item_p', + parentId: 'level_1', + position: [2, 0, 0], + name: 'Entry portal trim', + asset: { + id: 'p', + name: 'Entry portal trim', + category: 'trim', + thumbnail: '/t.webp', + src: '/items/a/model.glb', + dimensions: [2.4, 2.4, 0.3], + }, + }) + expect(swings(doored(2, [portal]))).toHaveLength(0) + // beside the door, the same box meets the leaf + const beside = ItemNode.parse({ ...portal, position: [2.25, 0, 0.7], dimensions: undefined }) + expect(swings(doored(2, [beside]))).toHaveLength(1) + }) + + test('a leaf that cannot open at all is still said to be against what it meets, with no about', () => { + const [found] = swings(doored(0.4, [])) + expect(found).toMatchObject({ severity: 'warning', valueDeg: 0 }) + expect(found!.message).toContain('cannot open') + expect(found!.message).not.toContain('about') + }) + }) +}) + +describe('usage_fixture_clearance', () => { + /** A 4 x 4 room with a toilet facing the north wall at `gap` from it (its front 0.4 m clear of it when gap = 0.4). */ + const toiletRoom = (gap: number, extra: AnyNode[] = []) => + closed([piece('item_t', 'Toilet', 'toilet', 2, 3.95 - gap - 0.35, 0.4, 0.7, 0.8), ...extra]) + const site = (profile?: string) => + SiteNode.parse({ id: 'site_1', ...(profile ? { metadata: { codeProfile: profile } } : {}) }) + const clear = (nodes: Nodes) => run(nodes, 'usage_fixture_clearance') + + test('an approximate fixture lacking clearance warns only with a named jurisdiction', () => { + for (const profile of [undefined, 'irc-2021']) { + const nodes = toiletRoom(0.4, [site(profile)]) + const toilet = nodes.item_t + if (toilet?.type !== 'item') throw new Error('Missing toilet') + delete toilet.source + expect(clear(nodes)).toContainEqual( + expect.objectContaining({ + severity: profile ? 'warning' : 'info', + approximate: true, + code: expect.objectContaining({ byDefault: !profile }), + }), + ) + } + }) + + test('set_code_profile on a US project turns the finding into a warning, and clearing it turns it back', () => { + const apply = (nodes: Nodes, profile: 'irc-2021' | null) => { + const out = setCodeProfile(nodes, { profile }, { activeLevelId: null }) + const update = out.changes?.update?.[0] + return update + ? ({ ...nodes, [update.id]: { ...nodes[update.id]!, ...update.data } } as Nodes) + : nodes + } + const bare = toiletRoom(0.4, [site()]) + expect(clear(bare)[0]).toMatchObject({ severity: 'info', code: { byDefault: true } }) + const us = apply(bare, 'irc-2021') + expect(clear(us)[0]).toMatchObject({ + severity: 'warning', + code: { profile: 'irc-2021', byDefault: false }, + }) + expect(clear(apply(us, null))[0]).toMatchObject({ severity: 'info' }) + }) +}) + +describe('usage_door_over_stair', () => { + /** + * A 14-riser stair climbing +z from level 1 to level 2 (its top step at z 4), and a room on level 2 north of it, + * whose south wall at z = 4 carries a door at the stair's head. The door is hinged left and swings `swingDirection`: + * inward is into the room, outward is over the top treads. + */ + const headOfStair = (swingDirection: 'inward' | 'outward', extra: AnyNode[] = []) => + scene( + 2, + [ + StairNode.parse({ + id: 'stair_1', + parentId: 'level_1', + name: 'Cellar stair', + position: [2, 0, 1], + totalRise: 2.8, + stepCount: 14, + width: 1, + fromLevelId: 'level_1', + toLevelId: 'level_2', + }), + slab('slab_2', 'level_2', [ + [0, 4], + [4, 4], + [4, 8], + [0, 8], + ]), + WallNode.parse({ + id: 'wall_2', + parentId: 'level_2', + start: [0, 4], + end: [4, 4], + thickness: 0.1, + children: ['door_1'], + }), + DoorNode.parse({ + id: 'door_1', + parentId: 'wall_2', + wallId: 'wall_2', + position: [2, 1.05, 0], + width: 0.9, + height: 2.1, + name: 'Cellar door', + hingesSide: 'left', + swingDirection, + }), + zone( + 'zone_2', + 'Hall', + [ + [0, 4], + [4, 4], + [4, 8], + [0, 8], + ], + 'level_2', + ), + ...extra, + ], + [2.8, 2.8], + ) + const site = (profile: string) => + SiteNode.parse({ id: 'site_1', metadata: { codeProfile: profile } }) + const over = (nodes: Nodes) => run(nodes, 'usage_door_over_stair') + + test('a leaf that swings over the top treads is information that names the US IRC with no code named, a warning with irc-2021, and nothing with another code', () => { + const none = over(headOfStair('outward')) + expect(none).toHaveLength(1) + expect(none[0]).toMatchObject({ + severity: 'info', + code: { profile: 'irc-2021', source: 'code text', byDefault: true }, + approximate: false, + }) + expect(none[0]!.valueM).toBeCloseTo(0.2, 2) + expect(none[0]!.message).toContain( + 'the US IRC 2021 (IRC R311.7.6 / R311.3) wants a floor or landing for the leaf to open onto, and this project names no code', + ) + expect(none[0]!.message).toContain( + '“Cellar door” in “Hall” swings over the steps of “Cellar stair”', + ) + expect(over(headOfStair('outward', [site('irc-2021')]))[0]).toMatchObject({ + severity: 'warning', + code: { byDefault: false }, + }) + expect(over(headOfStair('outward', [site('au-ncc')]))).toHaveLength(0) + expect(over(headOfStair('outward', [site('fr')]))).toHaveLength(0) + }) + + test('the same door swinging into the room, away from the stair, says nothing', () => { + expect(over(headOfStair('inward'))).toHaveLength(0) + }) +}) diff --git a/packages/core/src/spatial/usage-field/findings.test.ts b/packages/core/src/spatial/usage-field/findings.test.ts new file mode 100644 index 0000000000..416472b281 --- /dev/null +++ b/packages/core/src/spatial/usage-field/findings.test.ts @@ -0,0 +1,481 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { verifyScene } from '../../agent-operations' +import { distanceToBoundary } from '../../lib/polygon-boolean' +import { + type AnyNode, + BuildingNode, + DoorNode, + ItemNode, + LevelNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../schema' +import { type UsageIssue, usageIssues } from './findings' +import { sdfChecksOn, setSdfChecks } from './flag' +import { obstacleGap, obstacleOf } from './obstacles' +import { usageShapes } from './shapes' +import type { Nodes } from './walls' + +const SHA = 'a'.repeat(64) + +const wall = ( + id: string, + start: [number, number], + end: [number, number], + children: string[] = [], +) => WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.1, children }) + +const zone = (id: string, name: string, polygon: [number, number][]) => + ZoneNode.parse({ id, parentId: 'level_1', name, polygon }) + +const slab = SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + elevation: 0.05, +}) + +function house(extra: AnyNode[]): Nodes { + const nodes: AnyNode[] = [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), + slab, + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + ...extra, + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as Nodes +} + +const frontDoor = DoorNode.parse({ + id: 'door_front', + parentId: 'wall_s', + wallId: 'wall_s', + position: [1.5, 1.05, 0], + width: 1, + height: 2.1, + name: 'Front door', + // These figures were drawn with a frame inside the wall's thickness; one as deep as the wall puts + // the door, not the wall, at the corridor's edge. + frameDepth: 0.07, +}) +const southWall = wall('wall_s', [0, 0], [6, 0], ['door_front']) + +// Two rooms side by side, a door in the partition; `split` makes the east side two rooms with no wall between them +function twoRooms(partition = 0.9, items: AnyNode[] = [], split = false) { + const inner = DoorNode.parse({ + id: 'door_inner', + parentId: 'wall_p', + wallId: 'wall_p', + position: [2, 1.05, 0], + width: partition, + height: 2.1, + name: 'Inner door', + }) + return house([ + southWall, + frontDoor, + wall('wall_p', [3, 0], [3, 4], ['door_inner']), + inner, + zone('zone_west', 'West room', [ + [0.05, 0.05], + [2.95, 0.05], + [2.95, 3.95], + [0.05, 3.95], + ]), + ...(split + ? [ + zone('zone_east', 'East room', [ + [3.05, 0.05], + [5.95, 0.05], + [5.95, 2.0], + [3.05, 2.0], + ]), + zone('zone_annex', 'East annex', [ + [3.05, 2.0], + [5.95, 2.0], + [5.95, 3.95], + [3.05, 3.95], + ]), + ] + : [ + zone('zone_east', 'East room', [ + [3.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [3.05, 3.95], + ]), + ]), + ...items, + ]) +} + +// A script-made bookcase with a stored shape, so what it narrows is exact +const bookcase = (id: string, x: number, z: number, w: number, d: number, h = 1.8) => + ItemNode.parse({ + id, + parentId: 'level_1', + position: [x, 0, z], + name: 'Bookcase', + asset: { + id: 'bookcase', + name: 'Bookcase', + category: 'storage', + thumbnail: '/t.webp', + src: `artifact://${SHA}`, + dimensions: [w, h, d], + }, + source: { + kind: 'script', + script: SHA, + artifact: SHA, + manifest: { + bounds: { min: [-w / 2, 0, -d / 2], max: [w / 2, h, d / 2] }, + triangles: 12, + shape: { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: h, + polygons: [ + { + outer: [ + [-w / 2, -d / 2], + [w / 2, -d / 2], + [w / 2, d / 2], + [-w / 2, d / 2], + ], + }, + ], + }, + ], + }, + }, + }, + }) + +const issues = (nodes: Nodes) => usageIssues(nodes, { cell: 0.02, entranceDoorId: 'door_front' }) + +// A corridor 1.2 m deep with a 0.5 m deep bookcase against its north wall (face at 1.25): 0.70 m left to the south wall +function corridorWithBookcase(): Nodes { + const back = DoorNode.parse({ + id: 'door_back', + parentId: 'wall_c', + wallId: 'wall_c', + position: [5, 1.05, 0], + width: 1, + height: 2.1, + frameDepth: 0.07, + }) + return house([ + southWall, + frontDoor, + wall('wall_c', [0, 1.3], [6, 1.3], ['door_back']), + back, + zone('zone_corridor', 'Corridor', [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 1.25], + [0.05, 1.25], + ]), + zone('zone_room', 'Study', [ + [0.05, 1.35], + [5.95, 1.35], + [5.95, 3.95], + [0.05, 3.95], + ]), + bookcase('item_1', 3, 1.0, 1.2, 0.5), + ]) +} + +describe('passages', () => { + test('a door with 0.80 m between its jambs is a doorway, and enough', () => { + expect(issues(twoRooms(0.9)).filter((i) => i.type === 'usage_passage_narrow')).toHaveLength(0) + }) + + test('a 0.70 m door narrows the way to the room behind it', () => { + const found = issues(twoRooms(0.7)).filter((i) => i.type === 'usage_passage_narrow') + expect(found).toHaveLength(1) + const [issue] = found + expect(issue!.severity).toBe('warning') + expect(issue!.valueM).toBeCloseTo(0.6, 2) + expect(issue!.thresholdM).toBe(0.8) + expect(issue!.place.room).toBe('East room') + expect(issue!.fromDoorId).toBe('door_front') + expect(issue!.message).toContain('Narrow passage to “East room”: 0.60 m') + // the door as drawn and the clear width between its jambs are both said; the limit applies to the clear width + expect(issue!.message).toContain( + '0.60 m clear between the jambs of “Inner door”, a 0.70 m door', + ) + expect(issue!.doorWidthM).toBe(0.7) + expect(issue!.message).toContain('measured from “Front door”') + expect(issue!.message).toContain('(below 0.80 m, a doorway)') + expect(issue!.message).not.toMatch(/non conforme/i) + }) + + test('a bookcase that leaves 0.70 m in a corridor narrows a passage that is not a doorway', () => { + const found = issues(corridorWithBookcase()).filter( + (i) => i.type === 'usage_passage_narrow' && i.place.room === 'Study', + ) + expect(found).toHaveLength(1) + expect(found[0]!.thresholdM).toBe(0.9) + expect(found[0]!.valueM).toBeCloseTo(0.7, 2) + expect(found[0]!.severity).toBe('warning') + expect(found[0]!.obstacles.map((o) => o.name)).toContain('Bookcase') + expect(found[0]!.message).toMatch(/between “[^”]+” and “[^”]+”/) + }) + + test('an approximate bookcase narrowing the corridor is a warning, not just a measurement', () => { + const nodes = corridorWithBookcase() + const bookcase = nodes.item_1 + if (bookcase?.type !== 'item') throw new Error('Missing corridor bookcase') + delete bookcase.source + const found = issues(nodes).filter((issue) => issue.type === 'usage_passage_narrow') + expect(found.length).toBeGreaterThan(0) + expect(found).toContainEqual( + expect.objectContaining({ severity: 'warning', approximate: true }), + ) + }) +}) + +const passages = (nodes: Nodes) => issues(nodes).filter((i) => i.type === 'usage_passage_narrow') + +describe('a narrow place is one finding for the rooms it leads to', () => { + const both = () => twoRooms(0.7, [], true) + + test('two rooms behind one 0.70 m door are one finding, with the figure it has for one room', () => { + const found = passages(both()) + expect(found).toHaveLength(1) + expect(found[0]!.serves!.map((room) => room.room).sort()).toEqual(['East annex', 'East room']) + expect(found[0]!.valueM).toBe(passages(twoRooms(0.7))[0]!.valueM) + expect(found[0]!.nodeIds).toEqual( + expect.arrayContaining(['zone_east', 'zone_annex', 'door_inner']), + ) + expect(found[0]!.message).toMatch( + /^Narrow passage to “East (room|annex)” and “East (room|annex)”: /, + ) + expect(found[0]!.message).toContain( + '0.60 m clear between the jambs of “Inner door”, a 0.70 m door', + ) + }) + + test('the best other exterior door is said once when it is the same for every room the place leads to', () => { + const east = DoorNode.parse({ + id: 'door_east', + parentId: 'wall_e', + wallId: 'wall_e', + position: [2, 1.05, 0], + width: 1, + height: 2.1, + name: 'East door', + }) + const [found] = passages( + twoRooms(0.7, [wall('wall_e', [6, 0], [6, 4], ['door_east']), east], true), + ) + expect(found!.serves!.map((room) => room.alternative?.doorId)).toEqual([ + 'door_east', + 'door_east', + ]) + expect(found!.message).toContain( + 'a 0.70 m door; 0.90 m from “East door”, measured from “Front door”', + ) + }) + + test('two different narrow places stay two findings, each for its own room', () => { + // a 0.70 m door into the middle room and a 0.65 m door on into the east one: the east room's narrowest point is the second door + const door = (id: string, wallId: string, width: number) => + DoorNode.parse({ + id, + parentId: wallId, + wallId, + position: [2, 1.05, 0], + width, + height: 2.1, + frameDepth: 0.07, + name: id, + }) + const nodes = house([ + southWall, + frontDoor, + wall('wall_p1', [2, 0], [2, 4], ['door_p1']), + door('door_p1', 'wall_p1', 0.7), + wall('wall_p2', [4, 0], [4, 4], ['door_p2']), + door('door_p2', 'wall_p2', 0.65), + zone('zone_west', 'West', [ + [0.05, 0.05], + [1.95, 0.05], + [1.95, 3.95], + [0.05, 3.95], + ]), + zone('zone_middle', 'Middle', [ + [2.05, 0.05], + [3.95, 0.05], + [3.95, 3.95], + [2.05, 3.95], + ]), + zone('zone_far', 'Far', [ + [4.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [4.05, 3.95], + ]), + ]) + const found = passages(nodes) + expect(found.map((i) => [i.serves!.map((room) => room.room), i.valueM]).sort()).toEqual([ + [['Far'], 0.55], + [['Middle'], 0.6], + ]) + }) + + test('a slot on no way to a room has no passage finding', () => { + // two stubs from the north wall leave a 0.30 m slot, 1.5 m deep, open to the hall at one end + const nodes = house([ + southWall, + frontDoor, + wall('wall_a', [2, 4], [2, 2.5]), + wall('wall_b', [2.4, 4], [2.4, 2.5]), + zone('zone_hall', 'Hall', [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ]), + ]) + expect(passages(nodes)).toHaveLength(0) + expect(issues(nodes).filter((i) => i.type === 'usage_pocket')).toHaveLength(0) + }) +}) + +describe('a passage names what bounds its figure', () => { + /** The prisms of one node in the band a body stands in (floor at 0.05 m). */ + const bodyPrisms = (nodes: Nodes, nodeId: string) => + usageShapes(nodes) + .levels.flatMap((level) => level.prisms) + .filter((prism) => prism.nodeId === nodeId && prism.z0 < 2.05 && prism.z1 > 0.08) + + /** How far a finding's spot is from the nearest outline of a thing it names. */ + const reach = (nodes: Nodes, issue: UsageIssue, nodeId: string) => + Math.min( + ...bodyPrisms(nodes, nodeId).map((prism) => + Math.abs(distanceToBoundary([{ outer: prism.outer, holes: prism.holes }], issue.place.at)), + ), + ) + + /** The exact distance between two named things' outlines. */ + const gap = (nodes: Nodes, a: string, b: string) => + Math.min( + ...bodyPrisms(nodes, a).flatMap((p, i) => + bodyPrisms(nodes, b).map((q, j) => obstacleGap(obstacleOf(p, i), obstacleOf(q, j)).d), + ), + ) + + const scenes: [string, Nodes][] = [ + ['two rooms, a 0.70 m door', twoRooms(0.7)], + ['a bookcase in a corridor', corridorWithBookcase()], + ] + + for (const [name, nodes] of scenes) + test(`${name}: two named things are as far apart as the figure, one named thing is within its half width`, () => { + const found = passages(nodes) + expect(found.length).toBeGreaterThan(0) + for (const issue of found) { + const things = [...new Set(issue.obstacles.map((o) => o.nodeId))] + if (things.length === 2) + expect(Math.abs(gap(nodes, things[0]!, things[1]!) - issue.valueM!)).toBeLessThanOrEqual( + 0.02, + ) + else + for (const thing of things) + expect(reach(nodes, issue, thing)).toBeLessThanOrEqual(issue.valueM! / 2 + 0.03) + } + }) + + test('a bookcase against a wall names the two things the figure is the gap between', () => { + const [issue] = passages(corridorWithBookcase()).filter((i) => i.place.room === 'Study') + expect(new Set(issue!.obstacles.map((o) => o.nodeId)).size).toBe(2) + }) +}) + +describe('turning circles', () => { + test('a room smaller than 1.50 m across has none', () => { + const nodes = house([ + southWall, + frontDoor, + wall('wall_p', [1.4, 0], [1.4, 4]), + zone('zone_closet', 'Closet', [ + [0.05, 0.05], + [1.35, 0.05], + [1.35, 3.95], + [0.05, 3.95], + ]), + ]) + const found = issues(nodes).filter((i) => i.type === 'usage_turning_narrow') + expect(found).toHaveLength(1) + expect(found[0]!.valueM).toBeGreaterThan(1.2) + expect(found[0]!.valueM).toBeLessThan(1.4) + expect(found[0]!.message).toBe('No 1.50 m turning circle in “Closet”: largest 1.30 m.') + }) + + test('a wide room has one', () => { + expect(issues(twoRooms()).filter((i) => i.type === 'usage_turning_narrow')).toHaveLength(0) + }) +}) + +describe('pockets', () => { + test('floor a unit fits in, cut off by a 0.50 m gap, is a pocket', () => { + // a stub wall from the south wall leaves a 0.50 m gap to the north wall: the east side is cut off for a 0.60 m unit + const nodes = house([ + southWall, + frontDoor, + wall('wall_p', [3, 0], [3, 3.5]), + zone('zone_hall', 'Hall', [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ]), + ]) + const found = issues(nodes).filter((i) => i.type === 'usage_pocket') + expect(found).toHaveLength(1) + expect(found[0]!.valueM2).toBeGreaterThan(5) + expect(found[0]!.message).toContain('no 0.60 m way out') + }) +}) + +describe('the flag', () => { + afterEach(() => setSdfChecks(false)) + + test('is off until a host turns it on', () => { + expect(sdfChecksOn()).toBe(false) + }) + + test('verify_scene shows the findings only with it on', () => { + const nodes = twoRooms(0.7) + const context = { activeLevelId: null } + const types = () => + (verifyScene(nodes, {}, context).result as { issues: { type: string }[] }).issues.map( + (i) => i.type, + ) + expect(types().some((t) => t.startsWith('usage_'))).toBe(false) + setSdfChecks(true) + expect(types()).toContain('usage_passage_narrow') + }) + + test('with it off verify_scene returns what it returned before the check existed', () => { + const nodes = twoRooms(0.7) + const context = { activeLevelId: null } + const off = JSON.stringify(verifyScene(nodes, {}, context).result) + setSdfChecks(true) + setSdfChecks(false) + expect(JSON.stringify(verifyScene(nodes, {}, context).result)).toBe(off) + expect(off).not.toContain('usage_') + }) +}) diff --git a/packages/core/src/spatial/usage-field/findings.ts b/packages/core/src/spatial/usage-field/findings.ts new file mode 100644 index 0000000000..d2d018cb49 --- /dev/null +++ b/packages/core/src/spatial/usage-field/findings.ts @@ -0,0 +1,369 @@ +import { + type CodeProfileId, + type ThresholdSource, + USAGE_INDICATORS, +} from '../../building/code-profile' +import type { AnyNode, DoorNode, ItemNode } from '../../schema' +import { bedIssues } from './beds' +import { blockedOpeningIssues } from './blocked' +import { clashIssues } from './clash' +import { doorOverStairIssues } from './door-stairs' +import { entryIssues } from './entry-way' +import { fixtureClearanceIssues } from './fixtures' +import { m, nameOf, quote, unique } from './labels' +import { + type MeasureOptions, + measureUsage, + type ObstacleRef, + type Passage, + type RoomMeasure, +} from './measure' +import { PROTRUSION_LIMIT_M, type Protrusion, wallProtrusions } from './protrusion' +import { usageShapes } from './shapes' +import { doorSwingIssues } from './swings' +import type { Nodes } from './walls' + +/** Clear width of a path in a house: 0,90 m, the arrêté du 24 décembre 2015 art. 11 II (36 in is the IRC hall). */ +export const PASSAGE_M = USAGE_INDICATORS.passage.value +/** Clear width through an interior door: 32 in; the same arrêté art. 11 II asks 0,80 m nominal and 0,77 m clear. */ +export const DOOR_M = USAGE_INDICATORS.doorClear.value +/** Wheelchair turning space: 1.50 m (arrêté du 24 décembre 2015 art. 13; ADA 304.3). */ +export const TURNING_M = USAGE_INDICATORS.turning.value +/** One unit of passage: 0.60 m (a clearance of 0.30 m); a pocket smaller than this is not worth a finding. */ +export const POCKET_MIN_M2 = 0.36 +/** A reading within this of its threshold is the threshold. */ +export const TOLERANCE_M = 0.005 +/** Rooms whose passages are the same pinch: the same things bound it, a figure within this, a spot within `PLACE_AT_M`. */ +export const PLACE_WIDTH_M = 0.005 +const PLACE_AT_M = 0.5 + +export type UsageObstacle = { + nodeId: string + name: string + kind: string + shape: 'exact' | 'approx' + movable: boolean +} + +export type UsageIssue = { + type: + | 'usage_passage_narrow' + | 'usage_turning_narrow' + | 'usage_pocket' + | 'usage_wall_object_protrudes' + | 'usage_clash' + | 'usage_opening_blocked' + | 'usage_door_swing' + | 'usage_entry_narrow' + | 'usage_door_over_stair' + | 'usage_fixture_clearance' + | 'usage_bed_clearance' + message: string + /** Use defects warn even on approximate shapes; measurements and unassigned code checks inform. */ + severity: 'warning' | 'info' + nodeIds: string[] + valueM?: number + valueM2?: number + thresholdM?: number + /** A door's free swing, and the 90 degrees it should have. */ + valueDeg?: number + thresholdDeg?: number + /** For a finding that applies a code: which one, the section, whether its text was read, and whether the project named it or it is the default US IRC applied to a project that names none. */ + code?: { profile: CodeProfileId; cite: string; source: ThresholdSource; byDefault: boolean } + place: { room: string; roomId: string; at: [number, number] } + obstacles: UsageObstacle[] + fromDoorId?: string + /** A passage: every room the way through this place leads to, each with the best other exterior door when that reaches it more widely. */ + serves?: { room: string; roomId: string; alternative?: { doorId: string; widthM: number } }[] + /** A doorway between its jambs: the door as drawn, where `valueM` is the clear width between the jambs. */ + doorWidthM?: number + /** The name of the door a passage was measured from (the ground floor's entrance), when there is one. */ + fromDoor?: string + /** What the model's answer says of the finding when the note carries the rest: a room entry's clause for a turning circle and a pocket, a passage's sentence without the entrance (`verify-scene-usage`). */ + brief?: string + /** A pocket that is the whole room's free floor: the room cannot be left by a 0.60 m unit at all. */ + wholeRoom?: boolean + approximate: boolean +} + +const MOVABLE = /chair|stool|bedside|night ?stand|ottoman|pouf/i + +function describe(nodes: Nodes, refs: ObstacleRef[]): UsageObstacle[] { + return refs.map((ref) => { + const node = nodes[ref.nodeId] + const label = + ref.kind === 'void' + ? 'stairwell opening' + : ref.kind === 'stair-rail' + ? `${nameOf(nodes, ref.nodeId)} railing` + : nameOf(nodes, ref.nodeId) + return { + nodeId: ref.nodeId, + name: label, + kind: ref.kind, + shape: ref.shape, + movable: + node?.type === 'item' && + MOVABLE.test(`${(node as ItemNode).asset.id} ${(node as ItemNode).asset.name}`), + } + }) +} + +/** The things a finding names, once each: the two parts of one door frame are that door, not two things. */ +const distinctOf = (items: UsageObstacle[]) => + items.filter((item, at) => items.findIndex((o) => o.nodeId === item.nodeId) === at) + +/** The door whose two frame members are the pinch: it is passed through, not against. */ +const framedBy = (items: UsageObstacle[]) => { + const distinct = distinctOf(items) + return distinct.length === 1 && items.length >= 2 && distinct[0]!.kind === 'jamb' + ? distinct[0]! + : null +} + +function between(items: UsageObstacle[]): string { + const distinct = distinctOf(items) + if (distinct.length >= 2) + return ` between ${quote(distinct[0]!.name)} and ${quote(distinct[1]!.name)}` + if (distinct.length === 1) return ` against ${quote(distinct[0]!.name)}` + return '' +} + +const beside = (items: UsageObstacle[]) => { + const distinct = distinctOf(items) + return distinct.length ? `, beside ${distinct.map((item) => quote(item.name)).join(' and ')}` : '' +} + +const listOf = (names: string[]) => + names.length < 2 + ? (names[0] ?? '') + : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` + +type Narrow = { + room: RoomMeasure + passage: Passage + sides: UsageObstacle[] + limit: number + doorway: boolean +} + +/** The room's narrow passage, with what bounds it and the limit it is read against; null when it is not narrow. */ +function narrowPassage(nodes: Nodes, room: RoomMeasure): Narrow | null { + const passage = room.passage + if (!passage) return null + const sides = describe(nodes, passage.by) + // a pinch between two door-frame members is a doorway, and a doorway needs 0.80 m, not 0.90 m + const doorway = passage.by.some((o) => o.kind === 'jamb') + const limit = doorway ? DOOR_M : PASSAGE_M + return passage.width < limit - TOLERANCE_M ? { room, passage, sides, limit, doorway } : null +} + +const sameStuff = (a: UsageObstacle[], b: UsageObstacle[]) => { + const ids = (items: UsageObstacle[]) => [...new Set(items.map((o) => o.nodeId))].sort().join('|') + return ids(a) === ids(b) +} + +/** + * One finding for each place a way is narrow, however many rooms it leads to: the rooms whose + * narrowest point is the same pinch (the same things bound it, the same width, the same spot) are + * its `serves`, each with the best other exterior door when that reaches it more widely. + */ +function passageIssues(nodes: Nodes, rooms: RoomMeasure[]): UsageIssue[] { + const places: Narrow[][] = [] + for (const room of rooms) { + const narrow = narrowPassage(nodes, room) + if (!narrow) continue + const place = places.find(([first]) => { + const a = first!.passage + const b = narrow.passage + return ( + sameStuff(first!.sides, narrow.sides) && + Math.abs(a.width - b.width) <= PLACE_WIDTH_M && + Math.hypot(a.at[0] - b.at[0], a.at[1] - b.at[1]) <= PLACE_AT_M + ) + }) + if (place) place.push(narrow) + else places.push([narrow]) + } + return places.map((members) => passageIssue(nodes, members)) +} + +function passageIssue(nodes: Nodes, members: Narrow[]): UsageIssue { + const narrowest = members.reduce((best, n) => (n.passage.width < best.passage.width ? n : best)) + const { passage, sides, limit, doorway } = narrowest + const door = passage.fromDoorId ? nameOf(nodes, passage.fromDoorId) : null + const approximate = passage.by.some((o) => o.shape === 'approx') + const target = (room: RoomMeasure) => + room.kind === 'stair-foot' + ? `the foot of ${quote(room.name.replace(/^Foot of /, ''))}` + : quote(room.name) + // the best other exterior door, said once when it is the same for every room and by room when it is not + const first = members[0]!.room.alternative + const shared = + first && + members.every( + ({ room }) => + room.alternative?.doorId === first.doorId && room.alternative.width === first.width, + ) + ? first + : null + const alternativeOf = (alternative: { doorId: string; width: number }) => + `${m(alternative.width)} m from ${quote(nameOf(nodes, alternative.doorId))}` + const targets = listOf( + members.map(({ room }) => + !shared && room.alternative + ? `${target(room)} (${alternativeOf(room.alternative)})` + : target(room), + ), + ) + // a doorway is read between its jambs; the door as drawn is said beside it + const frame = framedBy(sides) + const drawn = frame ? (nodes[frame.nodeId] as DoorNode | undefined)?.width : undefined + const clause = `${ + frame + ? `${m(passage.width)} m clear between the jambs of ${quote(frame.name)}${typeof drawn === 'number' ? `, a ${m(drawn)} m door` : ''}` + : `${m(passage.width)} m${between(sides)}` + }${shared ? `; ${alternativeOf(shared)}` : ''}` + const sentence = `${targets}: ${clause}` + const tail = ` (below ${m(limit)} m${doorway ? ', a doorway' : ''}).` + const lead = members[0]!.room + return { + type: 'usage_passage_narrow', + message: `Narrow passage to ${sentence}${door ? `, measured from ${quote(door)}` : ''}${tail}`, + brief: `Passage to ${sentence}${tail}`, + ...(door ? { fromDoor: door } : {}), + severity: 'warning', + nodeIds: unique([ + ...members.map(({ room }) => (room.roomId.startsWith('zone_') ? room.roomId : undefined)), + ...sides.map((s) => s.nodeId), + ]), + valueM: passage.width, + thresholdM: limit, + ...(typeof drawn === 'number' ? { doorWidthM: drawn } : {}), + place: { room: lead.name, roomId: lead.roomId, at: passage.at }, + obstacles: sides, + ...(passage.fromDoorId ? { fromDoorId: passage.fromDoorId } : {}), + serves: members.map(({ room }) => ({ + room: room.name, + roomId: room.roomId, + ...(room.alternative + ? { alternative: { doorId: room.alternative.doorId, widthM: room.alternative.width } } + : {}), + })), + approximate, + } +} + +function turningIssue(room: RoomMeasure): UsageIssue | null { + const turning = room.turning + if (!turning || !(turning.diameter < TURNING_M - TOLERANCE_M)) return null + return { + type: 'usage_turning_narrow', + message: `No ${m(TURNING_M)} m turning circle in ${quote(room.name)}: largest ${m(turning.diameter)} m.`, + brief: `no ${m(TURNING_M)} m turning circle, largest ${m(turning.diameter)} m`, + // A turning circle is a measurement of the room, not a use defect of a piece: on an approximate outline it informs. + severity: turning.approximate ? 'info' : 'warning', + nodeIds: [room.roomId], + valueM: turning.diameter, + thresholdM: TURNING_M, + place: { room: room.name, roomId: room.roomId, at: turning.at }, + obstacles: [], + approximate: turning.approximate, + } +} + +function pocketIssue(nodes: Nodes, room: RoomMeasure, from: string): UsageIssue | null { + const pocket = room.pocket + if (!(pocket.isolatedM2 >= POCKET_MIN_M2) || !pocket.at) return null + const around = describe(nodes, pocket.by) + const approximate = pocket.by.some((o) => o.shape === 'approx') + const brief = pocket.whole + ? `no 0.60 m way out from ${from} (${m(pocket.isolatedM2)} m²)` + : `${m(pocket.isolatedM2)} m² of floor with no 0.60 m way out${beside(around)}` + return { + type: 'usage_pocket', + message: `${quote(room.name)}: ${brief}.`, + brief, + ...(pocket.whole ? { wholeRoom: true } : {}), + severity: 'warning', + nodeIds: unique([room.roomId, ...around.map((o) => o.nodeId)]), + valueM2: pocket.isolatedM2, + place: { room: room.name, roomId: room.roomId, at: pocket.at }, + obstacles: around, + approximate, + } +} + +function protrusionIssue(nodes: Nodes, found: Protrusion): UsageIssue { + return { + type: 'usage_wall_object_protrudes', + message: `${quote(nameOf(nodes, found.nodeId))} protrudes ${m(found.depth)} m from the wall at ${m(found.bottom)} m above a free floor in ${quote(found.roomName)} (over ${m(PROTRUSION_LIMIT_M)} m).`, + severity: 'warning', + nodeIds: [found.nodeId, found.wallId], + valueM: found.depth, + thresholdM: PROTRUSION_LIMIT_M, + place: { room: found.roomName, roomId: found.roomId, at: found.at }, + obstacles: [], + approximate: found.approximate, + } +} + +/** + * The usage findings of a scene: narrow passages (measured from the chosen entrance, one for each + * place that is narrow with the rooms it leads to, and the best other door as a fact), missing turning circles, floor a 0.60 m unit cannot get out of, wall + * objects that stand out into circulation, pieces inside something solid, what stands in front of a + * window or a door, a bed's room, a room's headroom and its ceiling. Every threshold is an indicator, + * not a compliance check. + */ +export function usageIssues(nodes: Nodes, options: MeasureOptions = {}): UsageIssue[] { + const shapes = usageShapes(nodes) + const measure = measureUsage(nodes, shapes, options) + const issues: UsageIssue[] = [] + for (const group of measure.groups) { + const from = group.source.kind === 'door' ? 'the entrance' : 'the stair arrival' + const rooms = group.rooms + const stuck = rooms.filter((room) => room.kind === 'room' && room.pocket.freeM2 > 0) + // a whole floor cut off from where it is entered is one finding, not one per room + const wholeFloor = + stuck.length > 1 && stuck.every((room) => room.pocket.whole) && group.source.kind !== 'none' + if (wholeFloor) { + const level = nodes[group.levelId] as + | (AnyNode & { name?: string; level?: number }) + | undefined + const area = stuck.reduce((sum, room) => sum + room.pocket.isolatedM2, 0) + issues.push({ + type: 'usage_pocket', + message: `${quote(String(level?.name ?? `Level ${level?.level ?? ''}`))}: no 0.60 m way out from ${from} (${m(area)} m²).`, + brief: `no 0.60 m way out from ${from} (${m(area)} m²)`, + wholeRoom: true, + severity: 'warning', + nodeIds: unique([group.levelId, ...stuck.map((room) => room.roomId)]), + valueM2: Math.round(area * 1000) / 1000, + place: { room: String(level?.name ?? 'Level'), roomId: group.levelId, at: stuck[0]!.at }, + obstacles: [], + approximate: false, + }) + } + issues.push(...passageIssues(nodes, rooms)) + for (const room of rooms) { + const turning = turningIssue(room) + if (turning) issues.push(turning) + if (!wholeFloor) { + const pocket = pocketIssue(nodes, room, from) + if (pocket) issues.push(pocket) + } + } + } + for (const found of wallProtrusions(nodes, shapes)) + if (found.depth > PROTRUSION_LIMIT_M + TOLERANCE_M) issues.push(protrusionIssue(nodes, found)) + issues.push( + ...clashIssues(nodes, shapes), + ...blockedOpeningIssues(nodes, shapes), + ...doorSwingIssues(nodes, shapes), + ...entryIssues(nodes, shapes), + ...doorOverStairIssues(nodes, shapes), + ...fixtureClearanceIssues(nodes, shapes), + ...bedIssues(nodes, shapes), + ) + return issues +} diff --git a/packages/core/src/spatial/usage-field/fixtures.ts b/packages/core/src/spatial/usage-field/fixtures.ts new file mode 100644 index 0000000000..7ccb3d3a95 --- /dev/null +++ b/packages/core/src/spatial/usage-field/fixtures.ts @@ -0,0 +1,187 @@ +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { + CODE_PROFILES, + type CodeProfile, + codeProfileOf, + type Threshold, + type ThresholdId, +} from '../../building/code-profile' +import type { ItemNode } from '../../schema' +import { catalogueKey } from './catalogue' +import type { UsageIssue } from './findings' +import { m, nameOf, quote, unique } from './labels' +import { type Obstacle, obstaclesInBand, rayHit } from './obstacles' +import { roomAt } from './pieces' +import type { Prism, UsageShapes } from './types' +import type { Nodes } from './walls' + +const TOILET = /toilet|water ?closet|(?:^|[^a-z])wc(?![a-z])/i +const BASIN = /basin|lavatory|vanity|bathroom[- ]sink|wash ?hand/i +const BASIN_WORD = /basin|lavatory|vanity|sink|wash ?hand/i +const SHOWER = /shower/i +/** The feet band: what a person's legs and a fixture's rim meet (m above the floor). */ +const BAND = { from: 0.05, to: 0.9 } +const RAY_MAX_M = 1.5 +/** Where along a fixture's depth, from its back, the sides are read. */ +const SIDE_SAMPLES = [0.25, 0.5, 0.75, 1] +/** A lavatory this wide has more than one basin: its centre line is not a basin's. */ +const SINGLE_BASIN_MAX_M = 1.0 + +type Kind = 'toilet' | 'lavatory' | 'shower' +type Point = [number, number] + +const kindOf = (item: ItemNode): Kind | null => { + const text = `${item.name ?? ''} ${item.asset.name ?? ''} ${item.asset.id ?? ''} ${item.asset.category ?? ''}` + const key = catalogueKey(item.asset.src ?? '') + if (key === 'system/toilet' || (TOILET.test(text) && !BASIN_WORD.test(text))) return 'toilet' + if (key === 'system/shower-square' || SHOWER.test(text)) return 'shower' + if (key === 'system/bathroom-sink' || (BASIN.test(text) && !/kitchen/i.test(text))) + return 'lavatory' + return null +} + +const inchesText = (metres: number) => `${Math.round(metres / 0.0254)} in` + +/** + * Bathroom fixture clearances: a toilet's centre to the nearest obstruction on each side and its clear + * space in front, a lavatory's front (and, for a single basin, its side), a shower's clear space at its + * best open side. Read on the exact outlines of the feet band. The fixture's front is its +Z, checked + * against the wall behind it (a fixture whose back is free and whose +Z meets a wall is read the other + * way round); a shower has no opening side in the model, so the best of its four sides is read, which is + * as good as the opening can be. + * + * These are a code's numbers. With no `site.metadata.codeProfile` the scene has no jurisdiction, and a + * finding is information that names the US IRC it used; with `irc-2021` set it is a warning. A profile + * with no row for it (the Australian NCC, France hold none of the bathroom figures) reports nothing. + * Approximate fixture outlines remain labeled as such without downgrading a clearance defect. + */ +export function fixtureClearanceIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { + const profile = codeProfileOf(nodes) + const applied: CodeProfile = profile ?? CODE_PROFILES['irc-2021'] + if (Object.keys(applied.thresholds).length === 0) return [] + const out: UsageIssue[] = [] + + for (const level of shapes.levels) { + const prisms = level.prisms.filter( + (prism) => + !(nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode)), + ) + for (const item of Object.values(nodes)) { + if (item.type !== 'item' || item.visible === false || item.parentId !== level.levelId) + continue + const kind = kindOf(item) + if (!kind) continue + const own = prisms.filter((p) => p.nodeId === item.id) + if (!own.length) continue + const approximate = own.some((p) => p.shape === 'approx') + // the feet band stands on the fixture's own floor: a floor plate set off its storey's base is the fixture's floor + const floorY = Math.min(...own.map((p) => p.z0)) + const band = { z0: floorY + BAND.from, z1: floorY + BAND.to } + const yaw = item.rotation?.[1] ?? 0 + const f: Point = [Math.sin(yaw), Math.cos(yaw)] + const r: Point = [Math.cos(yaw), -Math.sin(yaw)] + const points = own.flatMap((p: Prism) => p.outer) as Point[] + const project = (u: Point) => points.map((p) => p[0] * u[0] + p[1] * u[1]) + const [r0, r1] = [Math.min(...project(r)), Math.max(...project(r))] + const [f0, f1] = [Math.min(...project(f)), Math.max(...project(f))] + const at = (ur: number, uf: number): Point => [r[0] * ur + f[0] * uf, r[1] * ur + f[1] * uf] + const obstacles: Obstacle[] = obstaclesInBand(prisms, band, undefined, (p) => { + if (p.nodeId === item.id || p.kind === 'treatment') return true + const owner = nodes[p.nodeId] + return owner?.type === 'item' && owner.parentId === item.id + }) + const middle = (r0 + r1) / 2 + const depth = f1 - f0 + const behind = rayHit(at(middle, f0 - 0.001), [-f[0], -f[1]], obstacles, 0.4) + const ahead = rayHit(at(middle, f1 + 0.001), f, obstacles, 0.4) + const turned = behind > ahead + 0.05 && ahead < 0.15 + const front: Point = turned ? [-f[0], -f[1]] : f + const edge = turned ? f0 - 0.001 : f1 + 0.001 + + const measures: { id: ThresholdId; label: string; value: number }[] = [] + if (kind === 'shower') { + let best = 0 + for (const [dir, e, u0, u1, across] of [ + [f, f1 + 0.001, r0, r1, true], + [[-f[0], -f[1]] as Point, f0 - 0.001, r0, r1, true], + [r, r1 + 0.001, f0, f1, false], + [[-r[0], -r[1]] as Point, r0 - 0.001, f0, f1, false], + ] as const) { + const clear = Math.min( + ...[0.25, 0.5, 0.75].map((s) => { + const u = u0 + (u1 - u0) * s + return rayHit(across ? at(u, e) : at(e, u), dir, obstacles, RAY_MAX_M) + }), + ) + best = Math.max(best, clear) + } + measures.push({ + id: 'showerFrontClear', + label: 'in front of its best open side', + value: best, + }) + } else { + const front0 = [-0.25, -0.125, 0, 0.125, 0.25].map((o) => + rayHit(at(middle + o, edge), front, obstacles, RAY_MAX_M), + ) + measures.push({ + id: kind === 'toilet' ? 'toiletFrontClear' : 'lavatoryFrontClear', + label: 'in front', + value: Math.min(...front0), + }) + if (kind === 'toilet' || r1 - r0 <= SINGLE_BASIN_MAX_M) { + let side = Number.POSITIVE_INFINITY + // not along the back edge: a ray grazing the wall behind the fixture is not a side obstruction + for (const sign of [-1, 1] as const) + for (const share of SIDE_SAMPLES) + side = Math.min( + side, + (r1 - r0) / 2 + + rayHit( + at(sign > 0 ? r1 + 0.001 : r0 - 0.001, f0 + depth * share), + [r[0] * sign, r[1] * sign], + obstacles, + 0.6, + ), + ) + measures.push({ + id: kind === 'toilet' ? 'toiletSideClear' : 'lavatorySideClear', + label: 'from its centre to the nearest obstruction at the side', + value: side, + }) + } + } + + const room = roomAt(nodes, level.levelId, at(middle, (f0 + f1) / 2)) + const name = nameOf(nodes, item.id) + for (const { id, label, value } of measures) { + const row: Threshold | undefined = applied.thresholds[id] + if (!row || !(value < row.value - 0.005)) continue + const secondary = row.source === 'secondary source' + const best = id === 'showerFrontClear' + out.push({ + type: 'usage_fixture_clearance', + message: `${quote(name)}${room ? ` in ${quote(room.name)}` : ''} has ${m(value)} m ${label}${best ? ', the best of its four sides (the model has no opening side)' : ''}; ${applied.label} (${row.section}${secondary ? ', secondary source' : ''}) asks ${m(row.value)} m (${inchesText(row.value)})${profile ? '' : ', and this project names no code'}.`, + severity: profile ? 'warning' : 'info', + nodeIds: unique([room?.id, item.id]), + valueM: Math.round(value * 1000) / 1000, + thresholdM: row.value, + place: { + room: room?.name ?? '', + roomId: room?.id ?? level.levelId, + at: at(middle, (f0 + f1) / 2), + }, + obstacles: [], + approximate, + code: { + profile: applied.id, + cite: row.cite, + source: row.source, + byDefault: profile === null, + }, + }) + } + } + } + return out +} diff --git a/packages/core/src/spatial/usage-field/flag.test.ts b/packages/core/src/spatial/usage-field/flag.test.ts new file mode 100644 index 0000000000..f1c7b4a1bf --- /dev/null +++ b/packages/core/src/spatial/usage-field/flag.test.ts @@ -0,0 +1,20 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { sdfChecksFromEnv, sdfChecksOn, setSdfChecks } from './flag' + +afterEach(() => setSdfChecks(false)) + +describe('the usage-checks flag', () => { + test('is off until a host turns it on, and a host turns it off again', () => { + expect(sdfChecksOn()).toBe(false) + setSdfChecks(true) + expect(sdfChecksOn()).toBe(true) + setSdfChecks(false) + expect(sdfChecksOn()).toBe(false) + }) + + test('PASCAL_SDF_CHECKS turns it on with 1 or true and nothing else does', () => { + for (const on of ['1', 'true', 'TRUE', 'True']) expect(sdfChecksFromEnv(on)).toBe(true) + for (const off of [undefined, '', '0', 'false', 'no', 'yes', ' 1', '2']) + expect(sdfChecksFromEnv(off)).toBe(false) + }) +}) diff --git a/packages/core/src/spatial/usage-field/flag.ts b/packages/core/src/spatial/usage-field/flag.ts new file mode 100644 index 0000000000..5eae58a521 --- /dev/null +++ b/packages/core/src/spatial/usage-field/flag.ts @@ -0,0 +1,16 @@ +let enabled = false + +/** + * Usage checks (passages, turning circles, pockets, wall objects, measured flow) are off until a + * host turns them on. Core reads no environment: the app and the servers set this once at start, + * from `PASCAL_SDF_CHECKS`. + */ +export function setSdfChecks(on: boolean): void { + enabled = on +} + +export const sdfChecksOn = (): boolean => enabled + +/** What `PASCAL_SDF_CHECKS` (or its `NEXT_PUBLIC_` mirror) says: `1` or `true` turns the checks on, anything else, or nothing, leaves them off. */ +export const sdfChecksFromEnv = (value: string | undefined): boolean => + value === '1' || value?.toLowerCase() === 'true' diff --git a/packages/core/src/spatial/usage-field/floors.ts b/packages/core/src/spatial/usage-field/floors.ts new file mode 100644 index 0000000000..4fdc2b1518 --- /dev/null +++ b/packages/core/src/spatial/usage-field/floors.ts @@ -0,0 +1,42 @@ +import { floorsOf } from '../../agent-operations/circulation-spaces' +import { difference } from '../../lib/polygon-boolean' +import type { FloorRegion, Skipped } from './types' +import type { Nodes } from './walls' + +/** + * The floor a person stands on, level by level: each slab's walking surface less the floor openings + * and lift shafts cut through it, at the height the circulation graph reads (`floorsOf`), so the + * usage checks and the circulation report stand on the same floor. A slab draped over terrain is one + * flat height here and is marked approximate; a recessed slab (a pool) is not a floor. + */ +export function levelFloors(nodes: Nodes): { + floors: Map + skipped: Skipped[] +} { + const floors = new Map() + const skipped: Skipped[] = [] + for (const floor of floorsOf(nodes).floors) { + const cuts = [...floor.voids, ...floor.shafts].map((ring) => ({ outer: ring, holes: [] })) + const regions: FloorRegion[] = [] + for (const slab of floor.slabs) { + const source = nodes[slab.id] + if (source?.type === 'slab' && source.recessed) { + skipped.push({ nodeId: slab.id, why: 'a recessed slab is not a floor to stand on' }) + continue + } + const pieces = difference({ outer: slab.polygon, holes: slab.holes }, cuts) + for (const [index, piece] of pieces.entries()) + regions.push({ + id: `${slab.id}#floor${pieces.length > 1 ? `.${index}` : ''}`, + nodeId: slab.id, + outer: piece.outer, + holes: piece.holes, + y: slab.elevation, + outdoor: slab.outdoor, + shape: 'exact', + }) + } + floors.set(floor.id, regions) + } + return { floors, skipped } +} diff --git a/packages/core/src/spatial/usage-field/index.ts b/packages/core/src/spatial/usage-field/index.ts new file mode 100644 index 0000000000..b03d290a37 --- /dev/null +++ b/packages/core/src/spatial/usage-field/index.ts @@ -0,0 +1,6 @@ +export { catalogueKey } from './catalogue' +export { type UsageIssue, usageIssues } from './findings' +export { sdfChecksFromEnv, sdfChecksOn, setSdfChecks } from './flag' +export { measureUsage, type UsageMeasure } from './measure' +export { usageShapes } from './shapes' +export type { FloorRegion, LevelShapes, Prism, PrismKind, Skipped, UsageShapes } from './types' diff --git a/packages/core/src/spatial/usage-field/items.test.ts b/packages/core/src/spatial/usage-field/items.test.ts new file mode 100644 index 0000000000..3c1c84c830 --- /dev/null +++ b/packages/core/src/spatial/usage-field/items.test.ts @@ -0,0 +1,286 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, BuildingNode, ItemNode, LevelNode, SlabNode, WallNode } from '../../schema' +import { catalogueKey } from './catalogue' +import { itemBodies } from './items' +import type { Prism } from './types' +import type { Nodes } from './walls' + +const SHA = 'a'.repeat(64) + +function scene(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const asset = (over: Record = {}) => ({ + id: 'thing', + name: 'Thing', + category: 'furniture', + thumbnail: '/thumb.webp', + src: `artifact://${SHA}`, + dimensions: [1.2, 0.75, 0.7], + ...over, +}) + +type Manifest = Record + +const manifestOf = (over: Manifest = {}) => ({ + bounds: { min: [-0.6, 0, -0.35], max: [0.6, 0.75, 0.35] }, + triangles: 12, + ...over, +}) + +const TABLE_SHAPE = { + tolerance: 0.009, + bands: [ + { + y0: 0, + y1: 0.7, + polygons: [ + { + outer: [ + [-0.6, -0.35], + [-0.55, -0.35], + [-0.55, -0.3], + [-0.6, -0.3], + ], + }, + { + outer: [ + [0.55, -0.35], + [0.6, -0.35], + [0.6, -0.3], + [0.55, -0.3], + ], + }, + ], + }, + { + y0: 0.7, + y1: 0.75, + polygons: [ + { + outer: [ + [-0.6, -0.35], + [0.6, -0.35], + [0.6, 0.35], + [-0.6, 0.35], + ], + }, + ], + }, + ], +} + +function scripted(over: Record = {}, manifest: Manifest = {}) { + return ItemNode.parse({ + id: 'item_1', + parentId: 'level_1', + position: [3, 0, 2], + asset: asset(), + source: { kind: 'script', script: SHA, artifact: SHA, manifest: manifestOf(manifest) }, + ...over, + }) +} + +const bounds = (prisms: Prism[]) => { + const points = prisms.flatMap((p) => p.outer) + const xs = points.map(([x]) => x) + const zs = points.map(([, z]) => z) + return { x0: Math.min(...xs), x1: Math.max(...xs), z0: Math.min(...zs), z1: Math.max(...zs) } +} + +const prismsOf = (nodes: Nodes, id = 'item_1') => + itemBodies(nodes).items.find((i) => i.itemId === id)!.prisms + +describe('a scripted item with a stored shape', () => { + test('stands where it is placed, band by band', () => { + const prisms = prismsOf(scene([scripted({}, { shape: TABLE_SHAPE })])) + expect(prisms).toHaveLength(3) + const top = prisms.find((p) => p.z0 > 0.69)! + expect([top.z0, top.z1]).toEqual([0.7, 0.75]) + expect(bounds([top])).toEqual({ x0: 2.4, x1: 3.6, z0: 1.65, z1: 2.35 }) + expect(prisms.every((p) => p.shape === 'exact' && p.kind === 'item')).toBe(true) + }) + + test('turns with the item and scales with it', () => { + const turned = prismsOf( + scene([scripted({ rotation: [0, Math.PI / 2, 0] }, { shape: TABLE_SHAPE })]), + ) + const top = turned.find((p) => p.z0 > 0.69)! + const b = bounds([top]) + expect(b.x1 - b.x0).toBeCloseTo(0.7, 6) + expect(b.z1 - b.z0).toBeCloseTo(1.2, 6) + const scaled = prismsOf(scene([scripted({ scale: [2, 1.5, 1] }, { shape: TABLE_SHAPE })])) + const wide = scaled.find((p) => p.z0 > 1)! + expect(wide.z1).toBeCloseTo(1.125, 6) + expect(bounds([wide]).x1 - bounds([wide]).x0).toBeCloseTo(2.4, 6) + }) + + test("a mirrored item keeps each ring's winding", () => { + const [prism] = prismsOf( + scene([scripted({ scale: [-1, 1, 1] }, { shape: TABLE_SHAPE })]), + ).filter((p) => p.z0 > 0.69) + const area = prism!.outer.reduce((sum, p, i) => { + const q = prism!.outer[(i + 1) % prism!.outer.length]! + return sum + p[0] * q[1] - q[0] * p[1] + }, 0) + expect(area).toBeGreaterThan(0) + }) + + test('the asset corrective offset and rotation apply before the item scale and pose', () => { + const prisms = prismsOf( + scene([ + scripted( + { asset: asset({ offset: [0.1, 0.05, 0], rotation: [0, Math.PI / 2, 0] }) }, + { shape: TABLE_SHAPE }, + ), + ]), + ) + const top = prisms.find((p) => p.z0 > 0.7)! + expect(top.z0).toBeCloseTo(0.75, 6) + const b = bounds([top]) + expect(b.x1 - b.x0).toBeCloseTo(0.7, 6) + expect((b.x0 + b.x1) / 2).toBeCloseTo(3.1, 6) + }) + + test('it stands on the slab under it, at the level above the floor', () => { + const slab = SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [0, 0], + [8, 0], + [8, 8], + [0, 8], + ], + elevation: 0.15, + }) + const prisms = prismsOf(scene([slab, scripted({}, { shape: TABLE_SHAPE })])) + expect(Math.min(...prisms.map((p) => p.z0))).toBeCloseTo(0.15, 6) + const pinned = scripted({ supportSlabId: 'ground' }, { shape: TABLE_SHAPE }) + expect(Math.min(...prismsOf(scene([slab, pinned])).map((p) => p.z0))).toBeCloseTo(0, 6) + }) + + test('a shape simplified to fit its manifest is approximate', () => { + const coarse = { ...TABLE_SHAPE, tolerance: 0.05 } + expect( + prismsOf(scene([scripted({}, { shape: coarse })])).every((p) => p.shape === 'approx'), + ).toBe(true) + }) +}) + +describe('an item without a stored shape', () => { + test("a script compiled before reads as its parts' boxes, approximate", () => { + const parts = [ + { id: 'legs', bounds: { min: [-0.6, 0, -0.35], max: [0.6, 0.7, 0.35] } }, + { id: 'top', bounds: { min: [-0.6, 0.7, -0.35], max: [0.6, 0.75, 0.35] } }, + ] + const prisms = prismsOf(scene([scripted({}, { parts })])) + expect(prisms).toHaveLength(2) + expect(prisms.every((p) => p.shape === 'approx' && p.why?.includes('parts'))).toBe(true) + }) + + test('with no parts it is its bounds box', () => { + const prisms = prismsOf(scene([scripted()])) + expect(prisms).toHaveLength(1) + expect(prisms[0]!.why).toContain('bounds box') + }) + + test('a catalogue model is its box, centred on its position', () => { + const chair = ItemNode.parse({ + id: 'item_2', + parentId: 'level_1', + position: [1, 0, 1], + asset: asset({ src: '/items/chair/model.glb', dimensions: [0.5, 0.9, 0.5] }), + }) + const [prism] = prismsOf(scene([chair]), 'item_2') + expect(bounds([prism!])).toEqual({ x0: 0.75, x1: 1.25, z0: 0.75, z1: 1.25 }) + expect([prism!.z0, prism!.z1]).toEqual([0, 0.9]) + expect(prism!.shape).toBe('approx') + }) + + test('a library model has the outline baked from its GLB, under its own corrective transform', () => { + const src = 'https://host.example/storage/v1/object/public/items/system/fridge/model.glb' + expect(catalogueKey(src)).toBe('system/fridge') + expect(catalogueKey('artifact://abc')).toBeNull() + const fridge = ItemNode.parse({ + id: 'item_5', + parentId: 'level_1', + position: [2, 0, 2], + asset: asset({ src, dimensions: [0.7, 1.8, 0.7] }), + }) + const prisms = prismsOf(scene([fridge]), 'item_5') + expect(prisms.length).toBeGreaterThan(0) + expect(prisms.every((p) => p.shape === 'exact')).toBe(true) + expect(Math.max(...prisms.map((p) => p.z1))).toBeGreaterThan(1.5) + }) + + test('an item tilted about a horizontal axis is its box, approximate', () => { + const prisms = prismsOf(scene([scripted({ rotation: [0.4, 0, 0] }, { shape: TABLE_SHAPE })])) + expect(prisms).toHaveLength(1) + expect(prisms[0]!.why).toContain('horizontal axis') + }) +}) + +describe('items hosted elsewhere', () => { + test('an item on another item stands on it and turns with it', () => { + const table = scripted({ rotation: [0, Math.PI / 2, 0] }, { shape: TABLE_SHAPE }) + const lamp = ItemNode.parse({ + id: 'item_2', + parentId: table.id, + position: [0.5, 0.75, 0], + asset: asset({ src: '/items/lamp/model.glb', dimensions: [0.2, 0.4, 0.2] }), + }) + const [prism] = prismsOf(scene([table, lamp]), 'item_2') + expect(prism!.z0).toBeCloseTo(0.75, 6) + expect(prism!.z1).toBeCloseTo(1.15, 6) + // 0.5 m along the table's x, which a quarter turn lays along -z + const b = bounds([prism!]) + expect((b.x0 + b.x1) / 2).toBeCloseTo(3, 6) + expect((b.z0 + b.z1) / 2).toBeCloseTo(1.5, 6) + }) + + test('a wall-mounted item stands out of the wall face it is on', () => { + const wall = WallNode.parse({ + id: 'wall_1', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + thickness: 0.1, + children: ['item_3'], + }) + const cabinet = ItemNode.parse({ + id: 'item_3', + parentId: wall.id, + wallId: wall.id, + position: [2, 1.4, 0], + asset: asset({ + attachTo: 'wall-side', + src: '/items/cabinet/model.glb', + dimensions: [0.85, 0.6, 0.46], + }), + side: 'front', + }) + const [prism] = prismsOf(scene([wall, cabinet]), 'item_3') + expect(prism!.host).toEqual({ wallId: 'wall_1', face: 'a' }) + // the catalogue box is centred on its position, so half of it is in the wall: the face-side z is 0.05 + expect([prism!.z0, prism!.z1]).toEqual([1.4, 2.0]) + }) + + test('a ceiling item is counted, not shaped', () => { + const lamp = ItemNode.parse({ + id: 'item_4', + parentId: 'level_1', + asset: asset({ attachTo: 'ceiling' }), + }) + const result = itemBodies(scene([lamp])) + expect(result.items).toHaveLength(0) + expect(result.unshaped).toEqual({ 'ceiling item': 1 }) + }) + + test('a hidden item, or one in a hidden level, is left out', () => { + expect(itemBodies(scene([scripted({ visible: false })])).items).toHaveLength(0) + }) +}) diff --git a/packages/core/src/spatial/usage-field/items.ts b/packages/core/src/spatial/usage-field/items.ts new file mode 100644 index 0000000000..eea4ee85ce --- /dev/null +++ b/packages/core/src/spatial/usage-field/items.ts @@ -0,0 +1,321 @@ +import { itemLevelPose } from '../../agent-operations/item-space' +import { resolveLevelId } from '../../lib/node-ancestry' +import { wallSupportForNodes } from '../../lib/opening-floor-datum' +import type { AnyNode, GeometryShape, ItemNode, WallNode } from '../../schema' +import { getScaledDimensions } from '../../schema/nodes/item' +import { getLevelElevations } from '../../services/storey' +import { + getWallCurveFrameAt, + getWallCurveLength, + isCurvedWall, +} from '../../systems/wall/wall-curve' +import { getWallBodyCenterOffset, getWallLocalFaceZ } from '../../systems/wall/wall-frame' +import { catalogueShape } from './catalogue' +import { floorUnder, isHidden, type SupportCache } from './support' +import type { Prism, Ring, Skipped } from './types' +import type { Nodes } from './walls' + +type Point = [number, number] +type Band = GeometryShape['bands'][number] + +/** A stored shape no looser than this is read as the build's own outline. */ +export const EXACT_SHAPE_TOLERANCE_M = 0.02 +const ROTATION_EPSILON = 1e-9 + +export type ItemShapes = { itemId: string; levelId: string | null; prisms: Prism[] } + +/** A band list in its own frame, with how far to trust it. */ +type Local = { bands: Band[]; frame: 'artifact' | 'node'; shape: 'exact' | 'approx'; why?: string } + +const rectangle = (x0: number, z0: number, x1: number, z1: number): Ring => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], +] + +function boxBand(min: readonly number[], max: readonly number[]): Band { + return { + y0: min[1]!, + y1: max[1]!, + polygons: [{ outer: rectangle(min[0]!, min[2]!, max[0]!, max[2]!) }], + } +} + +/** + * What an item occupies in its own frame. A script compiled with usage checks on carries the + * outline it traced from its meshes; one compiled before has only its parts' and its bounds, which + * are drawn as boxes and marked approximate; a library model has the outline baked from its GLB, and + * one without is its box. + */ +function localShape(item: ItemNode): Local { + const manifest = item.source?.manifest + if (manifest?.shape) { + const coarse = manifest.shape.tolerance > EXACT_SHAPE_TOLERANCE_M + return { + bands: manifest.shape.bands, + frame: 'artifact', + shape: coarse ? 'approx' : 'exact', + ...(coarse ? { why: 'a script outline simplified to fit its manifest' } : {}), + } + } + if (manifest) { + const parts = manifest.parts.filter((part) => part.bounds) + if (parts.length >= 2) + return { + bands: parts.map((part) => boxBand(part.bounds!.min, part.bounds!.max)), + frame: 'artifact', + shape: 'approx', + why: 'a script compiled without a usage outline: its parts as boxes', + } + return { + bands: [boxBand(manifest.bounds.min, manifest.bounds.max)], + frame: 'artifact', + shape: 'approx', + why: 'a script compiled without a usage outline: its bounds box', + } + } + const baked = catalogueShape(item.asset.src) + if (baked) { + const coarse = baked.tolerance > EXACT_SHAPE_TOLERANCE_M + return { + bands: baked.bands, + frame: 'artifact', + shape: coarse ? 'approx' : 'exact', + ...(coarse ? { why: 'a library model outlined to within a few centimetres' } : {}), + } + } + const [w, h, d] = item.asset.dimensions + return { + bands: [boxBand([-w / 2, 0, -d / 2], [w / 2, h, d / 2])], + frame: 'node', + shape: 'approx', + why: 'a catalogue model: its box', + } +} + +const turn = (x: number, z: number, angle: number): Point => [ + x * Math.cos(angle) + z * Math.sin(angle), + -x * Math.sin(angle) + z * Math.cos(angle), +] + +const flat = (rotation: readonly number[]) => + Math.abs(rotation[0] ?? 0) < ROTATION_EPSILON && Math.abs(rotation[2] ?? 0) < ROTATION_EPSILON + +const orientation = (ring: Ring) => { + let a = 0 + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) + a += ring[j]![0] * ring[i]![1] - ring[i]![0] * ring[j]![1] + return a +} + +type Placement = { + /** The item's origin in the host frame: plan x, z and the absolute height of its base. */ + origin: [number, number, number] + /** Turn, about the vertical, from the host frame. */ + yaw: number + /** Host-frame plan point to building plan. */ + plan: (x: number, z: number) => Point + host?: Prism['host'] + approx?: string +} + +/** One local band as a prism in building metres, through the corrective, node and host transforms. */ +function bandPrisms(item: ItemNode, local: Local, place: Placement, id: string): Prism[] { + const assetScale = item.asset.scale ?? [1, 1, 1] + const offset = item.asset.offset + const corrective = local.frame === 'artifact' + const scale = item.scale + const asset = corrective ? item.asset.rotation[1]! : 0 + const out: Prism[] = [] + for (const [index, band] of local.bands.entries()) { + const heightAt = (y: number) => + place.origin[2] + (corrective ? assetScale[1]! * y + offset[1]! : y) * scale[1]! + const [z0, z1] = [heightAt(band.y0), heightAt(band.y1)].sort((a, b) => a - b) as [ + number, + number, + ] + for (const [k, polygon] of band.polygons.entries()) { + const ring = (points: Ring): Ring => { + const moved = points.map(([x, z]) => { + let px = x + let pz = z + if (corrective) { + ;[px, pz] = turn(x * assetScale[0]!, z * assetScale[2]!, asset) + px += offset[0]! + pz += offset[2]! + } + ;[px, pz] = turn(px * scale[0]!, pz * scale[2]!, place.yaw) + return place.plan(px + place.origin[0], pz + place.origin[1]) + }) + // A mirrored item (a negative scale) reverses the winding; keep each ring's as it was. + return orientation(moved) * orientation(points) < 0 ? moved.reverse() : moved + } + out.push({ + id: `${id}.${index}.${k}`, + nodeId: item.id, + kind: 'item', + z0, + z1, + outer: ring(polygon.outer), + holes: (polygon.holes ?? []).map(ring), + shape: local.shape === 'exact' && !place.approx ? 'exact' : 'approx', + ...(local.why || place.approx ? { why: local.why ?? place.approx } : {}), + ...(place.host ? { host: place.host } : {}), + }) + } + } + return out +} + +/** The box a tilted or oddly scaled item fills, as one approximate prism. */ +function tiltedPrism(item: ItemNode, place: Placement, id: string): Prism[] { + const [sx, sy, sz] = item.scale + const [w, h, d] = item.asset.dimensions + const half: Ring = rectangle((-w / 2) * sx, (-d / 2) * sz, (w / 2) * sx, (d / 2) * sz) + const moved = half.map(([x, z]) => { + const [px, pz] = turn(x, z, place.yaw) + return place.plan(px + place.origin[0], pz + place.origin[1]) + }) + return [ + { + id, + nodeId: item.id, + kind: 'item', + z0: place.origin[2], + z1: place.origin[2] + h * sy, + outer: moved, + holes: [], + shape: 'approx', + why: 'an item turned about a horizontal axis: its box', + ...(place.host ? { host: place.host } : {}), + }, + ] +} + +/** Where a wall's local frame (x along the wall, z across, toward its left) lands in plan. */ +function wallPlan(wall: WallNode): Placement['plan'] { + const length = getWallCurveLength(wall) + return (x, z) => { + const frame = getWallCurveFrameAt( + wall, + length > 1e-9 ? Math.min(1, Math.max(0, x / length)) : 0, + ) + return [frame.point.x + frame.normal.x * z, frame.point.y + frame.normal.y * z] + } +} + +export type ItemContext = { + nodes: Nodes + byId: Map + elevations: ReturnType + supportCache: SupportCache +} + +export const itemContext = (nodes: Nodes): ItemContext => ({ + nodes, + byId: new Map(Object.entries(nodes)), + elevations: getLevelElevations(nodes as never), + supportCache: new Map(), +}) + +/** One item as prisms in absolute building metres; or `unshaped` with what it is hosted by, or `skipped` with why. */ +export function itemShapesOf( + item: ItemNode, + { nodes, byId, elevations, supportCache }: ItemContext, +): { shapes: ItemShapes } | { unshaped: string } | { skipped: Skipped } { + try { + if (item.asset.attachTo === 'ceiling') return { unshaped: 'ceiling item' } + if (item.roofSegmentId || item.blockFaceId) return { unshaped: 'item on a roof or a block' } + const levelId = resolveLevelId(item, nodes as Record) + const baseY = elevations.get(levelId)?.baseY ?? 0 + const parent = item.parentId ? nodes[item.parentId] : undefined + const local = localShape(item) + let place: Placement + if (parent?.type === 'wall') { + if (item.asset.attachTo !== 'wall' && item.asset.attachTo !== 'wall-side') + return { unshaped: 'item on a wall that is not wall-mounted' } + const wall = parent + const across = + item.asset.attachTo === 'wall-side' + ? getWallLocalFaceZ(wall, item.side === 'front' ? 'a' : 'b') + : item.position[2] + getWallBodyCenterOffset(wall) + const base = baseY + wallSupportForNodes(wall, nodes).elevation + place = { + origin: [item.position[0], across, base + item.position[1]], + yaw: item.rotation[1]!, + plan: wallPlan(wall), + host: { wallId: wall.id, face: across >= 0 ? 'a' : 'b' }, + ...(isCurvedWall(wall) ? { approx: 'an item on a curved wall' } : {}), + } + } else { + const pose = itemLevelPose(item, byId) + if (!pose) return { unshaped: 'item hosted where its pose cannot be read' } + const [x, y, z] = pose.position + const root = rootOf(item, nodes) + const floor = + root.parentId === levelId || !root.parentId + ? floorUnder( + root, + { + position: [root.position[0], 0, root.position[2]], + dimensions: getScaledDimensions(root), + rotation: root.rotation, + }, + nodes, + levelId, + supportCache, + ) + : 0 + place = { + origin: [x, z, baseY + floor + y], + // `yawDeg` is the sum of the hosts' `rotation[1]`, which is in radians + yaw: pose.yawDeg, + plan: (px, pz) => [px, pz], + } + } + const id = `${item.id}#shape` + const tilted = !flat(item.rotation) || !flat(item.asset.rotation) + const degenerate = [...item.scale, ...(item.asset.scale ?? [1, 1, 1])].some((v) => v === 0) + const prisms = + tilted || degenerate ? tiltedPrism(item, place, id) : bandPrisms(item, local, place, id) + return { shapes: { itemId: item.id, levelId, prisms } } + } catch (error) { + return { + skipped: { nodeId: item.id, why: error instanceof Error ? error.message : String(error) }, + } + } +} + +/** + * Every item as prisms in absolute building metres, filed under its level. An item stands on the + * floor under it, on the item that hosts it, or on a wall; one hosted by a ceiling, a roof or a block + * is counted in `unshaped`. Its outline is its script's stored shape when it has one, else a box. + */ +export function itemBodies(nodes: Nodes): { + items: ItemShapes[] + skipped: Skipped[] + unshaped: Record +} { + const items: ItemShapes[] = [] + const skipped: Skipped[] = [] + const unshaped: Record = {} + const context = itemContext(nodes) + for (const node of Object.values(nodes) as AnyNode[]) { + if (node.type !== 'item' || isHidden(node, nodes)) continue + const shaped = itemShapesOf(node, context) + if ('shapes' in shaped) items.push(shaped.shapes) + else if ('skipped' in shaped) skipped.push(shaped.skipped) + else unshaped[shaped.unshaped] = (unshaped[shaped.unshaped] ?? 0) + 1 + } + return { items, skipped, unshaped } +} + +function rootOf(item: ItemNode, nodes: Nodes): ItemNode { + let root = item + for (let parent = root.parentId ? nodes[root.parentId] : undefined; parent?.type === 'item'; ) { + root = parent + parent = root.parentId ? nodes[root.parentId] : undefined + } + return root +} diff --git a/packages/core/src/spatial/usage-field/labels.ts b/packages/core/src/spatial/usage-field/labels.ts new file mode 100644 index 0000000000..eb191a9ea9 --- /dev/null +++ b/packages/core/src/spatial/usage-field/labels.ts @@ -0,0 +1,19 @@ +import type { AnyNode } from '../../schema' +import type { Nodes } from './walls' + +/** A node's name as a finding says it: its own, its asset's, or its kind and the tail of its id. */ +export function nameOf(nodes: Nodes, id: string): string { + const node = nodes[id] as (AnyNode & { name?: string; asset?: { name?: string } }) | undefined + if (!node) return id + const tail = id.slice(id.indexOf('_') + 1).slice(0, 4) + return String( + node.name ?? node.asset?.name ?? `${node.type[0]!.toUpperCase()}${node.type.slice(1)} ${tail}`, + ) +} + +export const m = (v: number) => v.toFixed(2) +export const cm = (v: number) => `${Math.round(v * 100)} cm` +export const quote = (name: string) => `“${name}”` +export const unique = (ids: (string | undefined)[]) => [ + ...new Set(ids.filter((id): id is string => !!id)), +] diff --git a/packages/core/src/spatial/usage-field/level-field.ts b/packages/core/src/spatial/usage-field/level-field.ts new file mode 100644 index 0000000000..25a62c39da --- /dev/null +++ b/packages/core/src/spatial/usage-field/level-field.ts @@ -0,0 +1,138 @@ +import { BucketIndex, bakeGrid, cellOf, cellX, cellZ, type Grid, makeGrid } from './field' +import { type Aabb, type Band, type Obstacle, obstaclesInBand } from './obstacles' +import type { FloorRegion, Prism, Ring, UsageShapes } from './types' + +/** A body in the height range a person's trunk and legs fill, and in the range a wheelchair's feet and wheels do. */ +export const BODY_BAND = { from: 0.03, to: 2.0 } as const +export const FEET_BAND = { from: 0.03, to: 0.7 } as const + +export type FloorGroup = { + levelId: string + /** Absolute height of the finished floor. */ + y: number + regions: FloorRegion[] + domain: Aabb +} + +/** Regions of one level at one finished height share a field; a step or a porch deck is a group of its own. */ +export function floorGroups(shapes: UsageShapes): FloorGroup[] { + const groups: FloorGroup[] = [] + for (const level of shapes.levels) { + const byHeight = new Map() + for (const region of level.floors) { + const key = Math.round(region.y * 200) / 200 + byHeight.set(key, [...(byHeight.get(key) ?? []), region]) + } + for (const [y, regions] of byHeight) { + let x0 = Number.POSITIVE_INFINITY + let z0 = Number.POSITIVE_INFINITY + let x1 = Number.NEGATIVE_INFINITY + let z1 = Number.NEGATIVE_INFINITY + for (const region of regions) + for (const [x, z] of region.outer) { + x0 = Math.min(x0, x) + x1 = Math.max(x1, x) + z0 = Math.min(z0, z) + z1 = Math.max(z1, z) + } + groups.push({ + levelId: level.levelId, + y, + regions, + domain: [x0 - 0.05, z0 - 0.05, x1 + 0.05, z1 + 0.05], + }) + } + } + return groups +} + +export function inRing(px: number, pz: number, ring: Ring): boolean { + let inside = false + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const a = ring[i]! + const b = ring[j]! + if (a[1] > pz !== b[1] > pz && px < ((b[0] - a[0]) * (pz - a[1])) / (b[1] - a[1]) + a[0]) + inside = !inside + } + return inside +} + +export const inRegion = (px: number, pz: number, region: Pick) => + inRing(px, pz, region.outer) && !region.holes.some((hole) => inRing(px, pz, hole)) + +/** The cells whose centre lies in any of the rings (holes excluded), as a 0/1 mask. */ +export function maskOf(g: Grid, regions: Pick[]): Uint8Array { + const mask = new Uint8Array(g.W * g.H) + for (const region of regions) { + let x0 = Number.POSITIVE_INFINITY + let z0 = Number.POSITIVE_INFINITY + let x1 = Number.NEGATIVE_INFINITY + let z1 = Number.NEGATIVE_INFINITY + for (const [x, z] of region.outer) { + x0 = Math.min(x0, x) + x1 = Math.max(x1, x) + z0 = Math.min(z0, z) + z1 = Math.max(z1, z) + } + const i0 = Math.max(0, Math.floor((x0 - g.x0) / g.h)) + const i1 = Math.min(g.W - 1, Math.ceil((x1 - g.x0) / g.h)) + const j0 = Math.max(0, Math.floor((z0 - g.z0) / g.h)) + const j1 = Math.min(g.H - 1, Math.ceil((z1 - g.z0) / g.h)) + for (let j = j0; j <= j1; j++) + for (let i = i0; i <= i1; i++) + if (inRegion(cellX(g, i), cellZ(g, j), region)) mask[j * g.W + i] = 1 + } + return mask +} + +export type LevelField = { + group: FloorGroup + band: Band + grid: Grid + /** Signed distance to the nearest obstacle in the band, at every cell centre. */ + F: Float32Array + A: Int32Array + /** 1 where a person can stand on the floor, whatever is on it. */ + floor: Uint8Array + /** 1 where the floor is free: on it, and clear of every obstacle. */ + free: Uint8Array + obstacles: Obstacle[] + index: BucketIndex +} + +/** What a body of a band bumps into above one floor group: every prism of the building meeting it, stairs included. */ +export function buildField( + shapes: UsageShapes, + group: FloorGroup, + range: { from: number; to: number }, + cell: number, + skip?: (prism: Prism) => boolean, + extra: Prism[] = [], +): LevelField { + const band: Band = { z0: group.y + range.from, z1: group.y + range.to } + const obstacles = obstaclesInBand( + [...shapes.levels.flatMap((level) => level.prisms), ...extra], + band, + group.domain, + skip, + ) + const grid = makeGrid(group.domain, cell) + const { F, A } = bakeGrid(grid, obstacles) + const floor = maskOf(grid, group.regions) + const free = new Uint8Array(floor.length) + for (let c = 0; c < free.length; c++) free[c] = floor[c] && F[c]! > 0 ? 1 : 0 + return { + group, + band, + grid, + F, + A, + floor, + free, + obstacles, + index: new BucketIndex(obstacles, group.domain), + } +} + +/** The cell under a plan point, or -1 off the field. */ +export const fieldCell = (field: LevelField, x: number, z: number) => cellOf(field.grid, x, z) diff --git a/packages/core/src/spatial/usage-field/measure.test.ts b/packages/core/src/spatial/usage-field/measure.test.ts new file mode 100644 index 0000000000..3b8121600d --- /dev/null +++ b/packages/core/src/spatial/usage-field/measure.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + DoorNode, + LevelNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../schema' +import { measureUsage } from './measure' +import { usageShapes } from './shapes' +import type { Nodes } from './walls' + +function house(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const wall = ( + id: string, + start: [number, number], + end: [number, number], + children: string[] = [], +) => WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.1, children }) + +const zone = (id: string, name: string, polygon: [number, number][]) => + ZoneNode.parse({ id, parentId: 'level_1', name, polygon }) + +// A 6 x 4 m shell: the front door in the south wall opens into the west room (x < 3), a partition +// at x = 3 with a door leads to the east room. +function twoRooms({ partition = 0.9, front = 1, extra = [] as AnyNode[] } = {}) { + const frontDoor = DoorNode.parse({ + id: 'door_front', + parentId: 'wall_s', + wallId: 'wall_s', + position: [1.5, 1.05, 0], + width: front, + height: 2.1, + frameDepth: 0.07, + }) + const inner = DoorNode.parse({ + id: 'door_inner', + parentId: 'wall_p', + wallId: 'wall_p', + position: [2, 1.05, 0], + width: partition, + height: 2.1, + frameDepth: 0.07, + }) + return house([ + SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + elevation: 0.05, + }), + wall('wall_s', [0, 0], [6, 0], ['door_front']), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + wall('wall_p', [3, 0], [3, 4], ['door_inner']), + frontDoor, + inner, + zone('zone_west', 'West room', [ + [0.05, 0.05], + [2.95, 0.05], + [2.95, 3.95], + [0.05, 3.95], + ]), + zone('zone_east', 'East room', [ + [3.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [3.05, 3.95], + ]), + ...extra, + ]) +} + +const measure = (nodes: Nodes, entranceDoorId = 'door_front') => { + const shapes = usageShapes(nodes) + return measureUsage(nodes, shapes, { cell: 0.02, entranceDoorId }) +} +const room = (m: ReturnType, id: string) => + m.groups[0]!.rooms.find((r) => r.roomId === id)! + +describe('measures of a two-room house', () => { + const m = measure(twoRooms()) + + test('the ground floor is measured from the front door', () => { + expect(m.entranceDoorId).toBe('door_front') + expect(m.groups[0]!.source).toEqual({ kind: 'door', doorId: 'door_front' }) + }) + + test('the passage to the far room is the clear width of the inner door, to the millimetre', () => { + const east = room(m, 'zone_east') + expect(east.reached).toBe(true) + // 0.9 m door, frame members of 0.05 on each side + expect(east.passage!.width).toBeGreaterThan(0.795) + expect(east.passage!.width).toBeLessThan(0.805) + expect(east.passage!.at[0]).toBeCloseTo(3, 1) + expect(east.passage!.fromDoorId).toBe('door_front') + expect(east.passage!.by.map((o) => o.kind).sort()).toEqual(['jamb', 'jamb']) + }) + + test('the room next to the door is limited by the front door itself', () => { + const west = room(m, 'zone_west') + expect(west.passage!.width).toBeGreaterThan(0.895) + expect(west.passage!.width).toBeLessThan(0.905) + }) + + test('a room that is empty has a turning circle as large as it is', () => { + const west = room(m, 'zone_west') + // 2.9 m between the walls; the circle may bulge a little through the open inner doorway + expect(west.turning!.diameter).toBeGreaterThan(2.9) + expect(west.turning!.diameter).toBeLessThan(3.05) + }) + + test('nothing is cut off: no pocket', () => { + for (const r of m.groups[0]!.rooms) expect(r.pocket.isolatedM2).toBe(0) + }) +}) + +describe('the entrance a measure walks from', () => { + const garage = DoorNode.parse({ + id: 'door_garage', + parentId: 'wall_s', + wallId: 'wall_s', + position: [4.5, 1.05, 0], + width: 2, + height: 2.1, + doorCategory: 'garage', + }) + // The garage door is the first node of the scene, so the first door the graph meets. + const withGarage = (children: string[]) => { + const nodes = twoRooms() + return { + door_garage: garage, + ...nodes, + wall_s: { ...nodes.wall_s, children }, + } as Nodes + } + const entrance = (nodes: Nodes) => { + const shapes = usageShapes(nodes) + return measureUsage(nodes, shapes, { cell: 0.05 }).entranceDoorId + } + + test('a street door is the entrance even when a garage door comes first on the wall', () => { + expect(entrance(withGarage(['door_garage', 'door_front']))).toBe('door_front') + }) + + test('a house whose only way in is a garage door is entered through it', () => { + const nodes = withGarage(['door_garage']) + delete nodes.door_front + expect(entrance(nodes)).toBe('door_garage') + }) +}) + +describe('what narrows a room', () => { + test('a narrow inner door narrows the way to the far room and cuts it off from a 0.60 m unit', () => { + const m = measure(twoRooms({ partition: 0.6 })) + const east = room(m, 'zone_east') + expect(east.passage!.width).toBeGreaterThan(0.495) + expect(east.passage!.width).toBeLessThan(0.505) + // a unit fits in the east room (clearance 0.30) and cannot get through a 0.50 m doorway + expect(east.pocket.whole).toBe(true) + // the floor 0.30 m or more from every wall: (2.9 - 0.6) x (3.9 - 0.6) + expect(east.pocket.isolatedM2).toBeGreaterThan(7.5) + expect(east.pocket.isolatedM2).toBeLessThan(7.7) + }) +}) diff --git a/packages/core/src/spatial/usage-field/measure.ts b/packages/core/src/spatial/usage-field/measure.ts new file mode 100644 index 0000000000..1097ddd465 --- /dev/null +++ b/packages/core/src/spatial/usage-field/measure.ts @@ -0,0 +1,576 @@ +import { + buildCirculationGraph, + exteriorEntranceEdges, +} from '../../agent-operations/circulation-graph' +import { floorsOf } from '../../agent-operations/circulation-spaces' +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { area, difference, union } from '../../lib/polygon-boolean' +import { polygonInteriorPoint } from '../../lib/polygon-label' +import type { AnyNode, DoorNode, ItemNode, WallNode } from '../../schema' +import { resolveStairWalkingSurfaces } from '../../systems/stair/stair-clearance' +import { cellX, cellZ, type Grid } from './field' +import { + BODY_BAND, + buildField, + FEET_BAND, + type FloorGroup, + floorGroups, + inRegion, + maskOf, +} from './level-field' +import { + boundingObstacles, + nearestNodes, + type Obstacle, + obstacleOf, + passagePair, + signedDistance, +} from './obstacles' +import { doorwayRing } from './openings' +import { pathTo, refinePassage, travel, type WindowCache, widestPath } from './path' +import type { Prism, Ring, UsageShapes } from './types' +import type { Nodes } from './walls' + +/** A person's trunk needs 0.45 m either side only in the loosest reading; the unit of passage is 0.60 m, so a clearance of 0.30 m. */ +export const UNIT_CLEARANCE_M = 0.3 +/** A cell with less of its room on the floor than this is not a room (an outdoor zone beside the house). */ +const MIN_INDOOR_SHARE = 0.25 + +export type ObstacleRef = { + nodeId: string + kind: Prism['kind'] + shape: Prism['shape'] + why?: string +} + +const refOf = (o: Obstacle): ObstacleRef => ({ + nodeId: o.prism.nodeId, + kind: o.prism.kind, + shape: o.prism.shape, + ...(o.prism.why ? { why: o.prism.why } : {}), +}) + +export type Passage = { + /** Width of the widest path to the room, refined to the millimetre. */ + width: number + /** What the grid alone said. */ + grid: number + at: [number, number] + /** What bounds the width: the pair whose exact gap it is, or the obstacles a disc of that width touches at the pinch. */ + by: ObstacleRef[] + /** The door the path starts at (ground floor), or null from a stair arrival. */ + fromDoorId: string | null +} + +export type RoomMeasure = { + roomId: string + levelId: string + name: string + kind: 'room' | 'stair-foot' + /** A point inside the room, for the finding's place. */ + at: [number, number] + /** False when no way from the entrance reaches it. */ + reached: boolean + passage: Passage | null + /** The same room measured from the best other exterior door, when that is wider. */ + alternative: { doorId: string; width: number } | null + /** Largest clear circle in the feet band, as a diameter. */ + turning: { diameter: number; at: [number, number]; approximate: boolean } | null + /** Floor where a unit of passage fits but cannot get out. */ + pocket: { + isolatedM2: number + freeM2: number + whole: boolean + at: [number, number] | null + /** The two nearest things around it. */ + by: ObstacleRef[] + } +} + +export type GroupMeasure = { + levelId: string + y: number + source: { kind: 'door' | 'stair-arrival' | 'none'; doorId: string | null } + rooms: RoomMeasure[] +} + +export type UsageMeasure = { + groups: GroupMeasure[] + /** The entrance the ground floor was measured from. */ + entranceDoorId: string | null +} + +export type MeasureOptions = { + /** Grid step of the clearance field, metres. 2 cm for checks, 5 cm for the editor. */ + cell?: number + entranceDoorId?: string +} + +const round = (v: number) => Math.round(v * 1000) / 1000 + +function exteriorDoors(nodes: Nodes): string[] { + try { + const graph = buildCirculationGraph(nodes) + return [ + ...new Set( + exteriorEntranceEdges(graph).flatMap((edge) => + (edge.kind === 'door' || edge.kind === 'opening') && edge.sourceId ? [edge.sourceId] : [], + ), + ), + ] + } catch { + return [] + } +} + +function chosenEntrance(nodes: Nodes, exterior: string[], given?: string): string | null { + if (given) return given + const street = exterior.find((id) => { + const door = nodes[id] + return door?.type === 'door' && door.doorCategory !== 'garage' + }) + return street ?? exterior[0] ?? null +} + +function doorCells( + nodes: Nodes, + field: { grid: Parameters[0] }, + doorId: string, +): number[] { + const door = nodes[doorId] + if (door?.type !== 'door') return [] + const wall = door.parentId ? nodes[door.parentId] : undefined + if (wall?.type !== 'wall') return [] + const ring = doorwayRing(wall as WallNode, door as DoorNode) + if (!ring) return [] + const mask = maskOf(field.grid, [{ outer: ring, holes: [] }]) + const cells: number[] = [] + for (let c = 0; c < mask.length; c++) if (mask[c]) cells.push(c) + return cells +} + +/** + * The stairs that end at this floor: the ring of the top tread, which is the way in from below, and + * those of every tread, whose plan is the stairwell opening they climb through. + */ +function arrivals(nodes: Nodes, group: FloorGroup): { top: Ring[]; all: Ring[] } { + const top: Ring[] = [] + const all: Ring[] = [] + for (const node of Object.values(nodes) as AnyNode[]) { + if (node.type !== 'stair') continue + try { + const surfaces = resolveStairWalkingSurfaces(node, nodes) + if (!surfaces.some((surface) => Math.abs(surface.top - group.y) < 0.06)) continue + for (const surface of surfaces) { + all.push(surface.region.outer) + if (Math.abs(surface.top - group.y) < 0.06) top.push(surface.region.outer) + } + } catch { + // a stair the resolver refuses gives no arrival + } + } + return { top, all } +} + +/** A convex ring pushed out by `d` on every side (mitred). */ +function grow(ring: Ring, d: number): Ring { + const n = ring.length + let turn = 0 + for (let i = 0; i < n; i++) { + const a = ring[i]! + const b = ring[(i + 1) % n]! + turn += a[0] * b[1] - b[0] * a[1] + } + const sign = turn >= 0 ? 1 : -1 + const lines = ring.map((a, i) => { + const b = ring[(i + 1) % n]! + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1 + const nx = (sign * (b[1] - a[1])) / length + const nz = (-sign * (b[0] - a[0])) / length + return { + p: [a[0] + nx * d, a[1] + nz * d] as [number, number], + u: [(b[0] - a[0]) / length, (b[1] - a[1]) / length] as [number, number], + } + }) + return lines.map((line, i) => { + const prev = lines[(i + n - 1) % n]! + const det = prev.u[0] * line.u[1] - prev.u[1] * line.u[0] + if (Math.abs(det) < 1e-9) return line.p + const t = ((line.p[0] - prev.p[0]) * line.u[1] - (line.p[1] - prev.p[1]) * line.u[0]) / det + return [prev.p[0] + prev.u[0] * t, prev.p[1] + prev.u[1] * t] as [number, number] + }) +} + +/** + * The openings in the floor as obstacles, less the stair that climbs through them and the slot + * around it (stepped over), and the slits too narrow to put a foot in: nobody walks into a hole, and + * the clearance beside one is what is left of the floor. + */ +function voidPrisms(group: FloorGroup, stair: Ring[]): Prism[] { + const holes = group.regions.flatMap((region) => region.holes) + if (holes.length === 0) return [] + const grownStair = + stair.length > 0 + ? union(stair.map((ring) => ({ outer: grow(ring, STAIRWELL_SLOT_M), holes: [] }))) + : [] + const out: Prism[] = [] + for (const [index, hole] of holes.entries()) { + const pieces = grownStair.length + ? difference({ outer: hole, holes: [] }, grownStair) + : [{ outer: hole, holes: [] as Ring[] }] + for (const [k, piece] of pieces.entries()) { + // a slit in the floor (a room boundary's rounding, a gap between two slabs) is stepped over, as the slot round a stair is + if (slitWidth(piece.outer, area([piece])) < STAIRWELL_SLOT_M) continue + out.push({ + id: `${group.levelId}#void.${index}.${k}`, + nodeId: group.regions[0]!.nodeId, + kind: 'void', + z0: group.y - 1, + z1: group.y + 4, + outer: piece.outer, + holes: piece.holes, + shape: 'exact', + }) + } + } + return out +} + +/** The short side of the rectangle that has the ring's area and perimeter: a slit's width, whatever angle it runs at. */ +function slitWidth(ring: Ring, size: number): number { + let perimeter = 0 + for (const [i, a] of ring.entries()) { + const b = ring[(i + 1) % ring.length]! + perimeter += Math.hypot(b[0] - a[0], b[1] - a[1]) + } + const half = perimeter / 2 + return (half - Math.sqrt(Math.max(0, half * half - 4 * size))) / 2 +} + +/** A slot of the floor narrower than this (between a stair and its opening in the slab, or a slit in the slab) is stepped over, not a void. */ +const STAIRWELL_SLOT_M = 0.15 + +/** The cells within `margin` of any of the rings. */ +function within(grid: Grid, rings: Ring[], margin: number): Uint8Array { + const mask = new Uint8Array(grid.W * grid.H) + for (const ring of rings) { + const edges = obstacleOf({ outer: ring, holes: [] } as unknown as Prism, 0).edges + let x0 = Number.POSITIVE_INFINITY + let z0 = Number.POSITIVE_INFINITY + let x1 = Number.NEGATIVE_INFINITY + let z1 = Number.NEGATIVE_INFINITY + for (const [x, z] of ring) { + x0 = Math.min(x0, x) + x1 = Math.max(x1, x) + z0 = Math.min(z0, z) + z1 = Math.max(z1, z) + } + const i0 = Math.max(0, Math.floor((x0 - margin - grid.x0) / grid.h)) + const i1 = Math.min(grid.W - 1, Math.ceil((x1 + margin - grid.x0) / grid.h)) + const j0 = Math.max(0, Math.floor((z0 - margin - grid.z0) / grid.h)) + const j1 = Math.min(grid.H - 1, Math.ceil((z1 + margin - grid.z0) / grid.h)) + for (let j = j0; j <= j1; j++) + for (let i = i0; i <= i1; i++) + if (signedDistance(edges, cellX(grid, i), cellZ(grid, j)) <= margin) + mask[j * grid.W + i] = 1 + } + return mask +} + +/** The 0.70 m strip in front of the first riser of every stair that climbs from this floor. */ +function stairFeet(nodes: Nodes, group: FloorGroup): { id: string; name: string; ring: Ring }[] { + const out: { id: string; name: string; ring: Ring }[] = [] + for (const node of Object.values(nodes) as AnyNode[]) { + if (node.type !== 'stair' || !node.toLevelId) continue + try { + const first = resolveStairWalkingSurfaces(node, nodes)[0] + if (!first || Math.abs(first.approach - group.y) > 0.06) continue + const [[ax, , az], [bx, , bz]] = first.walkingLine + const length = Math.hypot(bx - ax, bz - az) + if (length < 1e-6) continue + const dx = (bx - ax) / length + const dz = (bz - az) / length + const [p0, p1] = first.region.outer + if (!(p0 && p1)) continue + out.push({ + id: `foot|${node.id}`, + name: `Foot of ${node.name ?? node.id}`, + ring: [p0, p1, [p1[0] - dx * 0.7, p1[1] - dz * 0.7], [p0[0] - dx * 0.7, p0[1] - dz * 0.7]], + }) + } catch { + // see arrivals + } + } + return out +} + +/** The field and the floor a person can walk on, for one floor group: shared by the usage measures and the flow's widths. */ +export function prepareGroup( + nodes: Nodes, + shapes: UsageShapes, + group: FloorGroup, + cell: number, + underlay: (prism: Prism) => boolean, +) { + const arrival = arrivals(nodes, group) + const body = buildField(shapes, group, BODY_BAND, cell, underlay, voidPrisms(group, arrival.all)) + const feet = buildField(shapes, group, FEET_BAND, cell, underlay, voidPrisms(group, arrival.top)) + const { grid } = body + const arrivalCells = new Set() + const arrivalMask = maskOf( + grid, + arrival.top.map((ring) => ({ outer: ring, holes: [] })), + ) + for (let c = 0; c < arrivalMask.length; c++) if (arrivalMask[c]) arrivalCells.add(c) + // the plate a person walks on: the floor, an arriving stair and the slot around it, and every doorway + const plate = Uint8Array.from(body.floor) + for (const c of arrivalCells) plate[c] = 1 + const stairwell = within(grid, arrival.all, STAIRWELL_SLOT_M) + for (let c = 0; c < stairwell.length; c++) if (stairwell[c]) plate[c] = 1 + // the stair itself is the way in, not part of any room it climbs through + const stairMask = maskOf( + grid, + arrival.all.map((ring) => ({ outer: ring, holes: [] })), + ) + const doorsHere = (Object.values(nodes) as AnyNode[]).filter( + (n): n is DoorNode => n.type === 'door' && nodes[n.parentId ?? '']?.parentId === group.levelId, + ) + for (const door of doorsHere) for (const c of doorCells(nodes, body, door.id)) plate[c] = 1 + return { arrival, body, feet, grid, arrivalCells, plate, stairMask, doorsHere } +} + +/** + * The widest-path, turning-circle and evacuation measures of every floor of the building, from the + * shapes `usageShapes` read. The floor is a cell grid of the clearance to the nearest obstacle in a + * band a body stands in; a passage is the widest path from the entrance to the room, its pinch + * re-solved on a finer grid to the millimetre; a pocket is floor where a 0.60 m unit fits but + * cannot get out. + */ +export function measureUsage( + nodes: Nodes, + shapes: UsageShapes, + options: MeasureOptions = {}, +): UsageMeasure { + const cell = options.cell ?? 0.02 + const floors = floorsOf(nodes).floors + const exterior = exteriorDoors(nodes) + const entrance = chosenEntrance(nodes, exterior, options.entranceDoorId) + const underlay = (prism: Prism) => { + const node = nodes[prism.nodeId] + return node?.type === 'item' && isFloorUnderlay(node as ItemNode) + } + const groups: GroupMeasure[] = [] + const allGroups = floorGroups(shapes) + for (const group of allGroups) { + const floor = floors.find((f) => f.id === group.levelId) + if (!floor) continue + const { arrival, body, feet, grid, arrivalCells, plate, stairMask, doorsHere } = prepareGroup( + nodes, + shapes, + group, + cell, + underlay, + ) + + // sources: the entrance's doorway on the ground floor, the arriving stair above + const exteriorHere = exterior.filter((id) => doorsHere.some((d) => d.id === id)) + const useDoors = floor.ground && exteriorHere.length > 0 + const fromDoor = useDoors + ? entrance && exteriorHere.includes(entrance) + ? entrance + : exteriorHere[0]! + : null + const sourceCells = useDoors + ? doorCells(nodes, body, fromDoor!).filter((c) => body.F[c]! > 0) + : [...arrivalCells].filter((c) => body.F[c]! > 0) + const source: GroupMeasure['source'] = sourceCells.length + ? useDoors + ? { kind: 'door', doorId: fromDoor } + : { kind: 'stair-arrival', doorId: null } + : { kind: 'none', doorId: null } + + // rooms of this floor: zones whose interior point lies on it and that are mostly floor + const targets: { + id: string + name: string + kind: RoomMeasure['kind'] + rings: Ring[] + cells: number[] + at: [number, number] + }[] = [] + for (const zone of floor.zones) { + if (zone.outdoor) continue + const probe = polygonInteriorPoint({ polygon: zone.polygon, holes: zone.holes }, true) + if (!group.regions.some((region) => inRegion(probe[0], probe[1], region))) continue + const mask = maskOf(grid, [{ outer: zone.polygon, holes: zone.holes }]) + const cells: number[] = [] + let all = 0 + for (let c = 0; c < mask.length; c++) + if (mask[c]) { + all++ + if (plate[c] && !stairMask[c]) cells.push(c) + } + if (all === 0 || cells.length < MIN_INDOOR_SHARE * all) continue + targets.push({ + id: zone.id, + name: String(nodes[zone.id]?.name ?? zone.id), + kind: 'room', + rings: [zone.polygon, ...zone.holes], + cells, + at: probe, + }) + } + for (const foot of stairFeet(nodes, group)) { + const mask = maskOf(grid, [{ outer: foot.ring, holes: [] }]) + const cells: number[] = [] + for (let c = 0; c < mask.length; c++) if (mask[c] && body.F[c]! > 0) cells.push(c) + if (cells.length) + targets.push({ + id: foot.id, + name: foot.name, + kind: 'stair-foot', + rings: [foot.ring], + cells, + at: [cellX(grid, cells[0]! % grid.W), cellZ(grid, (cells[0]! / grid.W) | 0)], + }) + } + + // widest path from the source (and from every other exterior door, for the alternative) + const sourceSet = new Set(sourceCells) + const widest = sourceCells.length ? widestPath(grid, body.F, plate, sourceCells) : null + const others = useDoors + ? exteriorHere + .filter((id) => id !== fromDoor) + .map((id) => ({ id, cells: doorCells(nodes, body, id).filter((c) => body.F[c]! > 0) })) + .filter((o) => o.cells.length) + .map((o) => ({ ...o, widest: widestPath(grid, body.F, plate, o.cells) })) + : [] + + // evacuation: where a 0.60 m unit fits, reached from the exits + const pass = new Uint8Array(plate.length) + for (let c = 0; c < pass.length; c++) + pass[c] = plate[c] && body.F[c]! >= UNIT_CLEARANCE_M ? 1 : 0 + const exitCells = useDoors + ? exteriorHere.flatMap((id) => doorCells(nodes, body, id)) + : [...arrivalCells] + for (const c of exitCells) pass[c] = body.F[c]! > 0 ? 1 : 0 + const reach = travel(grid, pass, exitCells) + + const windows: WindowCache = new Map() + const rooms: RoomMeasure[] = targets.map((room) => { + // best target cell by bottleneck + let best = -1 + if (widest) + for (const c of room.cells) + if ( + widest.B[c]! > Number.NEGATIVE_INFINITY && + (best < 0 || widest.B[c]! > widest.B[best]!) + ) + best = c + const inRoom = (x: number, z: number) => + room.rings.length > 0 && + inRegion(x, z, { outer: room.rings[0]!, holes: room.rings.slice(1) }) + let passage: Passage | null = null + if (widest && best >= 0) { + const path = pathTo(widest.P, body.F, best) + const refined = refinePassage( + grid, + body.F, + body.index, + path, + (c) => sourceSet.has(c), + inRoom, + ) + const grided = 2 * body.F[path.cells[path.narrowest]!]! + const pair = passagePair(body.obstacles, refined.at[0], refined.at[1]) + // the pinch is two outlines: when the pair found at the refined spot agrees with it, their exact gap is the width + const exact = pair !== null && Math.abs(pair.width - refined.width) < 0.02 + const width = exact ? pair.width : Math.min(refined.width, grided + 2 * grid.h) + passage = { + width: round(width), + grid: round(grided), + at: [round(refined.at[0]), round(refined.at[1])], + by: (exact + ? [pair.a, pair.b] + : boundingObstacles(body.obstacles, refined.at[0], refined.at[1], width / 2) + ).map(refOf), + fromDoorId: fromDoor, + } + } + // the best other exterior door, when it reaches this room more widely + let alternative: RoomMeasure['alternative'] = null + if (passage) + for (const other of others) { + let b = Number.NEGATIVE_INFINITY + for (const c of room.cells) b = Math.max(b, other.widest.B[c]!) + if (2 * b > passage.width + 0.01 && (!alternative || 2 * b > alternative.width)) + alternative = { doorId: other.id, width: round(2 * b) } + } + // turning circle: the largest clear circle, found on the grid and then on a 5 mm lattice + let turning: RoomMeasure['turning'] = null + let mf = Number.NEGATIVE_INFINITY + let mc = -1 + for (const c of room.cells) + if (feet.F[c]! > mf) { + mf = feet.F[c]! + mc = c + } + if (mc >= 0 && room.kind === 'room') { + let bestD = mf + let bat: [number, number] = [cellX(grid, mc % grid.W), cellZ(grid, (mc / grid.W) | 0)] + const [cx, cz] = bat + for (let dz = -0.05; dz <= 0.05001; dz += 0.005) + for (let dx = -0.05; dx <= 0.05001; dx += 0.005) { + if (!inRoom(cx + dx, cz + dz)) continue + const d = feet.index.query(cx + dx, cz + dz).d + if (d > bestD) { + bestD = d + bat = [cx + dx, cz + dz] + } + } + const owner = feet.obstacles[feet.index.query(bat[0], bat[1]).arg] + turning = { + diameter: round(2 * bestD), + at: [round(bat[0]), round(bat[1])], + approximate: owner?.prism.shape === 'approx', + } + } + // pocket: a unit fits, and cannot get out + let free = 0 + let isolated = 0 + let sx = 0 + let sz = 0 + for (const c of room.cells) { + if (!pass[c]) continue + free++ + if (!Number.isFinite(reach[c]!)) { + isolated++ + sx += cellX(grid, c % grid.W) + sz += cellZ(grid, (c / grid.W) | 0) + } + } + return { + roomId: room.id, + levelId: group.levelId, + name: room.name, + kind: room.kind, + at: room.at, + reached: passage !== null, + passage, + alternative, + turning, + pocket: { + isolatedM2: round(isolated * grid.h * grid.h), + freeM2: round(free * grid.h * grid.h), + whole: free > 0 && isolated === free, + at: isolated ? [round(sx / isolated), round(sz / isolated)] : null, + by: isolated + ? nearestNodes(body.obstacles, sx / isolated, sz / isolated, 2).map(refOf) + : [], + }, + } + }) + groups.push({ levelId: group.levelId, y: group.y, source, rooms }) + } + return { groups, entranceDoorId: entrance } +} diff --git a/packages/core/src/spatial/usage-field/obstacles.ts b/packages/core/src/spatial/usage-field/obstacles.ts new file mode 100644 index 0000000000..0c2ef3f91c --- /dev/null +++ b/packages/core/src/spatial/usage-field/obstacles.ts @@ -0,0 +1,275 @@ +import { boxesMeet } from './pieces' +import type { Prism } from './types' + +/** [x0, z0, x1, z1] */ +export type Aabb = [number, number, number, number] + +/** + * A prism seen from above for a body in one height band: its rings as a flat edge list (outer and + * holes, even-odd), so the signed distance to it is the distance to the nearest edge, negative + * inside. + */ +export type Obstacle = { + index: number + prism: Prism + /** a.x, a.z, b.x, b.z for every edge. */ + edges: Float64Array + aabb: Aabb +} + +export function obstacleOf(prism: Prism, index: number): Obstacle { + const rings = [prism.outer, ...prism.holes] + let n = 0 + for (const ring of rings) n += ring.length + const edges = new Float64Array(n * 4) + let k = 0 + let x0 = Number.POSITIVE_INFINITY + let z0 = Number.POSITIVE_INFINITY + let x1 = Number.NEGATIVE_INFINITY + let z1 = Number.NEGATIVE_INFINITY + for (const ring of rings) + for (let i = 0; i < ring.length; i++) { + const a = ring[i]! + const b = ring[(i + 1) % ring.length]! + edges[k++] = a[0] + edges[k++] = a[1] + edges[k++] = b[0] + edges[k++] = b[1] + x0 = Math.min(x0, a[0]) + x1 = Math.max(x1, a[0]) + z0 = Math.min(z0, a[1]) + z1 = Math.max(z1, a[1]) + } + return { index, prism, edges, aabb: [x0, z0, x1, z1] } +} + +/** Signed distance to a set of rings given as flat edges: exact, negative inside (even-odd). */ +export function signedDistance(edges: Float64Array, px: number, pz: number): number { + let d2 = Number.POSITIVE_INFINITY + let inside = false + for (let k = 0; k < edges.length; k += 4) { + const ax = edges[k]! + const az = edges[k + 1]! + const bx = edges[k + 2]! + const bz = edges[k + 3]! + const ex = bx - ax + const ez = bz - az + const wx = px - ax + const wz = pz - az + const length2 = ex * ex + ez * ez + let t = length2 > 0 ? (wx * ex + wz * ez) / length2 : 0 + t = Math.min(1, Math.max(0, t)) + const dx = wx - ex * t + const dz = wz - ez * t + const q = dx * dx + dz * dz + if (q < d2) d2 = q + if (az > pz !== bz > pz && px < ax + ((pz - az) * ex) / ez) inside = !inside + } + const d = Math.sqrt(d2) + return inside ? -d : d +} + +export const obstacleDistance = (o: Obstacle, px: number, pz: number) => + signedDistance(o.edges, px, pz) + +/** The closest point of an obstacle's edges to a point, and how far. */ +export function closestOnEdges( + edges: Float64Array, + px: number, + pz: number, +): { x: number; z: number; d: number } { + let d2 = Number.POSITIVE_INFINITY + let cx = 0 + let cz = 0 + for (let k = 0; k < edges.length; k += 4) { + const ax = edges[k]! + const az = edges[k + 1]! + const ex = edges[k + 2]! - ax + const ez = edges[k + 3]! - az + const length2 = ex * ex + ez * ez + let t = length2 > 0 ? ((px - ax) * ex + (pz - az) * ez) / length2 : 0 + t = Math.min(1, Math.max(0, t)) + const qx = ax + ex * t + const qz = az + ez * t + const q = (px - qx) ** 2 + (pz - qz) ** 2 + if (q < d2) { + d2 = q + cx = qx + cz = qz + } + } + return { x: cx, z: cz, d: Math.sqrt(d2) } +} + +export type Band = { z0: number; z1: number } + +/** + * The prisms a body standing in the band bumps into: those whose height range meets it, within + * the plan window if one is given. A prism that only touches the band's edge does not count. + */ +export function obstaclesInBand( + prisms: Iterable, + band: Band, + window?: Aabb, + skip?: (prism: Prism) => boolean, +): Obstacle[] { + const out: Obstacle[] = [] + for (const prism of prisms) { + if (!(prism.z1 > band.z0 + 1e-6 && prism.z0 < band.z1 - 1e-6)) continue + if (skip?.(prism)) continue + const obstacle = obstacleOf(prism, out.length) + if (window) { + const [a0, b0, a1, b1] = obstacle.aabb + if (a1 < window[0] || a0 > window[2] || b1 < window[1] || b0 > window[3]) continue + } + out.push(obstacle) + } + return out +} + +/** How far a ray from a point goes before it meets an obstacle's outline, at most `max`. */ +export function rayHit( + from: [number, number], + dir: [number, number], + obstacles: readonly Obstacle[], + max: number, +): number { + let best = max + const ex = from[0] + dir[0] * max + const ez = from[1] + dir[1] * max + const box = [ + Math.min(from[0], ex), + Math.min(from[1], ez), + Math.max(from[0], ex), + Math.max(from[1], ez), + ] + for (const o of obstacles) { + if (!boxesMeet(box, o.aabb)) continue + for (let k = 0; k < o.edges.length; k += 4) { + const ax = o.edges[k]! + const az = o.edges[k + 1]! + const sx = o.edges[k + 2]! - ax + const sz = o.edges[k + 3]! - az + const den = dir[0] * sz - dir[1] * sx + if (Math.abs(den) < 1e-12) continue + const t = ((ax - from[0]) * sz - (az - from[1]) * sx) / den + const u = ((ax - from[0]) * dir[1] - (az - from[1]) * dir[0]) / den + if (t >= 0 && t < best && u >= 0 && u <= 1) best = t + } + } + return best +} + +/** The exact distance between two obstacles' outlines (0 when they touch or overlap) and the two closest points. */ +export function obstacleGap( + a: Obstacle, + b: Obstacle, +): { d: number; pa: [number, number]; pb: [number, number] } { + if ( + signedDistance(a.edges, b.edges[0]!, b.edges[1]!) <= 0 || + signedDistance(b.edges, a.edges[0]!, a.edges[1]!) <= 0 + ) + return { d: 0, pa: [b.edges[0]!, b.edges[1]!], pb: [b.edges[0]!, b.edges[1]!] } + let best = Number.POSITIVE_INFINITY + let pa: [number, number] = [0, 0] + let pb: [number, number] = [0, 0] + for (const [from, to, swapped] of [ + [a, b, false], + [b, a, true], + ] as const) + for (let k = 0; k < from.edges.length; k += 4) { + const closest = closestOnEdges(to.edges, from.edges[k]!, from.edges[k + 1]!) + if (closest.d < best) { + best = closest.d + const here: [number, number] = [from.edges[k]!, from.edges[k + 1]!] + const there: [number, number] = [closest.x, closest.z] + pa = swapped ? there : here + pb = swapped ? here : there + } + } + return { d: best, pa, pb } +} + +/** + * The two obstacles that make the passage at a point: the nearest one, and the nearest one whose + * closest point lies on the other side of the point. The passage is their exact distance, whatever + * the grid said. + */ +export function passagePair( + obstacles: Obstacle[], + px: number, + pz: number, + reach = 1.5, +): { width: number; a: Obstacle; b: Obstacle; pa: [number, number]; pb: [number, number] } | null { + const near = obstacles + .filter( + (o) => + o.aabb[0] - reach <= px && + px <= o.aabb[2] + reach && + o.aabb[1] - reach <= pz && + pz <= o.aabb[3] + reach, + ) + .map((o) => ({ o, ...closestOnEdges(o.edges, px, pz) })) + .sort((u, v) => u.d - v.d) + const first = near[0] + if (!first) return null + const second = near.find((n) => (n.x - px) * (first.x - px) + (n.z - pz) * (first.z - pz) < 0) + if (!second) return null + const gap = obstacleGap(first.o, second.o) + return { width: gap.d, a: first.o, b: second.o, pa: gap.pa, pb: gap.pb } +} + +/** + * What bounds a width read at a point: the nearest obstacle a disc of `radius` there touches, to + * within `slack`, and the nearest touching one on the other side of the point, if there is one. + * The nearest obstacle alone when nothing else bounds the disc. + */ +export function boundingObstacles( + obstacles: Obstacle[], + px: number, + pz: number, + radius: number, + slack = 0.03, +): Obstacle[] { + const reach = radius + slack + const touching = nearestNodes(obstacles, px, pz, 6, reach).filter( + (o) => Math.abs(signedDistance(o.edges, px, pz)) <= reach, + ) + const first = touching[0] ?? nearestNodes(obstacles, px, pz, 1)[0] + if (!first) return [] + const at = closestOnEdges(first.edges, px, pz) + const across = touching.find((o) => { + const there = closestOnEdges(o.edges, px, pz) + return (there.x - px) * (at.x - px) + (there.z - pz) * (at.z - pz) < 0 + }) + return across ? [first, across] : [first] +} + +/** The `count` obstacles of different nodes nearest a point, nearest first. */ +export function nearestNodes( + obstacles: Obstacle[], + px: number, + pz: number, + count: number, + reach = 3, +): Obstacle[] { + const seen = new Set() + const out: Obstacle[] = [] + const near = obstacles + .filter( + (o) => + o.aabb[0] - reach <= px && + px <= o.aabb[2] + reach && + o.aabb[1] - reach <= pz && + pz <= o.aabb[3] + reach, + ) + .map((o) => ({ o, d: Math.abs(signedDistance(o.edges, px, pz)) })) + .sort((a, b) => a.d - b.d) + for (const { o } of near) { + if (seen.has(o.prism.nodeId)) continue + seen.add(o.prism.nodeId) + out.push(o) + if (out.length === count) break + } + return out +} diff --git a/packages/core/src/spatial/usage-field/openings.test.ts b/packages/core/src/spatial/usage-field/openings.test.ts new file mode 100644 index 0000000000..042d00a470 --- /dev/null +++ b/packages/core/src/spatial/usage-field/openings.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, BuildingNode, DoorNode, LevelNode, WallNode, WindowNode } from '../../schema' +import { openingBodies } from './openings' +import type { Prism } from './types' +import type { Nodes } from './walls' + +function scene(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const wall = (children: string[]) => + WallNode.parse({ + id: 'wall_1', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + thickness: 0.1, + children, + }) + +const box = (p: Prism) => { + const xs = p.outer.map(([x]) => x) + const zs = p.outer.map(([, z]) => z) + return { x0: Math.min(...xs), x1: Math.max(...xs), z0: Math.min(...zs), z1: Math.max(...zs) } +} + +describe('door frames', () => { + const door = (over: Record = {}) => + DoorNode.parse({ + id: 'door_1', + parentId: 'wall_1', + wallId: 'wall_1', + position: [3, 1.05, 0], + width: 0.9, + height: 2.1, + ...over, + }) + + test('a door is passed between its jambs: the clear width is the width less two frame members', () => { + const prisms = openingBodies(scene([wall(['door_1']), door()]), 'level_1') + const left = prisms.find((p) => p.id.endsWith('#jamb.l'))! + const right = prisms.find((p) => p.id.endsWith('#jamb.r'))! + expect(left.kind).toBe('jamb') + expect(box(left).x1).toBeCloseTo(2.6, 6) + expect(box(right).x0).toBeCloseTo(3.4, 6) + expect(box(right).x0 - box(left).x1).toBeCloseTo(0.9 - 2 * 0.05, 6) + // a frame with no depth of its own is as deep as its wall (0.1), centred on the wall's body + expect(box(left).z0).toBeCloseTo(-0.05, 6) + expect(box(left).z1).toBeCloseTo(0.05, 6) + expect([left.z0, left.z1]).toEqual([0, 2.1]) + expect(left.shape).toBe('exact') + }) + + test('the head and the threshold are the frame members across the opening', () => { + const prisms = openingBodies(scene([wall(['door_1']), door()]), 'level_1') + const head = prisms.find((p) => p.kind === 'door-head')! + expect(head.z0).toBeCloseTo(2.05, 6) + expect(head.z1).toBeCloseTo(2.1, 6) + const threshold = prisms.find((p) => p.kind === 'threshold')! + expect(threshold.z1 - threshold.z0).toBeCloseTo(0.02, 6) + expect(box(threshold).x1 - box(threshold).x0).toBeCloseTo(0.8, 6) + }) + + test('a frameless opening has no frame', () => { + expect( + openingBodies(scene([wall(['door_1']), door({ openingKind: 'opening' })]), 'level_1'), + ).toHaveLength(0) + }) + + test('an arched head leaves the head out and the door approximate', () => { + const prisms = openingBodies( + scene([wall(['door_1']), door({ openingShape: 'arch' })]), + 'level_1', + ) + expect(prisms.some((p) => p.kind === 'door-head')).toBe(false) + expect(prisms.filter((p) => p.kind === 'jamb').every((p) => p.shape === 'approx')).toBe(true) + }) +}) + +describe('window frames and sills', () => { + const win = (over: Record = {}) => + WindowNode.parse({ + id: 'window_1', + parentId: 'wall_1', + wallId: 'wall_1', + position: [3, 1.5, 0], + width: 1.2, + height: 1.2, + ...over, + }) + + test('the frame fills the opening and the sill stands under it on the side the window faces', () => { + const prisms = openingBodies(scene([wall(['window_1']), win()]), 'level_1') + const frame = prisms.find((p) => p.kind === 'window-frame')! + expect([frame.z0, frame.z1]).toEqual([0.9, 2.1]) + expect(box(frame).x1 - box(frame).x0).toBeCloseTo(1.2, 6) + const sill = prisms.find((p) => p.kind === 'sill')! + // the sill's top stands 1 mm over the opening's bottom, as the window builder lifts it + expect(sill.z1).toBeCloseTo(0.9 + 0.001, 6) + expect(sill.z1 - sill.z0).toBeCloseTo(0.03, 6) + expect(box(sill).x1 - box(sill).x0).toBeCloseTo(1.2 + 0.08 * 0.4, 6) + // starts on the wall face (0.05) when the frame runs through the wall, and stands out sillDepth, + // on the +normal side of a window turned 0 + expect(box(sill).z0).toBeCloseTo(0.05, 6) + expect(box(sill).z1).toBeCloseTo(0.13, 6) + expect(sill.host).toEqual({ wallId: 'wall_1', face: 'a' }) + }) + + test('a window turned half a turn has its sill on the other side', () => { + const prisms = openingBodies( + scene([wall(['window_1']), win({ rotation: [0, Math.PI, 0] })]), + 'level_1', + ) + const sill = prisms.find((p) => p.kind === 'sill')! + expect(box(sill).z1).toBeCloseTo(-0.05, 6) + expect(sill.host?.face).toBe('b') + }) + + test('a frame shallower than its wall keeps the sill 2 mm off the wall face', () => { + const prisms = openingBodies(scene([wall(['window_1']), win({ frameDepth: 0.07 })]), 'level_1') + expect(box(prisms.find((p) => p.kind === 'sill')!).z0).toBeCloseTo(0.052, 6) + }) + + test('no sill, no sill prism', () => { + expect( + openingBodies(scene([wall(['window_1']), win({ sill: false })]), 'level_1').some( + (p) => p.kind === 'sill', + ), + ).toBe(false) + }) + + test('a bay window is approximate: its projection is not drawn', () => { + const prisms = openingBodies(scene([wall(['window_1']), win({ windowType: 'bay' })]), 'level_1') + expect(prisms.every((p) => p.shape === 'approx')).toBe(true) + }) +}) diff --git a/packages/core/src/spatial/usage-field/openings.ts b/packages/core/src/spatial/usage-field/openings.ts new file mode 100644 index 0000000000..9578f1b34b --- /dev/null +++ b/packages/core/src/spatial/usage-field/openings.ts @@ -0,0 +1,261 @@ +import { getOpeningFloorDatum } from '../../lib/opening-floor-datum' +import { resolveOpeningFrameDepth } from '../../lib/opening-frame-depth' +import type { AnyNode, DoorNode, WallNode, WindowNode } from '../../schema' +import { + getWallCurveFrameAt, + getWallCurveLength, + isCurvedWall, +} from '../../systems/wall/wall-curve' +import { getWallThickness } from '../../systems/wall/wall-footprint' +import { getWallBodyCenterOffset } from '../../systems/wall/wall-frame' +import type { Prism, Ring } from './types' +import { isOpening, levelWalls, type Nodes } from './walls' + +/** Where an opening stands in plan: its centre, the wall's direction along it and across it. */ +type Pose = { cx: number; cz: number; tx: number; tz: number; nx: number; nz: number } + +function poseOf(wall: WallNode, opening: DoorNode | WindowNode): Pose { + const length = getWallCurveLength(wall) + const frame = getWallCurveFrameAt( + wall, + length > 1e-9 ? Math.min(1, Math.max(0, opening.position[0] / length)) : 0, + ) + const across = getWallBodyCenterOffset(wall) + opening.position[2] + return { + cx: frame.point.x + frame.normal.x * across, + cz: frame.point.y + frame.normal.y * across, + tx: frame.tangent.x, + tz: frame.tangent.y, + nx: frame.normal.x, + nz: frame.normal.y, + } +} + +/** The plan rectangle `u0..u1` along the wall and `a0..a1` across it, from the opening's centre. */ +function rect(pose: Pose, u0: number, u1: number, a0: number, a1: number): Ring { + const at = (u: number, a: number): [number, number] => [ + pose.cx + pose.tx * u + pose.nx * a, + pose.cz + pose.tz * u + pose.nz * a, + ] + return [at(u0, a0), at(u1, a0), at(u1, a1), at(u0, a1)] +} + +type Common = Pick + +/** How far the window builder lifts the sill's top over the opening's bottom (`SILL_LIFT` there). */ +const SILL_LIFT = 0.001 + +function push( + out: Prism[], + id: string, + kind: Prism['kind'], + z0: number, + z1: number, + outer: Ring, + common: Common, +) { + if (z1 - z0 > 1e-4) out.push({ id, kind, z0, z1, outer, holes: [], ...common }) +} + +/** + * A door's frame as the door builder cuts it (`viewer/src/systems/door/door-system.tsx`, "Frame + * members"): two posts of `frameThickness` and a head across the width, `frameDepth` deep, centred + * on the wall's body; a threshold of `thresholdHeight` between the posts. The leaf is not an + * obstacle (a door is passed open). A frameless opening has no frame. The arch and the rounded head + * are left out and the door is marked approximate; a scripted door is its bounds. + */ +function doorFrame(wall: WallNode, door: DoorNode, yc: number, out: Prism[]) { + const pose = poseOf(wall, door) + const half = resolveOpeningFrameDepth(door, getWallThickness(wall)) / 2 + const curved = isCurvedWall(wall) + const common: Common = { + nodeId: door.id, + shape: curved ? 'approx' : 'exact', + ...(curved ? { why: 'a door on a curved wall' } : {}), + } + if (door.source) { + const size = scriptedBounds(door.source.manifest.bounds) + push( + out, + `${door.id}#script`, + 'jamb', + yc - door.height / 2, + yc - door.height / 2 + size.height, + rect(pose, -size.width / 2, size.width / 2, -size.depth / 2, size.depth / 2), + { + nodeId: door.id, + shape: 'approx', + why: 'a scripted door: its bounds box', + }, + ) + return + } + if (door.openingKind === 'opening') return + const w = door.width + const h = door.height + const ft = door.frameThickness + const bottom = yc - h / 2 + const top = yc + h / 2 + const shaped = door.openingShape !== 'rectangle' + const approx: Common = shaped + ? { ...common, shape: 'approx', why: `a ${door.openingShape} head: the posts only` } + : common + const postTop = + door.openingShape === 'arch' + ? Math.max( + top - Math.min(Math.max(door.archHeight, 0), h) - (door.archHeight <= ft * 2 ? ft : 0), + bottom + 0.01, + ) + : top + push( + out, + `${door.id}#jamb.l`, + 'jamb', + bottom, + postTop, + rect(pose, -w / 2, -w / 2 + ft, -half, half), + approx, + ) + push( + out, + `${door.id}#jamb.r`, + 'jamb', + bottom, + postTop, + rect(pose, w / 2 - ft, w / 2, -half, half), + approx, + ) + if (!shaped) + push( + out, + `${door.id}#head`, + 'door-head', + top - ft, + top, + rect(pose, -w / 2, w / 2, -half, half), + common, + ) + if (door.threshold) + push( + out, + `${door.id}#threshold`, + 'threshold', + bottom, + bottom + door.thresholdHeight, + rect(pose, -(w - 2 * ft) / 2, (w - 2 * ft) / 2, -half, half), + common, + ) +} + +function scriptedBounds(bounds: { min: readonly number[]; max: readonly number[] }) { + return { + width: bounds.max[0]! - bounds.min[0]!, + height: bounds.max[1]! - bounds.min[1]!, + depth: bounds.max[2]! - bounds.min[2]!, + } +} + +/** + * A window as the window builder cuts it (`viewer/src/systems/window/window-system.tsx`): the frame + * and its glazing fill the opening, `width × height × frameDepth`, centred on the wall's body; a sill + * box `width + 0.4·sillDepth` wide, `sillThickness` thick, `sillDepth` deep stands under it on the + * side the window faces, starting on the wall face (2 mm off it when the frame is shallower than the wall). A bay or a bow + * projects: only its frame is drawn here and it is marked approximate. */ +function window(wall: WallNode, win: WindowNode, yc: number, out: Prism[]) { + const pose = poseOf(wall, win) + const half = resolveOpeningFrameDepth(win, getWallThickness(wall)) / 2 + const w = win.width + const h = win.height + const curved = isCurvedWall(wall) + const projecting = win.windowType === 'bay' || win.windowType === 'bow' + const why = projecting + ? `a ${win.windowType} window: its projection is not drawn` + : curved + ? 'a window on a curved wall' + : undefined + const common: Common = { + nodeId: win.id, + shape: why ? 'approx' : 'exact', + ...(why ? { why } : {}), + } + if (win.source) { + const size = scriptedBounds(win.source.manifest.bounds) + push( + out, + `${win.id}#script`, + 'window-frame', + yc - h / 2, + yc - h / 2 + size.height, + rect(pose, -size.width / 2, size.width / 2, -size.depth / 2, size.depth / 2), + { + nodeId: win.id, + shape: 'approx', + why: 'a scripted window: its bounds box', + }, + ) + return + } + push( + out, + `${win.id}#frame`, + 'window-frame', + yc - h / 2, + yc + h / 2, + rect(pose, -w / 2, w / 2, -half, half), + common, + ) + if (!win.sill) return + // window-local +z is the wall's normal for a window turned 0, its opposite for one turned half a turn + const side = Math.cos(win.rotation[1]) >= 0 ? 1 : -1 + const faceZ = Math.max( + getWallThickness(wall) / 2 - win.position[2] * Math.cos(win.rotation[1]), + half, + ) + // The builder stands the sill's back on the wall face when the frame runs through the wall, + // and 2 mm off it when the frame is shallower. + const from = faceZ + (faceZ > half ? 0.002 : 0) + const sillW = w + win.sillDepth * 0.4 + const [a0, a1] = side > 0 ? [from, from + win.sillDepth] : [-(from + win.sillDepth), -from] + push( + out, + `${win.id}#sill`, + 'sill', + yc - h / 2 - win.sillThickness + SILL_LIFT, + yc - h / 2 + SILL_LIFT, + rect(pose, -sillW / 2, sillW / 2, a0, a1), + { + ...common, + host: { wallId: wall.id, face: side > 0 ? 'a' : 'b' }, + }, + ) +} + +/** + * The plan rectangle of the hole a door is walked through, across the wall's thickness: the width + * between its frame members, or the whole width for a frameless opening. Null for a scripted door, + * whose frame is not known. + */ +export function doorwayRing(wall: WallNode, door: DoorNode): Ring | null { + if (door.source) return null + const clear = door.openingKind === 'opening' ? door.width : door.width - 2 * door.frameThickness + const half = getWallThickness(wall) / 2 + 0.01 + return rect(poseOf(wall, door), -clear / 2, clear / 2, -half, half) +} + +/** Doors' frames and windows' frames and sills of one level, in level-local heights. */ +export function openingBodies( + nodes: Nodes, + levelId: string, + walls: WallNode[] = levelWalls(nodes, levelId), +): Prism[] { + const out: Prism[] = [] + for (const wall of walls) + for (const id of wall.children ?? []) { + const opening = nodes[id] as AnyNode | undefined + if (!isOpening(opening) || opening.visible === false) continue + const yc = getOpeningFloorDatum(wall, opening, nodes) + opening.position[1] + if (opening.type === 'door') doorFrame(wall, opening, yc, out) + else window(wall, opening, yc, out) + } + return out +} diff --git a/packages/core/src/spatial/usage-field/path.ts b/packages/core/src/spatial/usage-field/path.ts new file mode 100644 index 0000000000..d84bdc828f --- /dev/null +++ b/packages/core/src/spatial/usage-field/path.ts @@ -0,0 +1,396 @@ +import { type BucketIndex, cellOf, cellX, cellZ, type Grid } from './field' + +/** A binary min-heap on a numeric key. */ +class Heap { + private keys: number[] = [] + private values: number[] = [] + + get size() { + return this.keys.length + } + + push(key: number, value: number) { + const keys = this.keys + const values = this.values + let i = keys.length + keys.push(key) + values.push(value) + while (i > 0) { + const parent = (i - 1) >> 1 + if (keys[i]! >= keys[parent]!) break + ;[keys[i], keys[parent]] = [keys[parent]!, keys[i]!] + ;[values[i], values[parent]] = [values[parent]!, values[i]!] + i = parent + } + } + + pop(): [number, number] { + const keys = this.keys + const values = this.values + const top: [number, number] = [keys[0]!, values[0]!] + const lastKey = keys.pop()! + const lastValue = values.pop()! + if (keys.length) { + keys[0] = lastKey + values[0] = lastValue + let i = 0 + for (;;) { + const l = 2 * i + 1 + const r = l + 1 + let m = i + if (l < keys.length && keys[l]! < keys[m]!) m = l + if (r < keys.length && keys[r]! < keys[m]!) m = r + if (m === i) break + ;[keys[i], keys[m]] = [keys[m]!, keys[i]!] + ;[values[i], values[m]] = [values[m]!, values[i]!] + i = m + } + } + return top + } +} + +const FOUR: [number, number][] = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], +] + +/** + * The widest path (maximin) from the source cells over cells where `inside` holds and the clearance + * is positive, 4-neighbour. `B[c]` is the best bottleneck, the least clearance along the widest path + * to `c`; `P[c]` the cell before it. + */ +export function widestPath( + g: Grid, + F: Float32Array, + inside: Uint8Array, + sources: Iterable, +): { B: Float64Array; P: Int32Array } { + const B = new Float64Array(g.W * g.H).fill(Number.NEGATIVE_INFINITY) + const P = new Int32Array(g.W * g.H).fill(-1) + const done = new Uint8Array(g.W * g.H) + const heap = new Heap() + // a max-heap on the bottleneck, as a min-heap on its negative + for (const s of sources) + if (F[s]! > 0 && inside[s]) { + B[s] = F[s]! + heap.push(-F[s]!, s) + } + while (heap.size) { + const [negative, c] = heap.pop() + if (done[c]) continue + done[c] = 1 + const b = -negative + const i = c % g.W + const j = (c / g.W) | 0 + for (const [di, dj] of FOUR) { + const ii = i + di + const jj = j + dj + if (ii < 0 || jj < 0 || ii >= g.W || jj >= g.H) continue + const n = jj * g.W + ii + if (!inside[n] || F[n]! <= 0 || done[n]) continue + const nb = Math.min(b, F[n]!) + if (nb > B[n]!) { + B[n] = nb + P[n] = c + heap.push(-nb, n) + } + } + } + return { B, P } +} + +/** The cells of the widest path from its source to `c`, in order, and the index of its narrowest. */ +export function pathTo( + P: Int32Array, + F: Float32Array, + c: number, +): { cells: number[]; narrowest: number } { + const cells: number[] = [] + for (let k = c; k >= 0; k = P[k]!) cells.push(k) + cells.reverse() + let narrowest = 0 + for (let k = 1; k < cells.length; k++) if (F[cells[k]!]! < F[cells[narrowest]!]!) narrowest = k + return { cells, narrowest } +} + +type Move = { di: number; dj: number; length: number; via: [number, number][] } + +/** The 16 moves of a grid walk; those that cross cells need those cells passable too, so no corner cuts a wall. */ +const MOVES: Move[] = (() => { + const seen = new Set() + const moves: Move[] = [] + const add = (di: number, dj: number) => { + const key = `${di},${dj}` + if (seen.has(key)) return + seen.add(key) + const via: [number, number][] = [] + if (Math.abs(di) === 1 && Math.abs(dj) === 1) via.push([di, 0], [0, dj]) + if (Math.abs(di) === 2) via.push([Math.sign(di), 0], [Math.sign(di), dj]) + if (Math.abs(dj) === 2) via.push([0, Math.sign(dj)], [di, Math.sign(dj)]) + moves.push({ di, dj, length: Math.hypot(di, dj), via }) + } + for (const [a, b] of [ + [1, 0], + [1, 1], + [2, 1], + [1, 2], + ] as const) + for (const sx of [1, -1]) for (const sz of [1, -1]) add(a * sx, b * sz) + add(0, 1) + add(0, -1) + return moves +})() + +/** Grid Dijkstra over the passable cells, 16 neighbours: the travel distance in metres, Infinity where unreached. */ +export function travel(g: Grid, pass: Uint8Array, sources: Iterable): Float64Array { + const D = new Float64Array(g.W * g.H).fill(Number.POSITIVE_INFINITY) + const heap = new Heap() + for (const s of sources) + if (pass[s]) { + D[s] = 0 + heap.push(0, s) + } + while (heap.size) { + const [d, c] = heap.pop() + if (d > D[c]!) continue + const i = c % g.W + const j = (c / g.W) | 0 + for (const m of MOVES) { + const ii = i + m.di + const jj = j + m.dj + if (ii < 0 || jj < 0 || ii >= g.W || jj >= g.H) continue + const n = jj * g.W + ii + if (!pass[n]) continue + let open = true + for (const [vi, vj] of m.via) + if (!pass[(j + vj) * g.W + (i + vi)]) { + open = false + break + } + if (!open) continue + const next = d + m.length * g.h + if (next < D[n]!) { + D[n] = next + heap.push(next, n) + } + } + } + return D +} + +type Window = { + x0: number + z0: number + n: number + step: number + sources: number[] + targets: number[] +} + +/** A fine grid (the coarse step divided by `fine`) of side 2R around path cell `k`, with its source and target cells. */ +function windowAround( + g: Grid, + cells: number[], + k: number, + isSource: (cell: number) => boolean, + isTarget: (x: number, z: number) => boolean, + R: number, + fine: number, +): Window { + const cx = (c: number) => cellX(g, c % g.W) + const cz = (c: number) => cellZ(g, (c / g.W) | 0) + const X = cx(cells[k]!) + const Z = cz(cells[k]!) + const step = g.h / fine + const n = Math.round((2 * R) / step) + const fx = (i: number) => X - R + (i + 0.5) * step + const fz = (j: number) => Z - R + (j + 0.5) * step + const far = (c: number) => Math.hypot(cx(c) - X, cz(c) - Z) > 0.75 * R + let before = -1 + let after = -1 + for (let q = k; q >= 0; q--) + if (far(cells[q]!)) { + before = cells[q]! + break + } + for (let q = k; q < cells.length; q++) + if (far(cells[q]!)) { + after = cells[q]! + break + } + const near = (c: number, i: number, j: number) => + Math.hypot(fx(i) - cx(c), fz(j) - cz(c)) <= g.h / 2 + const sources: number[] = [] + const targets: number[] = [] + for (let j = 0; j < n; j++) + for (let i = 0; i < n; i++) { + const coarse = Math.floor((fz(j) - g.z0) / g.h) * g.W + Math.floor((fx(i) - g.x0) / g.h) + if (before >= 0 ? near(before, i, j) : isSource(coarse)) sources.push(j * n + i) + if (after >= 0 ? near(after, i, j) : isTarget(fx(i), fz(j))) targets.push(j * n + i) + } + return { x0: X - R, z0: Z - R, n, step, sources, targets } +} + +/** + * The widest path inside one window, on the exact clearance of its fine cells: the best bottleneck + * and where it pinches. Only fine cells that could still limit the path are asked exactly; where + * the grid says the clearance is `slack` above the coarse bottleneck, it cannot be the bottleneck. + */ +function solveWindow( + w: Window, + index: BucketIndex, + g: Grid, + F: Float32Array, + limit: number, +): { d: number; at: [number, number] } { + const field = new Float32Array(w.n * w.n) + // a fine cell's coarse cell is off its centre by at most this + const reach = Math.SQRT1_2 * g.h + for (let j = 0; j < w.n; j++) + for (let i = 0; i < w.n; i++) { + const x = w.x0 + (i + 0.5) * w.step + const z = w.z0 + (j + 0.5) * w.step + const coarse = cellOf(g, x, z) + field[j * w.n + i] = + coarse >= 0 && F[coarse]! - reach > limit ? F[coarse]! : index.query(x, z).d + } + const fine = { W: w.n, H: w.n, h: w.step, x0: w.x0, z0: w.z0 } + const { B } = widestPath(fine, field, new Uint8Array(w.n * w.n).fill(1), w.sources) + let best = Number.NEGATIVE_INFINITY + for (const c of w.targets) if (B[c]! > best) best = B[c]! + let at: [number, number] = [w.x0 + w.n * w.step * 0.5, w.z0 + w.n * w.step * 0.5] + let nearest = Number.POSITIVE_INFINITY + for (let c = 0; c < B.length; c++) { + const gap = Math.abs(field[c]! - best) + if (Math.abs(B[c]! - best) < 1e-6 && gap < nearest) { + nearest = gap + at = [w.x0 + ((c % w.n) + 0.5) * w.step, w.z0 + (((c / w.n) | 0) + 0.5) * w.step] + } + } + return { d: best, at } +} + +export type WindowCache = Map + +/** + * The passage along a coarse widest path, to the millimetre. The grid says where the path pinches, + * to within half a cell; this re-solves the widest path on a grid ten times finer, with exact + * clearances, in a window around every path cell that is within one cell of the coarse bottleneck + * (centres at least `spacing` apart), and takes the narrowest result. The passage is twice that + * clearance. + */ +export function refinePassage( + g: Grid, + F: Float32Array, + index: BucketIndex, + path: { cells: number[]; narrowest: number }, + isSource: (cell: number) => boolean, + isTarget: (x: number, z: number) => boolean, + { + R = 0.3, + step = 0.005, + spacing = 0.2, + cache, + roomKey = '', + }: { R?: number; step?: number; spacing?: number; cache?: WindowCache; roomKey?: string } = {}, +): { width: number; at: [number, number]; windows: number } { + const { cells } = path + const coarse = F[cells[path.narrowest]!]! + const threshold = coarse + g.h + const fine = Math.max(1, Math.round(g.h / step)) + const centres: number[] = [] + const at = (k: number): [number, number] => [ + cellX(g, cells[k]! % g.W), + cellZ(g, (cells[k]! / g.W) | 0), + ] + for (let k = 0; k < cells.length; k++) { + if (F[cells[k]!]! > threshold) continue + const [x, z] = at(k) + if (centres.every((m) => Math.hypot(at(m)[0] - x, at(m)[1] - z) > spacing)) centres.push(k) + } + let best: { d: number; at: [number, number] } | null = null + for (const k of centres) { + // a window whose path leaves it the same way for any room is shared between rooms + const [x, z] = at(k) + const leaves = cells + .slice(k) + .some((q) => Math.hypot(cellX(g, q % g.W) - x, cellZ(g, (q / g.W) | 0) - z) > 0.75 * R) + const key = `${cells[k]}${leaves ? '' : `|${roomKey}`}` + let result = cache?.get(key) + if (!result) { + result = solveWindow( + windowAround(g, cells, k, isSource, isTarget, R, fine), + index, + g, + F, + coarse + 2 * g.h, + ) + cache?.set(key, result) + } + if (!best || result.d < best.d) best = result + } + if (!best) { + const c = cells[path.narrowest]! + best = { d: F[c]!, at: [cellX(g, c % g.W), cellZ(g, (c / g.W) | 0)] } + } + return { width: 2 * best.d, at: best.at, windows: centres.length } +} + +const EIGHT: [number, number][] = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, 1], + [1, -1], + [-1, 1], + [-1, -1], +] + +/** + * The shortest way from one cell to another over the passable cells, 8 neighbours, no corner cut + * through a blocked cell (A*). The cells in order, or null when there is no way. + */ +export function shortestRoute( + g: Grid, + pass: Uint8Array, + from: number, + to: number, +): number[] | null { + if (!pass[from] || !pass[to]) return null + const cost = new Float64Array(g.W * g.H).fill(Number.POSITIVE_INFINITY) + const parent = new Int32Array(g.W * g.H).fill(-1) + const tx = to % g.W + const tz = (to / g.W) | 0 + const heuristic = (c: number) => Math.hypot((c % g.W) - tx, ((c / g.W) | 0) - tz) + const heap = new Heap() + cost[from] = 0 + heap.push(heuristic(from), from) + while (heap.size) { + const [, c] = heap.pop() + if (c === to) break + const i = c % g.W + const j = (c / g.W) | 0 + for (const [di, dj] of EIGHT) { + const ii = i + di + const jj = j + dj + if (ii < 0 || jj < 0 || ii >= g.W || jj >= g.H) continue + const n = jj * g.W + ii + if (!pass[n]) continue + if (di !== 0 && dj !== 0 && !(pass[j * g.W + ii] && pass[jj * g.W + i])) continue + const next = cost[c]! + Math.hypot(di, dj) + if (next < cost[n]!) { + cost[n] = next + parent[n] = c + heap.push(next + heuristic(n), n) + } + } + } + if (parent[to]! < 0 && from !== to) return null + const route: number[] = [] + for (let c = to; c >= 0; c = parent[c]!) route.push(c) + return route.reverse() +} diff --git a/packages/core/src/spatial/usage-field/pieces.ts b/packages/core/src/spatial/usage-field/pieces.ts new file mode 100644 index 0000000000..f2aa91e0ad --- /dev/null +++ b/packages/core/src/spatial/usage-field/pieces.ts @@ -0,0 +1,115 @@ +import { containsPoint, type Ring } from '../../lib/polygon-boolean' +import type { AnyNode, ItemNode, ZoneNode } from '../../schema' +import type { Prism } from './types' +import type { Nodes } from './walls' + +/** What a person puts in a room and walks around: items, cabinets, columns, shelves. */ +const PIECE_KINDS = new Set(['item', 'cabinet', 'column', 'shelf']) +export const isPiecePrism = (prism: Prism): boolean => PIECE_KINDS.has(prism.kind) + +/** Foliage is a cloud of leaves: its bounds overlap by design, and it stands in front of walls. */ +const FOLIAGE = /plant|palm|foliage|tree|shrub|hedge|grass|fern|flower|bouquet|vase of|landscape/i +/** Items that are part of the building (trim, soffits, cladding, piers, guards, beams, lights): they meet walls by design. */ +const BUILDING_ELEMENT = + /trim|fascia|soffit|cladding|cornice|surround|portal|railing|balustrade|guard|pier|beam|post\b|column|canopy|pergola|awning|downlight|light/i + +export const textOf = (node: ItemNode) => + `${node.name ?? ''} ${node.asset?.name ?? ''} ${node.asset?.category ?? ''}` + +export const isFoliageItem = (node: ItemNode): boolean => FOLIAGE.test(textOf(node)) + +export const isBuildingElementItem = (node: ItemNode): boolean => + BUILDING_ELEMENT.test(textOf(node)) + +/** What an item is called and filed under, or '' for a node that is not an item (a candidate not in the scene yet is passed as the item itself). */ +export function itemText(nodes: Nodes, nodeId: string): string { + const node = nodes[nodeId] + return node?.type === 'item' ? textOf(node) : '' +} + +export function isFoliage(nodes: Nodes, nodeId: string): boolean { + const node = nodes[nodeId] + return node?.type === 'item' && isFoliageItem(node) +} + +export function isBuildingElement(nodes: Nodes, nodeId: string): boolean { + const node = nodes[nodeId] + return node?.type === 'item' && isBuildingElementItem(node) +} + +export const isBed = (node: AnyNode | undefined): node is ItemNode => + node?.type === 'item' && node.asset?.category === 'bed' + +/** Whether `ancestor` hosts `nodeId`, however many items deep (a lamp on a table on a rug). */ +export function hosts(nodes: Nodes, ancestor: string, nodeId: string): boolean { + let at = nodes[nodeId] as AnyNode | undefined + for (let depth = 0; at && depth < 24; depth++) { + if (at.id === ancestor) return at.id !== nodeId + at = at.parentId ? (nodes[at.parentId] as AnyNode | undefined) : undefined + } + return false +} + +/** The narrowest extent of some polygons, over 36 directions: how deep one shape sits in another. */ +export function narrowestExtent(polygons: readonly { outer: Ring }[]): number { + const points = polygons.flatMap((polygon) => polygon.outer) + if (points.length < 3) return 0 + let narrowest = Number.POSITIVE_INFINITY + for (let k = 0; k < 36; k++) { + const angle = (k * Math.PI) / 36 + const c = Math.cos(angle) + const s = Math.sin(angle) + let low = Number.POSITIVE_INFINITY + let high = Number.NEGATIVE_INFINITY + for (const [x, z] of points) { + const t = x * c + z * s + low = Math.min(low, t) + high = Math.max(high, t) + } + narrowest = Math.min(narrowest, high - low) + } + return narrowest +} + +export const ringBox = (ring: Ring): [number, number, number, number] => { + let x0 = Number.POSITIVE_INFINITY + let z0 = Number.POSITIVE_INFINITY + let x1 = Number.NEGATIVE_INFINITY + let z1 = Number.NEGATIVE_INFINITY + for (const [x, z] of ring) { + x0 = Math.min(x0, x) + z0 = Math.min(z0, z) + x1 = Math.max(x1, x) + z1 = Math.max(z1, z) + } + return [x0, z0, x1, z1] +} + +export const boxesMeet = (a: readonly number[], b: readonly number[], pad = 0): boolean => + !(a[2]! + pad < b[0]! || b[2]! + pad < a[0]! || a[3]! + pad < b[1]! || b[3]! + pad < a[1]!) + +/** The room (zone) of a level that holds a point: the smallest when rooms overlap. */ +export function roomAt( + nodes: Nodes, + levelId: string, + point: [number, number], +): { id: string; name: string } | null { + let best: { id: string; name: string; size: number } | null = null + for (const node of Object.values(nodes)) { + if (node.type !== 'zone' || node.parentId !== levelId) continue + const zone = node as ZoneNode + if ( + !containsPoint([{ outer: zone.polygon as Ring, holes: (zone.holes ?? []) as Ring[] }], point) + ) + continue + const ring = zone.polygon as Ring + const size = Math.abs( + ring.reduce((sum, p, i) => { + const q = ring[(i + 1) % ring.length]! + return sum + (p[0] * q[1] - q[0] * p[1]) + }, 0) / 2, + ) + if (!best || size < best.size) best = { id: zone.id, name: String(zone.name ?? zone.id), size } + } + return best ? { id: best.id, name: best.name } : null +} diff --git a/packages/core/src/spatial/usage-field/protrusion.test.ts b/packages/core/src/spatial/usage-field/protrusion.test.ts new file mode 100644 index 0000000000..8e97a63f62 --- /dev/null +++ b/packages/core/src/spatial/usage-field/protrusion.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + CabinetModuleNode, + CabinetNode, + ItemNode, + LevelNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../schema' +import { usageIssues } from './findings' +import { wallProtrusions } from './protrusion' +import { usageShapes } from './shapes' +import type { Nodes } from './walls' + +const asset = (over: Record = {}) => ({ + id: 'thing', + name: 'Thing', + category: 'kitchen', + thumbnail: '/thumb.webp', + src: '/items/thing/model.glb', + dimensions: [0.85, 0.6, 0.46], + ...over, +}) + +// A 6 x 4 m kitchen; its south wall is along z = 0, the room on the +z side of it. +function kitchen(extra: AnyNode[], wallChildren: string[] = []): Nodes { + const nodes: AnyNode[] = [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), + SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + elevation: 0.05, + }), + WallNode.parse({ + id: 'wall_s', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + thickness: 0.1, + children: wallChildren, + }), + WallNode.parse({ + id: 'wall_e', + parentId: 'level_1', + start: [6, 0], + end: [6, 4], + thickness: 0.1, + }), + WallNode.parse({ + id: 'wall_n', + parentId: 'level_1', + start: [6, 4], + end: [0, 4], + thickness: 0.1, + }), + WallNode.parse({ + id: 'wall_w', + parentId: 'level_1', + start: [0, 4], + end: [0, 0], + thickness: 0.1, + }), + ZoneNode.parse({ + id: 'zone_k', + parentId: 'level_1', + name: 'Kitchen', + polygon: [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ], + }), + ...extra, + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as Nodes +} + +const found = (nodes: Nodes) => wallProtrusions(nodes, usageShapes(nodes)) + +describe('wall objects that stand out', () => { + test('a hung item stands out of the face it is on, from the face, by its depth', () => { + const screen = ItemNode.parse({ + id: 'item_1', + parentId: 'wall_s', + wallId: 'wall_s', + position: [3, 1.4, 0], + side: 'front', + asset: asset({ attachTo: 'wall-side' }), + }) + const [p] = found(kitchen([screen], ['item_1'])) + expect(p!.nodeId).toBe('item_1') + expect(p!.face).toBe('a') + // the library box is centred on its position: half of its 0.46 m is out of the 0.05 face + expect(p!.depth).toBeCloseTo(0.23 + 0, 1) + expect(p!.bottom).toBeCloseTo(1.4 - 0.0, 1) + expect(p!.roomName).toBe('Kitchen') + expect(usageIssues(kitchen([screen], ['item_1']))).toContainEqual( + expect.objectContaining({ + type: 'usage_wall_object_protrudes', + severity: 'warning', + approximate: true, + }), + ) + }) + + test('a wall cabinet run set off its wall protrudes from the face, not from its own back', () => { + const run = CabinetNode.parse({ + id: 'cabinet_1', + parentId: 'level_1', + position: [3, 1.4, 0.3], + runTier: 'wall', + children: ['cabinet-module_1'], + }) + const module = CabinetModuleNode.parse({ + id: 'cabinet-module_1', + parentId: run.id, + position: [0, 0, 0], + width: 0.85, + depth: 0.32, + }) + const [p] = found(kitchen([run, module])) + // its back is at 0.14 (0.09 off the 0.05 face) and its front at 0.46: 0.41 from the face + expect(p!.depth).toBeCloseTo(0.41, 3) + expect(p!.bottom).toBeCloseTo(1.4, 3) + expect(p!.approximate).toBe(true) + }) + + test('a base cabinet, whose lower edge is the floor, is not a hazard', () => { + const run = CabinetNode.parse({ + id: 'cabinet_1', + parentId: 'level_1', + position: [3, 0, 0.3], + children: ['cabinet-module_1'], + }) + const module = CabinetModuleNode.parse({ + id: 'cabinet-module_1', + parentId: run.id, + position: [0, 0, 0], + width: 0.85, + depth: 0.6, + }) + expect(found(kitchen([run, module]))).toHaveLength(0) + }) + + test('an object that stands out by less than 10 cm is not', () => { + const frame = ItemNode.parse({ + id: 'item_1', + parentId: 'wall_s', + wallId: 'wall_s', + position: [3, 1.4, 0], + side: 'front', + asset: asset({ attachTo: 'wall-side', dimensions: [0.6, 0.4, 0.04] }), + }) + expect(found(kitchen([frame], ['item_1']))).toHaveLength(0) + }) + + test('over furniture it is not in the way of anyone walking', () => { + const run = CabinetNode.parse({ + id: 'cabinet_1', + parentId: 'level_1', + position: [3, 1.4, 0.3], + runTier: 'wall', + children: ['cabinet-module_1'], + }) + const module = CabinetModuleNode.parse({ + id: 'cabinet-module_1', + parentId: run.id, + position: [0, 0, 0], + width: 0.85, + depth: 0.32, + }) + const counter = ItemNode.parse({ + id: 'item_2', + parentId: 'level_1', + position: [3, 0, 0.45], + asset: asset({ src: '/items/counter/model.glb', dimensions: [1.2, 0.9, 0.7] }), + }) + expect(found(kitchen([run, module, counter]))).toHaveLength(0) + }) +}) diff --git a/packages/core/src/spatial/usage-field/protrusion.ts b/packages/core/src/spatial/usage-field/protrusion.ts new file mode 100644 index 0000000000..7b380a4a09 --- /dev/null +++ b/packages/core/src/spatial/usage-field/protrusion.ts @@ -0,0 +1,223 @@ +import { floorsOf } from '../../agent-operations/circulation-spaces' +import { USAGE_INDICATORS } from '../../building/code-profile' +import type { WallNode } from '../../schema' +import { isCurvedWall } from '../../systems/wall/wall-curve' +import { getWallFaceLine } from '../../systems/wall/wall-frame' +import { type FloorGroup, floorGroups, inRegion } from './level-field' +import { obstacleOf, signedDistance } from './obstacles' +import type { Prism, PrismKind, UsageShapes } from './types' +import type { Nodes } from './walls' + +/** What a cane finds: a wall object whose lower edge is between 27 in and 80 in (ADA 307.2). */ +export const PROTRUSION_LOWER_EDGE_M = [ + USAGE_INDICATORS.protrusionLowest.value, + USAGE_INDICATORS.protrusionHighest.value, +] as const +/** 4 in (ADA 307.2): nearer than this to the wall, an object is not an obstacle. */ +export const PROTRUSION_LIMIT_M = USAGE_INDICATORS.protrusionLimit.value +const OBJECT_KINDS: PrismKind[] = ['item', 'cabinet', 'shelf'] +/** An object is "on" a wall if its back is this close to the face (it may stand off, or sink a little in). */ +const BACK_REACH = { standOff: 0.15, sunk: 0.12 } + +export type Protrusion = { + nodeId: string + wallId: string + face: 'a' | 'b' + /** How far the object stands out of the wall face, at most. */ + depth: number + /** Height of the lower edge of the part that protrudes, above the floor. */ + bottom: number + roomId: string + roomName: string + at: [number, number] + approximate: boolean +} + +type Face = { + wall: WallNode + face: 'a' | 'b' + ox: number + oz: number + nx: number + nz: number + tx: number + tz: number + length: number +} + +function faces(nodes: Nodes, levelId: string): Face[] { + const out: Face[] = [] + for (const node of Object.values(nodes)) { + if ( + node.type !== 'wall' || + node.parentId !== levelId || + node.visible === false || + isCurvedWall(node) + ) + continue + const dx = node.end[0] - node.start[0] + const dz = node.end[1] - node.start[1] + const length = Math.hypot(dx, dz) + if (length < 1e-6) continue + for (const face of ['a', 'b'] as const) { + const line = getWallFaceLine(node, face) + const nx = (face === 'a' ? -dz : dz) / length + const nz = (face === 'a' ? dx : -dx) / length + out.push({ + wall: node, + face, + ox: line.start.x, + oz: line.start.y, + nx, + nz, + tx: dx / length, + tz: dz / length, + length, + }) + } + } + return out +} + +/** Signed distance of a plan point beyond a wall face, outward (the room side) positive. */ +const beyond = (f: Face, x: number, z: number) => (x - f.ox) * f.nx + (z - f.oz) * f.nz +const along = (f: Face, x: number, z: number) => (x - f.ox) * f.tx + (z - f.oz) * f.tz + +/** + * Wall objects (hung cabinets, mounted shelves and screens) that stand out of a wall face by more + * than 0.10 m with their lower edge at the height a cane does not find, over a free floor in a room. + * An object is on a wall when it is hosted by it or its back is within reach of its face; the depth + * is measured from the face, whatever the object's own frame says. + */ +export function wallProtrusions(nodes: Nodes, shapes: UsageShapes): Protrusion[] { + const out: Protrusion[] = [] + const groups = floorGroups(shapes) + const zones = floorsOf(nodes).floors + const allPrisms = shapes.levels.flatMap((level) => level.prisms) + for (const level of shapes.levels) { + const levelGroups = groups.filter((g) => g.levelId === level.levelId) + if (levelGroups.length === 0) continue + const levelFaces = faces(nodes, level.levelId) + const byNode = new Map() + // wall objects only: what a wall hosts, and a run of wall cabinets; a table on legs is not one + const onWall = (prism: Prism) => { + if (!OBJECT_KINDS.includes(prism.kind)) return false + const node = nodes[prism.nodeId] + return !!prism.host || (node?.type === 'cabinet' && node.runTier === 'wall') + } + for (const prism of level.prisms) + if (onWall(prism)) byNode.set(prism.nodeId, [...(byNode.get(prism.nodeId) ?? []), prism]) + for (const [nodeId, prisms] of byNode) { + // the face it is on: the hosted one, else the face its back is nearest + let best: { face: Face; back: number } | null = null + for (const f of levelFaces) { + if ( + prisms.some((p) => p.host) && + !prisms.some((p) => p.host?.wallId === f.wall.id && p.host.face === f.face) + ) + continue + let back = Number.POSITIVE_INFINITY + let u0 = Number.POSITIVE_INFINITY + let u1 = Number.NEGATIVE_INFINITY + for (const p of prisms) + for (const [x, z] of p.outer) { + back = Math.min(back, beyond(f, x, z)) + u0 = Math.min(u0, along(f, x, z)) + u1 = Math.max(u1, along(f, x, z)) + } + const hosted = prisms.some((p) => p.host) + if (!hosted && (back < -BACK_REACH.sunk || back > BACK_REACH.standOff)) continue + if (Math.min(u1, f.length) - Math.max(u0, 0) < 0.1) continue + if (!best || Math.abs(back) < Math.abs(best.back)) best = { face: f, back } + } + if (!best) continue + const f = best.face + // each piece of the object (a module, a band) is judged where it stands: a hung cabinet run is + // over a counter at one end and over open floor at the other + let lowestBottom = Number.POSITIVE_INFINITY + let found: { + depth: number + at: [number, number] + roomId: string + roomName: string + } | null = null + for (const p of prisms) { + let reach = 0 + const out: [number, number][] = [] + for (const [x, z] of p.outer) { + const d = beyond(f, x, z) + reach = Math.max(reach, d) + if (d > PROTRUSION_LIMIT_M) out.push([x, z]) + } + if (reach <= PROTRUSION_LIMIT_M || out.length === 0) continue + const cx = out.reduce((sum, q) => sum + q[0], 0) / out.length + const cz = out.reduce((sum, q) => sum + q[1], 0) / out.length + const group = pick(levelGroups, cx, cz) + if (!group) continue + // the lower edge is the lowest the object goes over that spot: a bed's headboard stands on its frame + const lowest = Math.min(...prisms.filter((q) => pointIn(q, cx, cz)).map((q) => q.z0), p.z0) + const bottom = lowest - group.y + if (!(bottom >= PROTRUSION_LOWER_EDGE_M[0] - 1e-9 && bottom < PROTRUSION_LOWER_EDGE_M[1])) + continue + const room = zones + .find((floor) => floor.id === level.levelId) + ?.zones.find( + (zone) => !zone.outdoor && inRegion(cx, cz, { outer: zone.polygon, holes: zone.holes }), + ) + if (!room || overFurniture(allPrisms, nodeId, f.wall.id, group.y, lowest, cx, cz)) continue + lowestBottom = Math.min(lowestBottom, bottom) + if (!found || reach > found.depth) + found = { + depth: reach, + at: [cx, cz], + roomId: room.id, + roomName: String(nodes[room.id]?.name ?? room.id), + } + } + if (!found) continue + out.push({ + nodeId, + wallId: f.wall.id, + face: f.face, + depth: Math.round(found.depth * 1000) / 1000, + bottom: Math.round(lowestBottom * 1000) / 1000, + roomId: found.roomId, + roomName: found.roomName, + at: [Math.round(found.at[0] * 1000) / 1000, Math.round(found.at[1] * 1000) / 1000], + approximate: prisms.some((p) => p.shape === 'approx'), + }) + } + } + return out +} + +const pick = (groups: FloorGroup[], x: number, z: number): FloorGroup | undefined => + groups.find((g) => g.regions.some((region) => inRegion(x, z, region))) ?? groups[0] + +const pointIn = (p: Prism, x: number, z: number) => signedDistance(obstacleOf(p, 0).edges, x, z) < 0 + +const FURNITURE: PrismKind[] = ['item', 'cabinet', 'shelf', 'column', 'other'] + +/** + * Whether a piece of furniture stands under the point, below the object's lower edge: then the + * object is over it and nobody walks there. One point, the middle of the protruding part. + */ +function overFurniture( + all: Prism[], + nodeId: string, + wallId: string, + floor: number, + lower: number, + x: number, + z: number, +): boolean { + return all.some( + (p) => + FURNITURE.includes(p.kind) && + p.nodeId !== nodeId && + p.nodeId !== wallId && + p.z1 > floor + 0.03 && + p.z0 < lower - 0.01 && + signedDistance(obstacleOf(p, 0).edges, x, z) < 0, + ) +} diff --git a/packages/core/src/spatial/usage-field/shapes.test.ts b/packages/core/src/spatial/usage-field/shapes.test.ts new file mode 100644 index 0000000000..ab17791837 --- /dev/null +++ b/packages/core/src/spatial/usage-field/shapes.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + ElevatorNode, + LevelNode, + SlabNode, + StairNode, + WallNode, +} from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { usageShapes } from './shapes' +import type { Nodes } from './walls' + +function house(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_0', 'level_1'] }) + const ground = LevelNode.parse({ id: 'level_0', parentId: 'building_1', level: 0, children: [] }) + const upper = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 1, children: [] }) + return Object.fromEntries( + [building, ground, upper, ...extra].map((node) => [node.id, node]), + ) as Nodes +} + +const slab = (id: string, levelId: string, over: Record = {}) => + SlabNode.parse({ + id, + parentId: levelId, + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + elevation: 0.05, + ...over, + }) + +const wall = (levelId: string) => + WallNode.parse({ + id: `wall_${levelId}`, + parentId: levelId, + start: [0, 0], + end: [4, 0], + thickness: 0.1, + children: [], + }) + +describe('usage shapes of a house', () => { + test('a wall on an upper level stands at that level, in absolute building metres', () => { + const nodes = house([wall('level_0'), wall('level_1')]) + const { levels } = usageShapes(nodes) + const base = getLevelElevations(nodes).get('level_1')!.baseY + expect(base).toBeGreaterThan(2) + const ground = levels + .find((l) => l.levelId === 'level_0')! + .prisms.find((p) => p.kind === 'wall')! + const upper = levels + .find((l) => l.levelId === 'level_1')! + .prisms.find((p) => p.kind === 'wall')! + expect(ground.z0).toBe(0) + expect(upper.z0).toBeCloseTo(base, 6) + expect(upper.z1 - upper.z0).toBeCloseTo(ground.z1 - ground.z0, 6) + }) + + test('a stair is filed under the level it starts from and rises through the one above', () => { + const stair = StairNode.parse({ + id: 'stair_1', + parentId: 'level_0', + fromLevelId: 'level_0', + toLevelId: 'level_1', + totalRise: 3, + stepCount: 10, + fillToFloor: true, + }) + const { levels } = usageShapes(house([stair])) + const below = levels + .find((l) => l.levelId === 'level_0')! + .prisms.filter((p) => p.kind === 'stair') + expect(below).toHaveLength(10) + expect(Math.max(...below.map((p) => p.z1))).toBeCloseTo(3, 6) + expect( + levels.find((l) => l.levelId === 'level_1')!.prisms.filter((p) => p.kind === 'stair'), + ).toHaveLength(0) + }) + + test('the floor is the slab surface at the height the circulation graph reads, less recessed slabs', () => { + const nodes = house([ + slab('slab_a', 'level_0'), + slab('slab_b', 'level_1', { elevation: 0.1 }), + slab('slab_pool', 'level_0', { recessed: true }), + ]) + const { levels, skipped } = usageShapes(nodes) + const base = getLevelElevations(nodes).get('level_1')!.baseY + const ground = levels.find((l) => l.levelId === 'level_0')!.floors + expect(ground.map((f) => f.nodeId)).toEqual(['slab_a']) + expect(ground[0]!.y).toBeCloseTo(0.05, 6) + expect(levels.find((l) => l.levelId === 'level_1')!.floors[0]!.y).toBeCloseTo(base + 0.1, 6) + expect(skipped.some((s) => s.nodeId === 'slab_pool')).toBe(true) + }) + + test('a slab hole is a hole in the floor', () => { + const holed = slab('slab_a', 'level_0', { + holes: [ + [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ], + ], + }) + const floor = usageShapes(house([holed])).levels[0]!.floors[0]! + expect(floor.holes).toHaveLength(1) + }) + + test('what is not shaped yet is counted, not hidden', () => { + const lift = ElevatorNode.parse({ id: 'elevator_1', parentId: 'level_0' }) + expect(usageShapes(house([lift])).unshaped).toEqual({ elevator: 1 }) + }) + + test('one stair the resolvers refuse does not take the others down', () => { + const fine = StairNode.parse({ + id: 'stair_ok', + parentId: 'level_0', + fromLevelId: 'level_0', + totalRise: 3, + }) + const huge = StairNode.parse({ + id: 'stair_huge', + parentId: 'level_0', + fromLevelId: 'level_0', + stepCount: 100_000, + totalRise: 3, + }) + const result = usageShapes(house([fine, huge])) + expect(result.skipped.map((s) => s.nodeId)).toEqual(['stair_huge']) + expect(result.levels[0]!.prisms.some((p) => p.nodeId === 'stair_ok')).toBe(true) + }) +}) diff --git a/packages/core/src/spatial/usage-field/shapes.ts b/packages/core/src/spatial/usage-field/shapes.ts new file mode 100644 index 0000000000..b8c677ae52 --- /dev/null +++ b/packages/core/src/spatial/usage-field/shapes.ts @@ -0,0 +1,99 @@ +import type { AnyNode, AnyNodeId } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { boxBodies } from './boxes' +import { fenceBodies } from './fences' +import { levelFloors } from './floors' +import { itemBodies } from './items' +import { openingBodies } from './openings' +import { stairBodies } from './stairs' +import type { LevelShapes, Prism, Skipped, UsageShapes } from './types' +import { levelWalls, type Nodes, wallBodies, wallTrims } from './walls' + +export { sdfChecksOn, setSdfChecks } from './flag' +export type { FloorRegion, LevelShapes, Prism, PrismKind, Skipped, UsageShapes } from './types' + +/** Kinds that stand in a room and are not shaped yet; counted so a finding can say what it did not see. */ +const NOT_SHAPED_YET = ['elevator', 'ramp', 'chimney', 'rock'] as const + +const lifted = (prisms: Prism[], dy: number): Prism[] => + dy === 0 ? prisms : prisms.map((prism) => ({ ...prism, z0: prism.z0 + dy, z1: prism.z1 + dy })) + +/** + * What a person walks around, level by level, as prisms in the building's frame: plan polygons in + * metres between two absolute heights. Walls, their trims, door and window frames and sills, stairs + * and their guards, and the floor itself. A stair is filed under the level it starts from, but its + * prisms rise through the levels above, so a query reads the prisms of a whole building by height, + * not one level's list. + * + * Items stand on the floor, on the item that hosts them, or on a wall, each as its script's stored + * outline or a box. Pure: it reads the node record and the helpers the renderers read, and builds no meshes. A node + * whose shape cannot be read is named in `skipped`; one that is drawn only roughly is named in + * `approximate`; kinds not shaped yet are counted in `unshaped`. + */ +export function usageShapes(nodes: Nodes): UsageShapes { + const elevations = getLevelElevations(nodes as Record) + const { floors, skipped: floorSkips } = levelFloors(nodes) + const skipped: Skipped[] = [...floorSkips] + const byLevel = new Map() + const level = (levelId: string): LevelShapes => { + let shapes = byLevel.get(levelId) + if (!shapes) { + shapes = { levelId, prisms: [], floors: floors.get(levelId) ?? [] } + byLevel.set(levelId, shapes) + } + return shapes + } + const levelIds = Object.values(nodes) + .filter((node) => node.type === 'level') + .map((node) => node.id) + .sort() + for (const levelId of levelIds) { + const baseY = elevations.get(levelId)?.baseY ?? 0 + const walls = levelWalls(nodes, levelId) + const trims = wallTrims(nodes, levelId, walls) + for (const wallId of trims.skipped) + skipped.push({ nodeId: wallId, why: 'a curved wall: its trim is not drawn here' }) + level(levelId).prisms.push( + ...lifted( + [ + ...wallBodies(nodes, levelId, walls), + ...trims.prisms, + ...openingBodies(nodes, levelId, walls), + ], + baseY, + ), + ) + } + const { stairs, skipped: stairSkips, handrails } = stairBodies(nodes) + skipped.push(...stairSkips) + for (const stair of stairs) { + if (!stair.levelId) { + skipped.push({ nodeId: stair.stairId, why: 'a stair on no level' }) + continue + } + level(stair.levelId).prisms.push(...stair.prisms) + } + const items = itemBodies(nodes) + skipped.push(...items.skipped) + for (const item of items.items) if (item.levelId) level(item.levelId).prisms.push(...item.prisms) + const boxes = boxBodies(nodes) + skipped.push(...boxes.skipped) + for (const box of boxes.nodes) if (box.levelId) level(box.levelId).prisms.push(...box.prisms) + const fences = fenceBodies(nodes) + skipped.push(...fences.skipped) + for (const fence of fences.fences) + if (fence.levelId) level(fence.levelId).prisms.push(...fence.prisms) + const unshaped: Record = { ...items.unshaped } + for (const node of Object.values(nodes)) + if ((NOT_SHAPED_YET as readonly string[]).includes(node.type)) + unshaped[node.type] = (unshaped[node.type] ?? 0) + 1 + if (handrails) unshaped['stair handrail'] = handrails + const levels = levelIds.map((levelId) => level(levelId)) + const approximate = [ + ...new Set([ + ...levels.flatMap((l) => l.prisms.filter((p) => p.shape === 'approx').map((p) => p.nodeId)), + ...levels.flatMap((l) => l.floors.filter((f) => f.shape === 'approx').map((f) => f.nodeId)), + ]), + ].sort() + return { levels, approximate, unshaped, skipped } +} diff --git a/packages/core/src/spatial/usage-field/stairs.test.ts b/packages/core/src/spatial/usage-field/stairs.test.ts new file mode 100644 index 0000000000..3e75b43766 --- /dev/null +++ b/packages/core/src/spatial/usage-field/stairs.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, BuildingNode, LevelNode, StairNode } from '../../schema' +import { rotateXZ } from '../../systems/stair/stair-footprint' +import { SLOPE_STEP_M, stairBodies } from './stairs' +import type { Prism } from './types' +import type { Nodes } from './walls' + +function scene(extra: AnyNode[]): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const stair = (over: Record = {}) => + StairNode.parse({ + id: 'stair_1', + parentId: 'level_1', + totalRise: 3, + stepCount: 10, + width: 1, + ...over, + }) + +const bounds = (prisms: Prism[]) => { + const points = prisms.flatMap((p) => p.outer) + const xs = points.map(([x]) => x) + const zs = points.map(([, z]) => z) + return { x0: Math.min(...xs), x1: Math.max(...xs), z0: Math.min(...zs), z1: Math.max(...zs) } +} + +describe('stair treads', () => { + test('a stair filled to the floor is solid from the floor to each tread', () => { + const { stairs } = stairBodies(scene([stair({ fillToFloor: true })])) + const treads = stairs[0]!.prisms.filter((p) => p.kind === 'stair') + expect(treads).toHaveLength(10) + expect(treads.every((p) => p.z0 === 0 && p.shape === 'exact')).toBe(true) + expect(Math.max(...treads.map((p) => p.z1))).toBeCloseTo(3, 6) + expect(Math.min(...treads.map((p) => p.z1))).toBeCloseTo(0.3, 6) + expect(stairs[0]!.levelId).toBe('level_1') + }) + + test('an open flight has a soffit that rises, cut into slices of the slope step', () => { + const { stairs } = stairBodies(scene([stair({ fillToFloor: false })])) + const treads = stairs[0]!.prisms.filter((p) => p.kind === 'stair') + const last = treads.filter((p) => p.id.includes('.9')) + expect(last.length).toBeGreaterThan(1) + for (const p of treads) expect(p.z1 - p.z0).toBeGreaterThan(0) + // the soffit under the last tread is about a slab's thickness under it, not at the floor + expect(Math.min(...last.map((p) => p.z0))).toBeGreaterThan(2) + // slices of one tread step by the slope step + const starts = [...last].map((p) => p.z0).sort((a, b) => a - b) + for (let i = 1; i < starts.length; i++) + expect(starts[i]! - starts[i - 1]!).toBeCloseTo(SLOPE_STEP_M, 6) + }) + + test('a stair that the resolvers refuse is named and leaves the others alone', () => { + const fine = stair({ id: 'stair_2', position: [5, 0, 0] }) + const tooLarge = stair({ id: 'stair_3', stepCount: 100_000, totalRise: 3 }) + const { stairs, skipped } = stairBodies(scene([fine, tooLarge])) + expect(stairs.map((s) => s.stairId)).toEqual(['stair_2']) + expect(skipped.map((s) => s.nodeId)).toEqual(['stair_3']) + expect(skipped[0]!.why.length).toBeGreaterThan(0) + }) +}) + +describe('stair guards', () => { + const rails = (over: Record = {}) => + stairBodies( + scene([stair({ railingMode: 'both', fillToFloor: true, ...over })]), + ).stairs[0]!.prisms.filter((p) => p.kind === 'stair-rail') + + test('a guard is read as its rail line: approximate, from the nosing to the rail height', () => { + const prisms = rails() + expect(prisms.length).toBeGreaterThan(0) + expect(prisms.every((p) => p.shape === 'approx' && p.why?.includes('rail line'))).toBe(true) + for (const p of prisms) expect(p.z1 - p.z0).toBeGreaterThanOrEqual(0.9 - 1e-6) + }) + + test('no railing mode, or a destination surface, draws no guard', () => { + expect(rails({ railingMode: 'none' })).toHaveLength(0) + expect(rails({ destinationSurfaceId: 'slab_x' })).toHaveLength(0) + }) + + test('a rail on a sloping flight is cut into slices that rise a slope step each, so a rail high over a walkway does not block it', () => { + const prisms = rails({ railingHeight: 0.9 }) + expect(prisms.length).toBeGreaterThan(40) + expect(Math.max(...prisms.map((p) => p.z1 - p.z0))).toBeLessThan(0.9 + SLOPE_STEP_M + 1e-6) + const low = prisms.filter((p) => p.z0 < 0.5) + const high = prisms.filter((p) => p.z0 > 2) + expect(low.length).toBeGreaterThan(0) + expect(high.length).toBeGreaterThan(0) + }) + + test('a rail height of the stair sets the guard height', () => { + expect(Math.min(...rails({ railingHeight: 1.1 }).map((p) => p.z1 - p.z0))).toBeCloseTo(1.1, 6) + }) + + test('the stair turned a quarter turn carries its guard with it', () => { + const at0 = rails() + const at90 = rails({ rotation: Math.PI / 2 }) + const b0 = bounds(at0) + const b90 = bounds(at90) + const corners = [rotateXZ(b0.x0, b0.z0, Math.PI / 2), rotateXZ(b0.x1, b0.z1, Math.PI / 2)] + expect(b90.x0).toBeCloseTo(Math.min(...corners.map(([x]) => x)), 6) + expect(b90.x1).toBeCloseTo(Math.max(...corners.map(([x]) => x)), 6) + expect(b90.z0).toBeCloseTo(Math.min(...corners.map(([, z]) => z)), 6) + expect(b90.z1).toBeCloseTo(Math.max(...corners.map(([, z]) => z)), 6) + }) + + test('an independent handrail is counted, not drawn', () => { + const { handrails } = stairBodies( + scene([stair({ railingMode: 'none', handrail: { mode: 'left' } })]), + ) + expect(handrails).toBe(1) + }) +}) diff --git a/packages/core/src/spatial/usage-field/stairs.ts b/packages/core/src/spatial/usage-field/stairs.ts new file mode 100644 index 0000000000..5c0b763991 --- /dev/null +++ b/packages/core/src/spatial/usage-field/stairs.ts @@ -0,0 +1,198 @@ +import { area } from '../../lib/polygon-boolean' +import type { AnyNode, StairNode } from '../../schema' +import { + resolveStairWalkingSurfaces, + type StairBodySurface, + type StairWalkingSurface, + stairSourceFrame, +} from '../../systems/stair/stair-clearance' +import { rotateXZ } from '../../systems/stair/stair-footprint' +import { resolveStairRailPaths } from '../../systems/stair/stair-rail-path' +import type { Prism, Ring, Skipped } from './types' +import type { Nodes } from './walls' + +/** + * A sloped member (a soffit, a rail, a glass pane) is cut into slices that rise this much each, so + * its prism height stays within this of the member's own at any point along it. + */ +export const SLOPE_STEP_M = 0.05 + +const MIN_AREA_M2 = 1e-7 + +type Point = [number, number] +type Place = (x: number, z: number) => Point + +export type StairShapes = { stairId: string; levelId: string | null; prisms: Prism[] } + +/** Convex hull of up to a few points, counter-clockwise. */ +function hull(points: Point[]): Ring { + const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]) + const cross = (o: Point, a: Point, b: Point) => + (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) + const half = (list: Point[]) => { + const out: Point[] = [] + for (const p of list) { + while (out.length >= 2 && cross(out.at(-2)!, out.at(-1)!, p) <= 1e-12) out.pop() + out.push(p) + } + out.pop() + return out + } + return [...half(sorted), ...half(sorted.reverse())] +} + +/** The part of a polygon where `value` is at least zero (Sutherland–Hodgman against one half-plane). */ +function clipAbove(ring: Ring, value: (p: Point) => number): Ring { + const out: Ring = [] + for (let i = 0; i < ring.length; i++) { + const p = ring[i]! + const q = ring[(i + 1) % ring.length]! + const vp = value(p) + const vq = value(q) + if (vp >= 0) out.push(p) + if (vp >= 0 !== vq >= 0) { + const t = vp / (vp - vq) + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]) + } + } + return out +} + +const ringArea = (ring: Ring) => area([{ outer: ring, holes: [] }]) + +type Common = Pick + +/** + * A body of a stair: its walking region from its soffit up to its top. A soffit that slopes (an + * open flight) is cut into slices where it rises `SLOPE_STEP_M`, each from the lowest the soffit + * gets inside it, so the headroom under a flight is read to within that step. + */ +function bodyPrisms( + id: string, + body: Pick, + common: Common, + out: Prism[], +) { + const [a, b, c] = body.underside + const floor = body.undersideFloor ?? Number.NEGATIVE_INFINITY + const outer = body.region.outer + const sloped = Math.abs(a) + Math.abs(b) > 1e-9 && body.region.holes.length === 0 + const soffit = (p: Point) => a * p[0] + b * p[1] + c + const heights = outer.map(soffit) + const lowest = Math.min(...heights) + const slices = sloped ? Math.max(1, Math.ceil((Math.max(...heights) - lowest) / SLOPE_STEP_M)) : 1 + for (let k = 0; k < slices; k++) { + const piece = + slices === 1 + ? outer + : clipAbove( + clipAbove(outer, (p) => soffit(p) - (lowest + k * SLOPE_STEP_M)), + (p) => lowest + (k + 1) * SLOPE_STEP_M - soffit(p), + ) + if (piece.length < 3 || (slices > 1 && ringArea(piece) < MIN_AREA_M2)) continue + const z0 = Math.max(slices === 1 ? lowest : lowest + k * SLOPE_STEP_M, floor) + if (body.top - z0 > 1e-4) + out.push({ + id: slices === 1 ? id : `${id}.${k}`, + z0, + z1: body.top, + outer: piece, + holes: slices === 1 ? body.region.holes : [], + ...common, + }) + } +} + +/** What a stair's guard fills in the clearance: its rail line, a hand wide, from the nosing to the rail. */ +const GUARD_WIDTH_M = 0.08 +const DEFAULT_RAIL_HEIGHT_M = 0.9 + +/** + * The guard along each rail path, as slices of the line it follows: a slice rises `SLOPE_STEP_M`, + * so a rail high over a walkway does not block it. Its posts, balusters and panes are not drawn + * one by one. + */ +function railPrisms(stair: StairNode, nodes: Nodes, base: number, place: Place, out: Prism[]) { + if (stair.destinationSurfaceId || stair.railingMode === 'none') return + const height = stair.railingHeight ?? DEFAULT_RAIL_HEIGHT_M + const common: Common = { + nodeId: stair.id, + kind: 'stair-rail', + shape: 'approx', + why: 'the stair guard is read as its rail line, a hand wide', + } + resolveStairRailPaths(stair, nodes).forEach((path, index) => { + for (const [i, from] of path.points.slice(0, -1).entries()) { + const to = path.points[i + 1] as [number, number, number] + const slices = Math.max(1, Math.ceil(Math.abs(to[1] - from[1]) / SLOPE_STEP_M)) + const length = Math.hypot(to[0] - from[0], to[2] - from[2]) + const [nx, nz] = + length > 1e-6 ? [(from[2] - to[2]) / length, (to[0] - from[0]) / length] : [0, 1] + const at = (t: number): [number, number, number] => [ + from[0] + (to[0] - from[0]) * t, + from[1] + (to[1] - from[1]) * t, + from[2] + (to[2] - from[2]) * t, + ] + for (let k = 0; k < slices; k++) { + const [a, b] = [at(k / slices), at((k + 1) / slices)] + const half = GUARD_WIDTH_M / 2 + out.push({ + id: `${stair.id}#rail.${path.side}.${index}.${i}.${k}`, + z0: base + Math.min(a[1], b[1]), + z1: base + Math.max(a[1], b[1]) + height, + outer: hull( + [a, b].flatMap(([x, , z]) => [ + place(x + nx * half, z + nz * half), + place(x - nx * half, z - nz * half), + ]), + ), + holes: [], + ...common, + }) + } + } + }) +} + +function treadPrisms(stair: StairNode, nodes: Nodes, out: Prism[]) { + const common: Common = { nodeId: stair.id, kind: 'stair', shape: 'exact' } + for (const surface of resolveStairWalkingSurfaces(stair, nodes) as StairWalkingSurface[]) { + const prefix = `${stair.id}#${surface.nodeId}.${surface.index}` + const solids: Pick[] = + surface.bodies ?? [surface] + for (const [i, solid] of solids.entries()) bodyPrisms(`${prefix}.${i}`, solid, common, out) + } +} + +/** + * Every stair's treads, landings and guards as prisms in absolute building metres, each filed under + * the level the stair starts from. A stair the resolvers refuse (their detail budgets) is named in + * `skipped` and leaves the others alone; the independent handrail is not drawn here and is counted. + */ +export function stairBodies(nodes: Nodes): { + stairs: StairShapes[] + skipped: Skipped[] + handrails: number +} { + const stairs: StairShapes[] = [] + const skipped: Skipped[] = [] + let handrails = 0 + for (const node of Object.values(nodes) as AnyNode[]) { + if (node.type !== 'stair') continue + try { + const frame = stairSourceFrame(node, nodes) + const place: Place = (x, z) => { + const [dx, dz] = rotateXZ(x, z, node.rotation) + return [node.position[0] + dx, node.position[2] + dz] + } + const prisms: Prism[] = [] + treadPrisms(node, nodes, prisms) + railPrisms(node, nodes, frame.base, place, prisms) + if (node.handrail && !node.destinationSurfaceId) handrails += 1 + stairs.push({ stairId: node.id, levelId: frame.sourceId, prisms }) + } catch (error) { + skipped.push({ nodeId: node.id, why: error instanceof Error ? error.message : String(error) }) + } + } + return { stairs, skipped, handrails } +} diff --git a/packages/core/src/spatial/usage-field/support.ts b/packages/core/src/spatial/usage-field/support.ts new file mode 100644 index 0000000000..7558db0a5a --- /dev/null +++ b/packages/core/src/spatial/usage-field/support.ts @@ -0,0 +1,72 @@ +import { GROUND_SUPPORT_ID } from '../../hooks/spatial-grid/support-host-id' +import { floorConstructionLift } from '../../lib/floor-construction-lift' +import { selectSlabSupportForItem } from '../../lib/item-slab-support' +import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import { levelBaseElevationAt } from '../../lib/terrain-support-query' +import type { AnyNode, SlabNode, WallNode } from '../../schema' +import type { Nodes } from './walls' + +type Footprint = { + position: [number, number, number] + dimensions: [number, number, number] + rotation: [number, number, number] +} + +type LevelSlabs = { slabs: SlabNode[]; polygons: Map } + +/** Per-level slabs and their rendered outlines, built once per query. */ +export type SupportCache = Map + +function slabsOf(nodes: Nodes, levelId: string, cache: SupportCache): LevelSlabs { + const hit = cache.get(levelId) + if (hit) return hit + const on = Object.values(nodes).filter((node) => node.parentId === levelId) + const slabs = on.filter((node): node is SlabNode => node.type === 'slab') + const walls = on.filter((node): node is WallNode => node.type === 'wall') + const polygons = new Map( + slabs.map((slab) => [ + slab.id, + getRenderableSlabPolygon(slab, { + walls, + siblingSlabs: slabs.filter((other) => other.id !== slab.id), + }), + ]), + ) + const made = { slabs, polygons } + cache.set(levelId, made) + return made +} + +/** + * The level-local height of the floor under a floor-placed node, by the election the editor makes: + * the slab its footprint overlaps (the one it is pinned to, else the highest), else the ground. + */ +export function floorUnder( + node: AnyNode & { supportSlabId?: string }, + footprint: Footprint, + nodes: Nodes, + levelId: string, + cache: SupportCache, +): number { + const [x, , z] = footprint.position + const ground = () => + levelBaseElevationAt(nodes as Record, levelId, x, z) + + floorConstructionLift(nodes, node) + if (node.supportSlabId === GROUND_SUPPORT_ID) return ground() + const { slabs, polygons } = slabsOf(nodes, levelId, cache) + const winner = selectSlabSupportForItem(slabs, footprint, (slab) => polygons.get(slab.id)!, { + preferredSlabId: node.supportSlabId, + }) + return winner ? winner.elevation : ground() +} + +/** Whether a node, or anything it hangs from, is hidden. */ +export function isHidden(node: AnyNode, nodes: Nodes): boolean { + for ( + let current: AnyNode | undefined = node; + current; + current = current.parentId ? nodes[current.parentId] : undefined + ) + if (current.visible === false && current.type !== 'site') return true + return false +} diff --git a/packages/core/src/spatial/usage-field/swings.ts b/packages/core/src/spatial/usage-field/swings.ts new file mode 100644 index 0000000000..7d6a63970f --- /dev/null +++ b/packages/core/src/spatial/usage-field/swings.ts @@ -0,0 +1,479 @@ +import { isFloorUnderlay } from '../../agent-operations/furniture-kind' +import { resolveLevelId } from '../../lib/node-ancestry' +import type { DoorNode, ItemNode, WallNode, ZoneNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import { getWallLocalFaceZ } from '../../systems/wall/wall-frame' +import { PASSAGE_M, type UsageIssue } from './findings' +import { m, nameOf, quote, unique } from './labels' +import { type Obstacle, obstacleDistance, obstacleOf } from './obstacles' +import { doorwayRing } from './openings' +import { isFoliage, isPiecePrism, roomAt } from './pieces' +import type { LevelShapes, Prism, UsageShapes } from './types' +import type { Nodes } from './walls' +import { wayIn } from './way-in' + +/** The leaf is swept in steps of this many degrees. */ +export const SWEEP_STEP_DEG = 3 +/** A door that stops before this angle does not open fully: a leaf flat against a wall at 90 degrees reads a few degrees short, and one that opens to 80 leaves the way clear. */ +export const OPENS_FULLY_DEG = 80 +/** A leaf that stops short of this angle is no way through: the finding is ranked with the blockers. */ +export const DOOR_STOPPED_BLOCKING_DEG = 30 +/** A leaf is in something once it is this far inside it (m): a leaf resting against a surface is not. */ +const PENETRATION_M = 0.015 +const LEAF_STEP_M = 0.04 +/** The leaf is a little narrower than its opening: the frame takes this much (m). */ +export const FRAME_M = 0.04 +const LEAF_THICKNESS_M = 0.04 +/** Two openings this near are one pair of doors. */ +const PAIR_GAP_M = 0.05 +/** An open leaf rests on a wall when its middle and tip are this near it (m): a hand's breadth off is not flat. */ +const REST_M = 0.1 +const DEFAULT_DOOR_HEIGHT_M = 2.04 + +export const FIXTURE = + /toilet|water ?closet|(?:^|[^a-z])wc(?![a-z])|basin|lavatory|vanity|sink|shower|bath|(?:^|[^a-z])tub(?![a-z])/i + +export type Hung = { swing: 1 | -1; hs: 1 | -1 } +type Point = [number, number] + +type Sweep = { + free: number + by: { + prism: Prism + name: string + kind: 'wall' | 'cabinet' | 'fixture' | 'furniture' | 'door' | 'stair' + } | null +} + +/** + * Which way each door's leaf can be swept: a door swinging to a side of its wall, hinged at one jamb. + * The side and the hinge follow the floor plan's drawing (`hingesSide`, `swingDirection`, both flipped for a turned door). + */ +export function hungOf(door: DoorNode): Hung { + const flipped = Math.cos(door.rotation?.[1] ?? 0) < 0 + const hingeLeft = flipped ? door.hingesSide !== 'left' : door.hingesSide === 'left' + const inward = flipped ? door.swingDirection !== 'inward' : door.swingDirection === 'inward' + return { swing: inward ? 1 : -1, hs: hingeLeft ? 1 : -1 } +} + +/** The door fields that give `hung` on a door that is not turned: the inverse of `hungOf`. */ +export function hangingOf(hung: Hung): Pick { + return { + hingesSide: hung.hs > 0 ? 'left' : 'right', + swingDirection: hung.swing > 0 ? 'inward' : 'outward', + } +} + +/** The doors on a level whose leaf swings: not sliding, garage, pocket or open doorways. */ +export function swingDoors(nodes: Nodes, levelId: string): DoorNode[] { + return Object.values(nodes).filter( + (node): node is DoorNode => + node.type === 'door' && + node.visible !== false && + node.doorType !== 'sliding' && + !String(node.doorType).startsWith('garage') && + node.doorType !== 'pocket' && + node.openingKind !== 'opening' && + (nodes[node.parentId ?? ''] as WallNode | undefined)?.type === 'wall' && + resolveLevelId(nodes[node.parentId!] as WallNode, nodes as never) === levelId, + ) +} + +/** A door in its wall's frame: the wall's origin, unit tangent and normal, half the opening and where it is along the wall. */ +export function doorFrame(nodes: Nodes, door: DoorNode) { + const wall = nodes[door.parentId!] as WallNode + const [sx, sz] = wall.start + const length = Math.hypot(wall.end[0] - sx, wall.end[1] - sz) + const tx = (wall.end[0] - sx) / length + const tz = (wall.end[1] - sz) / length + return { + wall, + sx, + sz, + tx, + tz, + nx: -tz, + nz: tx, + half: (door.width ?? 0.9) / 2, + along: door.position[0], + } +} + +/** Where a door's leaf is hinged: at the jamb, on the face of the wall it swings to. */ +export function hingeOf(nodes: Nodes, door: DoorNode, hung: Hung): Point { + const f = doorFrame(nodes, door) + const faceZ = getWallLocalFaceZ(f.wall, hung.swing > 0 ? 'a' : 'b') + return [ + f.sx + f.tx * (f.along - hung.hs * f.half) + f.nx * faceZ, + f.sz + f.tz * (f.along - hung.hs * f.half) + f.nz * faceZ, + ] +} + +/** The direction the leaf points at `theta` radians from closed. */ +export function leafDirection(f: ReturnType, hung: Hung, theta: number): Point { + return [ + f.tx * hung.hs * Math.cos(theta) + f.nx * hung.swing * Math.sin(theta), + f.tz * hung.hs * Math.cos(theta) + f.nz * hung.swing * Math.sin(theta), + ] +} + +/** Whether two walls lie on the same line (a wall split in two, the door near the join): neither is an obstacle to a leaf on the other. */ +function continues(a: WallNode, b: WallNode): boolean { + const ax = a.end[0] - a.start[0] + const az = a.end[1] - a.start[1] + const bx = b.end[0] - b.start[0] + const bz = b.end[1] - b.start[1] + const al = Math.hypot(ax, az) + const bl = Math.hypot(bx, bz) + if (al < 1e-6 || bl < 1e-6) return false + if (Math.abs((ax * bz - az * bx) / (al * bl)) > Math.sin((8 * Math.PI) / 180)) return false + return Math.abs(((b.start[0] - a.start[0]) * -az + (b.start[1] - a.start[1]) * ax) / al) < 0.3 +} + +/** + * What reads how the doors of one level swing: a door's leaf swept against what stands round it (`sweepOf`), and the way + * into the room it opens into past the leaf open at an angle (`wayOf`). + */ +export function swingReader(nodes: Nodes, shapes: UsageShapes, level: LevelShapes) { + const baseY = getLevelElevations(nodes as never).get(level.levelId)?.baseY ?? 0 + const isUnderlay = (prism: Prism) => + nodes[prism.nodeId]?.type === 'item' && isFloorUnderlay(nodes[prism.nodeId] as ItemNode) + const prisms = level.prisms.filter((prism) => !isUnderlay(prism)) + const pieces = prisms.filter((p) => isPiecePrism(p) && !isFoliage(nodes, p.nodeId)) + const walls = prisms.filter((p) => p.kind === 'wall') + const stairs = prisms.filter((p) => p.kind === 'stair') + const doors = swingDoors(nodes, level.levelId) + const heightOf = (door: DoorNode) => baseY + (door.height ?? DEFAULT_DOOR_HEIGHT_M) + + const frameOf = (door: DoorNode) => doorFrame(nodes, door) + const leafPrism = (door: DoorNode): Prism => { + const f = frameOf(door) + const across = (getWallLocalFaceZ(f.wall, 'a') + getWallLocalFaceZ(f.wall, 'b')) / 2 + const at = (u: number, v: number): Point => [ + f.sx + f.tx * u + f.nx * v, + f.sz + f.tz * u + f.nz * v, + ] + return { + id: `${door.id}#leaf`, + nodeId: door.id, + kind: 'other', + z0: baseY, + z1: heightOf(door), + outer: [ + at(f.along - f.half, across - LEAF_THICKNESS_M / 2), + at(f.along + f.half, across - LEAF_THICKNESS_M / 2), + at(f.along + f.half, across + LEAF_THICKNESS_M / 2), + at(f.along - f.half, across + LEAF_THICKNESS_M / 2), + ], + holes: [], + shape: 'exact', + } + } + const classOf = (prism: Prism): NonNullable['kind'] => + prism.kind === 'wall' + ? 'wall' + : prism.kind === 'stair' + ? 'stair' + : prism.kind === 'other' + ? 'door' + : prism.kind === 'cabinet' + ? 'cabinet' + : FIXTURE.test(nameOf(nodes, prism.nodeId)) + ? 'fixture' + : 'furniture' + const leaves = new Map(doors.map((door) => [door.id, leafPrism(door)])) + /** The walls a door's leaf can meet: all but its own and those that carry on in line with it. */ + const wallsAround = (door: DoorNode) => { + const host = frameOf(door).wall + return walls.filter((p) => { + const other = nodes[p.nodeId] as WallNode | undefined + return p.nodeId !== host.id && !(other?.type === 'wall' && continues(host, other)) + }) + } + + const sweepOf = (door: DoorNode, hung: Hung): Sweep & { pivot: Point } => { + const f = frameOf(door) + const [hx, hz] = hingeOf(nodes, door, hung) + const top = heightOf(door) + const around: Obstacle[] = [] + let index = 0 + const across = (getWallLocalFaceZ(f.wall, 'a') + getWallLocalFaceZ(f.wall, 'b')) / 2 + const closed: Point = [ + f.sx + f.tx * f.along + f.nx * across, + f.sz + f.tz * f.along + f.nz * across, + ] + const take = (prism: Prism) => { + if (prism.z1 <= baseY + 0.05 || prism.z0 >= top - 0.1) return + const obstacle = obstacleOf(prism, index++) + // An approximate outline that holds the closed leaf is a box round the door (a portal, a + // frame, trim the door stands in), not something in its way: its true outline has the opening. + if (prism.shape === 'approx' && obstacleDistance(obstacle, closed[0], closed[1]) < 0) return + around.push(obstacle) + } + for (const p of pieces) if (p.nodeId !== door.id) take(p) + for (const p of wallsAround(door)) take(p) + for (const p of stairs) take(p) + for (const [id, leaf] of leaves) if (id !== door.id) take(leaf) + const length = 2 * f.half - FRAME_M + for (let a = SWEEP_STEP_DEG; a <= 90; a += SWEEP_STEP_DEG) { + const th = (a * Math.PI) / 180 + const [dx, dz] = leafDirection(f, hung, th) + for (let s = LEAF_STEP_M; s <= length + 1e-9; s += LEAF_STEP_M) { + const px = hx + dx * s + const pz = hz + dz * s + for (const ob of around) { + if ( + px < ob.aabb[0] - 0.02 || + px > ob.aabb[2] + 0.02 || + pz < ob.aabb[1] - 0.02 || + pz > ob.aabb[3] + 0.02 + ) + continue + if (obstacleDistance(ob, px, pz) >= -PENETRATION_M) continue + return { + free: a - SWEEP_STEP_DEG, + by: { + prism: ob.prism, + name: nameOf(nodes, ob.prism.nodeId), + kind: classOf(ob.prism), + }, + pivot: [hx, hz], + } + } + } + } + return { free: 90, by: null, pivot: [hx, hz] } + } + + // only a door of one hinged leaf: a double, a french pair, a folding or a barn door is not one leaf of the whole width, + // and neither is a door whose opening abuts another's, a pair meant to open together + const notOneLeaf = (door: DoorNode) => + door.doorType !== 'hinged' || + (door.leafCount ?? 1) > 1 || + doors.some( + (other) => + other.id !== door.id && + other.parentId === door.parentId && + hungOf(other).swing === hungOf(door).swing && + Math.abs(other.position[0] - door.position[0]) <= + ((other.width ?? 0.9) + (door.width ?? 0.9)) / 2 + PAIR_GAP_M, + ) + + /** The room a leaf swinging to `swing` opens into: the zone 0.3 m off the wall's face on that side. */ + const roomBeyond = (door: DoorNode, swing: 1 | -1) => { + const f = frameOf(door) + const across = (getWallLocalFaceZ(f.wall, 'a') + getWallLocalFaceZ(f.wall, 'b')) / 2 + const front: Point = [ + f.sx + f.tx * f.along + f.nx * (across + swing * 0.3), + f.sz + f.tz * f.along + f.nz * (across + swing * 0.3), + ] + return roomAt(nodes, level.levelId, front) + } + /** The way into the room the door opens into, with its leaf open at `angle`: narrow only when the leaf bounds it. */ + const wayOf = (door: DoorNode, hung: Hung, angle: number) => { + const f = frameOf(door) + const room = roomBeyond(door, hung.swing) + const zone = room ? (nodes[room.id] as ZoneNode) : null + if (!room || !zone) return null + const ring = doorwayRing(f.wall, door) + if (!ring) return null + const [hx, hz] = hingeOf(nodes, door, hung) + const [dx, dz] = leafDirection(f, hung, (angle * Math.PI) / 180) + const length = 2 * f.half - FRAME_M + const leaf: Prism = { + id: `${door.id}#open-leaf`, + nodeId: door.id, + kind: 'other', + z0: baseY, + z1: baseY + (door.height ?? DEFAULT_DOOR_HEIGHT_M), + outer: [ + [hx, hz], + [hx + dx * length, hz + dz * length], + ], + holes: [], + shape: 'exact', + } + const way = wayIn( + shapes, + level, + zone, + ring, + [hx, hz], + baseY, + isUnderlay, + (prism) => prism.id === leaf.id, + leaf, + ) + return { room, way, leaf } + } + const rests = (door: DoorNode, hung: Hung) => { + const f = frameOf(door) + const [hx, hz] = hingeOf(nodes, door, hung) + const [dx, dz] = leafDirection(f, hung, Math.PI / 2) + const length = 2 * f.half - FRAME_M + const against = wallsAround(door) + .filter((wall) => wall.z1 > baseY + 0.05 && wall.z0 < heightOf(door) - 0.1) + .map(obstacleOf) + return against.some((wall) => + [0.5, 1].every( + (share) => + obstacleDistance(wall, hx + dx * length * share, hz + dz * length * share) <= REST_M, + ), + ) + } + const wayInIssue = (door: DoorNode, hung: Hung, angle: number): UsageIssue | null => { + if (notOneLeaf(door)) return null + const here = wayOf(door, hung, angle) + if (!here?.way) return null + const { room, way, leaf } = here + const other = way.by.find((o) => o.prism.id !== leaf.id) + const bound = other + ? `between the leaf's edge and ${quote(nameOf(nodes, other.prism.nodeId))}` + : `against the leaf's edge` + const flipped: Hung = { swing: hung.swing, hs: -hung.hs as 1 | -1 } + const there = sweepOf(door, flipped) + const instead = + there.free < OPENS_FULLY_DEG + ? `hung at the other jamb it opens to ${there.free}° and no further` + : (() => { + const again = wayOf(door, flipped, there.free)?.way + return again + ? `hung at the other jamb the way would be ${m(again.width)} m` + : 'hung at the other jamb the leaf would leave the way clear' + })() + const approximate = way.by.some((o) => o.prism.shape === 'approx') + return { + type: 'usage_door_swing', + message: `${quote(nameOf(nodes, door.id))} open${angle < 90 ? ` to ${angle}°` : ''}: ${m(way.width)} m to enter ${quote(room.name)}, ${bound} (below ${m(PASSAGE_M)} m); ${instead}.`, + severity: 'warning', + nodeIds: unique([room.id, door.id, ...way.by.map((o) => o.prism.nodeId)]), + valueM: way.width, + thresholdM: PASSAGE_M, + place: { room: room.name, roomId: room.id, at: way.at }, + obstacles: way.by.map((o) => ({ + nodeId: o.prism.nodeId, + name: + o.prism.id === leaf.id + ? `the leaf of ${quote(nameOf(nodes, door.id))}` + : nameOf(nodes, o.prism.nodeId), + kind: o.prism.kind, + shape: o.prism.shape, + movable: false, + })), + approximate, + } + } + return { baseY, doors, roomBeyond, sweepOf, wayOf, rests, wayInIssue } +} + +type SwingReader = ReturnType + +/** + * Prefer the served side, then a leaf resting against a wall, but only among clear, fully opening hangings. + * Read the costly way-in measure down that ranking only until the first clear one. + */ +export function hangToClear( + reader: SwingReader, + door: DoorNode, + order: readonly [Hung, ...Hung[]], +): { hung: Hung; why: string } { + const failures = new Map() + const opening = order.flatMap((hung) => { + const { free } = reader.sweepOf(door, hung) + if (free >= OPENS_FULLY_DEG) return [{ hung, free, rests: reader.rests(door, hung) }] + failures.set(hung, `opens to ${free}° and no further`) + return [] + }) + const ranked = opening.sort( + (left, right) => + Number(right.hung.swing === order[0].swing) - Number(left.hung.swing === order[0].swing) || + Number(right.rests) - Number(left.rests), + ) + for (const { hung, free, rests } of ranked) { + const entry = reader.wayOf(door, hung, free) + const way = entry?.way + if (!way) { + const merit = entry + ? `its open leaf ${rests ? 'rests against a wall and ' : ''}leaves the way clear` + : `opens fully${rests ? ' with its leaf against a wall' : ''}; no closed room to measure the way in` + const first = failures.get(order[0]) + return { hung, why: first ? `${merit}; the first choice ${first}` : merit } + } + failures.set(hung, `leaves ${m(way.width)} m to enter the room`) + } + return { hung: order[0], why: 'no hanging opens fully and leaves the way clear' } +} + +/** + * A door's leaf swept from its closed position to 90 degrees about its hinge at the jamb, on the face of the wall + * it swings to, against the pieces, cabinets, fixtures, walls, the treads and landings of a stair that rise above the + * door's floor and the closed leaves of other doors: the first + * angle at which it is in something. Read on the real outlines; the leaf is a line, so it is as long as the opening + * is wide less the frame. A leaf that cannot open to 90 degrees is a finding; so is one that would open fully hung + * the other way, which the message says. A door that cannot open at all (its hinge in a corner wall's body) reads 0. + * A leaf stopped below `OPENS_FULLY_DEG` warns whatever outline its blocker has; an approximate + * outline keeps its uncertainty and the message says "about" for the angle. + * + * A door that does open fully has its open leaf, at the angle it stops at, as an obstacle on the way from + * the doorway into the room: a way under a passage's width that the leaf bounds is the second case of the + * finding (`wayIn`), with what hanging the leaf at the other jamb would leave. + */ +export function doorSwingIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { + const out: UsageIssue[] = [] + for (const level of shapes.levels) { + const { baseY, doors, sweepOf, wayInIssue } = swingReader(nodes, shapes, level) + + const found = new Map() + for (const door of doors) { + const hung = hungOf(door) + const here = sweepOf(door, hung) + if (here.free >= OPENS_FULLY_DEG) { + const way = wayInIssue(door, hung, here.free) + if (way) found.set(`${door.id}|way`, way) + } + if (here.by === null || here.free >= OPENS_FULLY_DEG) continue + const swung = sweepOf(door, { swing: -hung.swing as 1 | -1, hs: hung.hs }) + const hinged = sweepOf(door, { swing: hung.swing, hs: -hung.hs as 1 | -1 }) + const fixes = [ + swung.free >= OPENS_FULLY_DEG ? 'swings the other way' : null, + hinged.free >= OPENS_FULLY_DEG ? 'is hinged on the other side' : null, + ].filter((fix): fix is string => fix !== null) + const room = roomAt(nodes, level.levelId, here.pivot) + const approximate = here.by.prism.shape === 'approx' + const roughly = approximate && here.free > 0 + // a stair's lower face above the middle of the leaf is its underside (a soffit over the door), not a tread the leaf meets low down + const leafHeight = door.height ?? DEFAULT_DOOR_HEIGHT_M + const clearance = here.by.prism.z0 - baseY + const underside = here.by.kind === 'stair' && clearance >= leafHeight / 2 + const what = + here.by.kind === 'door' + ? `the leaf of ${quote(here.by.name)}` + : underside + ? `the underside of ${quote(here.by.name)} at ${m(clearance)} m, below the leaf's ${m(leafHeight)} m top` + : quote(here.by.name) + const key = `${door.id}|${here.by.prism.nodeId}` + if (found.has(key)) continue + found.set(key, { + type: 'usage_door_swing', + message: `${quote(nameOf(nodes, door.id))}${room ? ` in ${quote(room.name)}` : ''} ${here.free <= 0 ? 'cannot open: its leaf is against' : `opens to ${roughly ? 'about ' : ''}${here.free}° and no further: its leaf meets`} ${what}${here.by.kind === 'wall' ? (here.free <= SWEEP_STEP_DEG ? ' (a wall: the door stands too close to its corner)' : ' (a wall)') : here.by.kind === 'cabinet' ? ' (a cabinet)' : here.by.kind === 'fixture' ? ' (a fixture)' : here.by.kind === 'stair' && !underside ? ' (a stair)' : ''}${fixes.length ? `; it opens fully if it ${fixes.join(' or ')}` : '; it does not open fully hung either way'}.`, + severity: 'warning', + nodeIds: unique([room?.id, door.id, here.by.prism.nodeId]), + valueDeg: here.free, + thresholdDeg: 90, + place: { room: room?.name ?? '', roomId: room?.id ?? level.levelId, at: here.pivot }, + obstacles: [ + { + nodeId: here.by.prism.nodeId, + name: here.by.name, + kind: here.by.prism.kind, + shape: here.by.prism.shape, + movable: false, + }, + ], + approximate, + }) + } + out.push(...found.values()) + } + return out +} diff --git a/packages/core/src/spatial/usage-field/types.ts b/packages/core/src/spatial/usage-field/types.ts new file mode 100644 index 0000000000..442eebc69a --- /dev/null +++ b/packages/core/src/spatial/usage-field/types.ts @@ -0,0 +1,82 @@ +import type { Polygon, Ring } from '../../lib/polygon-boolean' + +export type { Polygon, Ring } + +/** + * What an obstacle is, for naming it in a finding and for the checks that look at one kind (a wall + * object's depth from its wall, a stair rail closing an arrival). + */ +export type PrismKind = + | 'wall' + | 'wall-trim' + | 'jamb' + | 'door-head' + | 'threshold' + | 'window-frame' + | 'sill' + | 'treatment' + | 'stair' + | 'stair-rail' + | 'guard' + | 'cabinet' + | 'item' + | 'column' + | 'shelf' + | 'void' + | 'other' + +/** + * A plan polygon between two heights, in the building's plan frame (x, z) and absolute building + * metres (y), so a stair that crosses a storey and the wall beside it are in one frame. Every + * obstacle the usage checks see is a union of these. `exact` means the + * outline and heights come from the node's own fields and the pure helper its renderer calls, pinned + * to the built mesh by a parity test; `approx` is a fallback (a bounds box, a head left out) and a + * finding that rests on it is informational. + */ +export type Prism = { + /** Stable within one scene: `#`. */ + id: string + nodeId: string + kind: PrismKind + z0: number + z1: number + outer: Ring + holes: Ring[] + shape: 'exact' | 'approx' + /** What made it approximate, for the finding's wording. */ + why?: string + /** Set for what is mounted on a wall, which the protrusion check measures from the wall's face. */ + host?: { wallId: string; face: 'a' | 'b' } +} + +/** A stretch of floor a person stands on, with its finished height in absolute building metres. */ +export type FloorRegion = { + id: string + nodeId: string + outer: Ring + holes: Ring[] + y: number + /** Outside the enclosed footprint: a terrace, a porch deck. */ + outdoor: boolean + shape: 'exact' | 'approx' + why?: string +} + +export type LevelShapes = { + levelId: string + prisms: Prism[] + floors: FloorRegion[] +} + +/** A node whose shape could not be read, with why; one such node never stops the others. */ +export type Skipped = { nodeId: string; why: string } + +export type UsageShapes = { + /** Prisms are filed under the level that owns the node: a stair under the level it starts from. */ + levels: LevelShapes[] + /** Node ids whose shape is approximate. */ + approximate: string[] + /** Kinds met on the way that contribute no shape, with how many nodes of each. */ + unshaped: Record + skipped: Skipped[] +} diff --git a/packages/core/src/spatial/usage-field/walls.test.ts b/packages/core/src/spatial/usage-field/walls.test.ts new file mode 100644 index 0000000000..8f0d583578 --- /dev/null +++ b/packages/core/src/spatial/usage-field/walls.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, test } from 'bun:test' +import { area } from '../../lib/polygon-boolean' +import { type AnyNode, BuildingNode, DoorNode, LevelNode, WallNode, WindowNode } from '../../schema' +import { type Nodes, wallBodies, wallTrims } from './walls' + +function scene(extra: AnyNode[] = []): Nodes { + const building = BuildingNode.parse({ id: 'building_1', children: ['level_1'] }) + const level = LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }) + return Object.fromEntries([building, level, ...extra].map((node) => [node.id, node])) as Nodes +} + +const wall = (over: Record = {}) => + WallNode.parse({ + id: 'wall_1', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + thickness: 0.1, + children: [], + ...over, + }) + +const door = (over: Record = {}) => + DoorNode.parse({ + id: 'door_1', + parentId: 'wall_1', + wallId: 'wall_1', + position: [3, 1.05, 0], + width: 0.9, + height: 2.1, + ...over, + }) + +const pieceArea = (pieces: { outer: [number, number][]; holes: [number, number][][] }[]) => + area(pieces.map(({ outer, holes }) => ({ outer, holes }))) + +describe('wall bodies', () => { + test('a plain wall is one prism over its footprint and height', () => { + const nodes = scene([wall()]) + const prisms = wallBodies(nodes, 'level_1') + expect(prisms).toHaveLength(1) + expect(prisms[0]!.kind).toBe('wall') + expect(prisms[0]!.z0).toBe(0) + expect(prisms[0]!.z1).toBeGreaterThan(2.4) + expect(pieceArea(prisms)).toBeCloseTo(6 * 0.1, 3) + }) + + test('a door takes its width out of the body and leaves a piece above its head', () => { + const w = wall({ children: ['door_1'] }) + const nodes = scene([w, door()]) + const prisms = wallBodies(nodes, 'level_1') + const body = prisms.filter((p) => p.id.endsWith('#body') || p.id.includes('#body.')) + expect(pieceArea(body)).toBeCloseTo((6 - 0.9) * 0.1, 3) + const above = prisms.filter((p) => p.id.includes('#above:door_1')) + expect(above).toHaveLength(1) + expect(above[0]!.z0).toBeCloseTo(2.1, 3) + expect(pieceArea(above)).toBeCloseTo(0.9 * 0.1, 3) + // nothing below a door that stands on the floor + expect(prisms.some((p) => p.id.includes('#below:'))).toBe(false) + }) + + test('a window leaves a piece below its sill and above its head', () => { + const w = wall({ children: ['window_1'] }) + const win = WindowNode.parse({ + id: 'window_1', + parentId: 'wall_1', + wallId: 'wall_1', + position: [3, 1.5, 0], + width: 1.2, + height: 1.2, + }) + const prisms = wallBodies(scene([w, win]), 'level_1') + const below = prisms.find((p) => p.id.includes('#below:window_1'))! + const above = prisms.find((p) => p.id.includes('#above:window_1'))! + expect(below.z0).toBe(0) + expect(below.z1).toBeCloseTo(0.9, 3) + expect(above.z0).toBeCloseTo(2.1, 3) + }) +}) + +describe('wall trims', () => { + test('a skirting stands out of its face by its profile and stops at a door', () => { + const w = wall({ + children: ['door_1'], + skirting: { enabled: true, sides: 'a', height: 0.12, proud: 0.02, profile: 'flat' }, + }) + const { prisms } = wallTrims(scene([w, door()]), 'level_1') + expect(prisms.length).toBeGreaterThan(0) + expect(prisms.every((p) => p.kind === 'wall-trim' && p.host?.face === 'a')).toBe(true) + // flat profile: the widest sample is 0.9 of proud + const ys = prisms.flatMap((p) => p.outer.map(([, z]) => z)) + expect(Math.max(...ys.map(Math.abs))).toBeCloseTo(0.05 + 0.02 * 0.9, 3) + // the door's 0.9 m is left out of the 6 m run + expect(pieceArea(prisms)).toBeCloseTo((6 - 0.9 - 2 * 0) * 0.018, 2) + }) + + test('a wall with no trim enabled adds none', () => { + expect(wallTrims(scene([wall()]), 'level_1').prisms).toHaveLength(0) + }) +}) diff --git a/packages/core/src/spatial/usage-field/walls.ts b/packages/core/src/spatial/usage-field/walls.ts new file mode 100644 index 0000000000..6b141f1ebd --- /dev/null +++ b/packages/core/src/spatial/usage-field/walls.ts @@ -0,0 +1,199 @@ +import { getOpeningWallCut, wallSupportForNodes } from '../../lib/opening-floor-datum' +import { difference, intersection, type MultiPolygon, union } from '../../lib/polygon-boolean' +import { wallFaceBaseOffset } from '../../lib/wall-face-script' +import type { AnyNode, DoorNode, WallNode, WindowNode } from '../../schema' +import { + getWallTrimFaces, + WALL_TRIM_DEFAULTS, + type WallFace, + type WallTrimConfig, + type WallTrimKind, +} from '../../schema/nodes/wall' +import { getWallTop } from '../../services/storey' +import { isCurvedWall } from '../../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../../systems/wall/wall-footprint' +import { getWallFaceLine } from '../../systems/wall/wall-frame' +import { TRIM_PROFILES } from '../../systems/wall/wall-trim-profiles' +import type { Prism, Ring } from './types' + +export type Nodes = Readonly> + +/** Lengths below this are rounding, not geometry: a piece thinner than it is not an obstacle. */ +const MIN_PIECE_M = 0.005 +/** The wall's trims are drawn in slices of at least this projection (`MIN_SLICE_PROUD` in the trim builder). */ +const MIN_SLICE_PROUD = 0.0005 + +export const isOpening = (node: AnyNode | undefined): node is DoorNode | WindowNode => + node?.type === 'door' || node?.type === 'window' + +export function levelWalls(nodes: Nodes, levelId: string): WallNode[] { + return Object.values(nodes) + .filter( + (node): node is WallNode => + node.type === 'wall' && node.parentId === levelId && node.visible !== false, + ) + .sort((a, b) => a.id.localeCompare(b.id)) +} + +const toRing = (points: readonly { x: number; y: number }[]): Ring => + points.map(({ x, y }) => [x, y] as [number, number]) + +function pushPieces( + out: Prism[], + pieces: MultiPolygon, + base: Omit & { id: string }, +) { + for (const [index, piece] of pieces.entries()) + out.push({ + ...base, + id: `${base.id}${pieces.length > 1 ? `.${index}` : ''}`, + outer: piece.outer, + holes: piece.holes, + }) +} + +/** + * The wall bodies of one level: each wall's mitred footprint over its height, less the bands its + * doors and windows cut, with the pieces left below a sill and above a head. Heights are level-local: + * from the wall's elected base (`wallSupportForNodes`) to its top (`getWallTop`), the same two + * numbers the wall renderer reads. + */ +export function wallBodies( + nodes: Nodes, + levelId: string, + walls = levelWalls(nodes, levelId), +): Prism[] { + const out: Prism[] = [] + const miters = calculateLevelMiters(walls) + for (const wall of walls) { + const footprint = toRing(getWallPlanFootprint(wall, miters)) + if (footprint.length < 3) continue + const support = wallSupportForNodes(wall, nodes) + const base = support.elevation + const top = getWallTop(wall, levelId, nodes as never, base) + if (!(top - base > MIN_PIECE_M)) continue + const cuts = (wall.children ?? []) + .map((id) => nodes[id]) + .filter(isOpening) + .map((opening) => ({ opening, cut: getOpeningWallCut(wall, opening, nodes, support) })) + .filter(({ cut }) => cut.band.length >= 3) + const bands = cuts.length ? union(cuts.map(({ cut }) => cut.band)) : [] + const common = { nodeId: wall.id, kind: 'wall' as const, shape: 'exact' as const } + pushPieces(out, difference(footprint, bands), { + ...common, + id: `${wall.id}#body`, + z0: base, + z1: top, + }) + for (const { opening, cut } of cuts) { + const inBand = intersection(footprint, cut.band) + if (cut.bottom - base > MIN_PIECE_M) + pushPieces(out, inBand, { + ...common, + id: `${wall.id}#below:${opening.id}`, + z0: base, + z1: Math.min(cut.bottom, top), + }) + if (top - cut.top > MIN_PIECE_M) + pushPieces(out, inBand, { + ...common, + id: `${wall.id}#above:${opening.id}`, + z0: Math.max(cut.top, base), + z1: top, + }) + } + } + return out +} + +/** How far a trim stands out, at most, over its height: the profile's own samples, as the trim builder cuts them. */ +export function trimProjection(kind: WallTrimKind, trim: WallTrimConfig): number { + const profile = + TRIM_PROFILES[kind][trim.profile] ?? + TRIM_PROFILES[kind][WALL_TRIM_DEFAULTS[kind].profile] ?? + TRIM_PROFILES[kind].flat + if (!profile) return trim.proud + let widest = MIN_SLICE_PROUD + for (let index = 0; index < profile.samples; index += 1) + widest = Math.max(widest, trim.proud * profile.proudAt((index + 0.5) / profile.samples)) + return widest +} + +const TRIM_KINDS: WallTrimKind[] = ['skirting', 'crown', 'chairRail'] + +/** + * A wall's skirting, chair rail and crown as thin prisms standing on the faces they are drawn on, + * cut where a door opens through their height. Straight walls only: a curved wall's trim is left + * out and the wall named in `skipped`. + */ +export function wallTrims( + nodes: Nodes, + levelId: string, + walls = levelWalls(nodes, levelId), +): { prisms: Prism[]; skipped: string[] } { + const prisms: Prism[] = [] + const skipped: string[] = [] + for (const wall of walls) { + const configs = TRIM_KINDS.flatMap((kind) => { + const trim = { ...WALL_TRIM_DEFAULTS[kind], ...(wall[kind] ?? {}) } as WallTrimConfig + return trim.enabled ? [{ kind, trim }] : [] + }) + if (!configs.length) continue + if (isCurvedWall(wall)) { + skipped.push(wall.id) + continue + } + const support = wallSupportForNodes(wall, nodes) + const top = getWallTop(wall, levelId, nodes as never, support.elevation) + const openings = (wall.children ?? []) + .map((id) => nodes[id]) + .filter(isOpening) + .map((opening) => ({ opening, cut: getOpeningWallCut(wall, opening, nodes, support) })) + .filter(({ cut }) => cut.band.length >= 3) + for (const { kind, trim } of configs) { + const proud = trimProjection(kind, trim) + for (const face of getWallTrimFaces(trim.sides) as WallFace[]) { + const line = getWallFaceLine(wall, face) + const dx = line.end.x - line.start.x + const dz = line.end.y - line.start.y + const length = Math.hypot(dx, dz) + if (length < 1e-9) continue + // face a is the wall's left (+normal), b its right + const sign = face === 'a' ? 1 : -1 + const nx = (-dz / length) * sign * proud + const nz = (dx / length) * sign * proud + const strip: Ring = [ + [line.start.x, line.start.y], + [line.end.x, line.end.y], + [line.end.x + nx, line.end.y + nz], + [line.start.x + nx, line.start.y + nz], + ] + const floor = support.elevation + wallFaceBaseOffset(support, face) + const z0 = + kind === 'crown' + ? top - trim.height + : kind === 'chairRail' + ? floor + (trim.offsetY ?? 0) + : floor + const z1 = z0 + trim.height + // a door opens through the trim's height where its own span meets it: the trim stops at the jambs + const crossing = openings + .filter(({ cut }) => cut.bottom < z1 && cut.top > z0) + .map(({ cut }) => cut.band) + const pieces = crossing.length + ? difference(strip, union(crossing)) + : [{ outer: strip, holes: [] }] + pushPieces(prisms, pieces, { + id: `${wall.id}#${kind}.${face}`, + nodeId: wall.id, + kind: 'wall-trim', + z0, + z1, + shape: 'exact', + host: { wallId: wall.id, face }, + }) + } + } + } + return { prisms, skipped } +} diff --git a/packages/core/src/spatial/usage-field/way-in.ts b/packages/core/src/spatial/usage-field/way-in.ts new file mode 100644 index 0000000000..b74d5ecf0b --- /dev/null +++ b/packages/core/src/spatial/usage-field/way-in.ts @@ -0,0 +1,150 @@ +import { polygonInteriorPoint } from '../../lib/polygon-label' +import { cellOf, cellX, cellZ } from './field' +import { PASSAGE_M, TOLERANCE_M } from './findings' +import { BODY_BAND, buildField, inRegion, maskOf } from './level-field' +import { boundingObstacles, type Obstacle, passagePair } from './obstacles' +import { pathTo, refinePassage, widestPath } from './path' +import type { FloorRegion, LevelShapes, Prism, Ring, UsageShapes } from './types' + +type Point = [number, number] + +/** Grid step of the local field; the pinch is then solved to the millimetre, as a passage is. */ +const CELL_M = 0.05 +/** The way is read inside this radius of where it starts: a leaf and a passage's width past its tip, or the first metres of a room. */ +const REACH_M = 3 + +export type Way = { + /** The clear width of the best way from the entrance to the room's open floor. */ + width: number + at: Point + /** The two things that bound the pinch. */ + by: Obstacle[] +} + +/** + * The best way from an entrance into the room it leads to: the widest path (as the passage measure reads + * one) from the entrance's opening (`entrance`, a ring across a doorway or an open edge) to the room's + * open floor, the cells where a disc of a passage's width fits. `leaf` is a line (a door's leaf standing + * open) added to what stands in the way. The entrance's own clear width caps that path, and an entrance is + * measured elsewhere, so a way is only returned when it is under a passage's width and `bounds` holds of + * one of the two things that bound its pinch. Null otherwise: the way is clear, or what narrows it is not + * what the caller asks about. + */ +export function wayIn( + shapes: UsageShapes, + level: LevelShapes, + zone: { id: string; polygon: Ring; holes?: Ring[] }, + entrance: Ring, + around: Point, + floorY: number, + underlay: (prism: Prism) => boolean, + bounds: (prism: Prism) => boolean, + leaf: Prism | null = null, +): Way | null { + const ring = entrance + const holes = (zone.holes ?? []) as FloorRegion['holes'] + const region = { outer: zone.polygon as FloorRegion['outer'], holes } + const probe = polygonInteriorPoint({ polygon: zone.polygon, holes: zone.holes }, true) + const y = level.floors.find((floor) => inRegion(probe[0], probe[1], floor))?.y ?? floorY + const [hx, hz] = around + const zx = region.outer.map((p) => p[0]) + const zz = region.outer.map((p) => p[1]) + const domain: [number, number, number, number] = [ + Math.max(hx - REACH_M, Math.min(...zx) - 0.2), + Math.max(hz - REACH_M, Math.min(...zz) - 0.2), + Math.min(hx + REACH_M, Math.max(...zx) + 0.2), + Math.min(hz + REACH_M, Math.max(...zz) + 0.2), + ] + // the prisms near the room only: the field builder makes an obstacle of every prism before it looks where it is + const near = (prism: Prism) => { + let x0 = Number.POSITIVE_INFINITY + let z0 = Number.POSITIVE_INFINITY + let x1 = Number.NEGATIVE_INFINITY + let z1 = Number.NEGATIVE_INFINITY + for (const [x, z] of prism.outer) { + x0 = Math.min(x0, x) + x1 = Math.max(x1, x) + z0 = Math.min(z0, z) + z1 = Math.max(z1, z) + } + return !(x1 < domain[0] || x0 > domain[2] || z1 < domain[1] || z0 > domain[3]) + } + const field = buildField( + { + ...shapes, + levels: shapes.levels.map((l) => ({ ...l, prisms: l.prisms.filter(near) })), + }, + { + levelId: '', + y, + regions: [{ id: zone.id, nodeId: zone.id, ...region, y, outdoor: false, shape: 'exact' }], + domain, + }, + BODY_BAND, + CELL_M, + underlay, + leaf ? [leaf] : [], + ) + const { grid, F, floor } = field + if (leaf) { + // a line is no wall to a grid path, which steps between the cells either side of it: the cells it runs through are shut + const [from, tip] = leaf.outer as [Point, Point] + const reach = Math.hypot(tip[0] - from[0], tip[1] - from[1]) + for (let s = 0; s <= reach; s += CELL_M / 4) { + const c = cellOf( + grid, + from[0] + ((tip[0] - from[0]) * s) / reach, + from[1] + ((tip[1] - from[1]) * s) / reach, + ) + if (c >= 0) F[c] = 0 + } + } + const doorway = maskOf(grid, [{ outer: ring, holes: [] }]) + const plate = Uint8Array.from(floor) + const sources: number[] = [] + for (let c = 0; c < doorway.length; c++) + if (doorway[c]) { + plate[c] = 1 + if (F[c]! > 0) sources.push(c) + } + if (sources.length === 0) return null + const sourceSet = new Set(sources) + const widest = widestPath(grid, F, plate, sources) + const open = (PASSAGE_M - TOLERANCE_M) / 2 + let best = -1 + for (let c = 0; c < floor.length; c++) + if ( + floor[c] && + F[c]! >= open && + widest.B[c]! > Number.NEGATIVE_INFINITY && + (best < 0 || widest.B[c]! > widest.B[best]!) + ) + best = c + if (best < 0) return null + // the grid is within a cell of the millimetre figure: a way a cell over the limit is not narrow + if (2 * widest.B[best]! > PASSAGE_M + 2 * CELL_M) return null + + const path = pathTo(widest.P, F, best) + const refined = refinePassage( + grid, + F, + field.index, + path, + (c) => sourceSet.has(c), + (x, z) => inRegion(x, z, region), + ) + // what bounds the way is read where the path is narrowest, not where the refinement says a cell of that clearance is + const narrowest = path.cells[path.narrowest]! + const here: Point = [cellX(grid, narrowest % grid.W), cellZ(grid, (narrowest / grid.W) | 0)] + const grided = 2 * F[narrowest]! + const pair = passagePair(field.obstacles, here[0], here[1]) + const exact = pair !== null && Math.abs(pair.width - refined.width) < 0.02 + const width = exact ? pair.width : Math.min(refined.width, grided + 2 * grid.h) + if (!(width < PASSAGE_M - TOLERANCE_M)) return null + const by = exact + ? [pair.a, pair.b] + : boundingObstacles(field.obstacles, here[0], here[1], width / 2) + const at: Point = exact ? [(pair.pa[0] + pair.pb[0]) / 2, (pair.pa[1] + pair.pb[1]) / 2] : here + if (!by.some((o) => bounds(o.prism))) return null + return { width: Math.round(width * 1000) / 1000, at, by } +} diff --git a/packages/core/src/systems/fence/guard-layout.ts b/packages/core/src/systems/fence/guard-layout.ts new file mode 100644 index 0000000000..7d68415b8e --- /dev/null +++ b/packages/core/src/systems/fence/guard-layout.ts @@ -0,0 +1,251 @@ +import type { FenceNode } from '../../schema' +import { getFenceCenterlineFrameAt, getFenceCenterlineLength } from './fence-centerline' + +/** Dressed lumber the guard is built from, metres. */ +const IN = 0.0254 +const GUARD_CAP_T = 1.5 * IN +const GUARD_CAP_W = 5.5 * IN +const GUARD_RAIL_T = 1.5 * IN +const GUARD_RAIL_D = 3.5 * IN +const GUARD_BALUSTER = 1.5 * IN +const GUARD_BOARD_D = 5.5 * IN +const GUARD_CABLE = 0.5 * IN +const GUARD_POST_ABOVE_CAP = 3 * IN +const GUARD_POST_CAP_T = 1 * IN + +/** A box standing on the fence's base: its centre, the turn about the vertical axis, its size along its own axes. */ +export type GuardPost = { + position: [number, number, number] + rotationY: number + scale: [number, number, number] + /** A 4-sided cone, square base aligned to the box. */ + shape?: 'pyramid' +} + +/** + * A run along the centreline between two fractions of its length, `depth` across it, `height` tall + * round `centerY`. `split` runs are cut into short segments so a curved fence bends them. + */ +export type GuardBlock = { + startT: number + endT: number + centerY: number + height: number + depth: number + split: boolean +} + +export type GuardLayout = { + posts: GuardPost[] + /** The cap rail flat over the posts and the top rail on edge under it. */ + rail: GuardBlock[] + /** The bottom rail the balusters stand on (balusters only). */ + base: GuardBlock[] + /** Balusters, cables or boards. */ + infill: GuardBlock[] +} + +type Frame = { x: number; z: number; angle: number } + +function frameAt(fence: FenceNode, t: number): Frame { + const { point, tangent } = getFenceCenterlineFrameAt(fence, t) + return { x: point.x, z: point.y, angle: Math.atan2(tangent.y, tangent.x) } +} + +/** + * A deck guard the way the AWC Deck Construction Guide (DCA 6) draws one: 4x4 posts (`postSize`) no + * more than `postSpacing` apart, the two ends counted as posts whether drawn or not (`startPost` / + * `endPost` false: the rails die into a post already standing there), a 2x6 cap rail flat over the + * posts, a 2x4 top rail on edge under it, and the infill: balusters (2x2 on a 2x4 bottom rail + * `groundClearance` over the deck, `slatGap` clear), cable (½ in runs `slatGap` apart from + * `groundClearance` up), or boards (`thickness` x 5½ in, `slatGap` apart from `groundClearance` + * up). `postThrough` runs the posts 3 in past the cap under a cap of their own (`postCap`). + * + * The pure layout the guard renderer builds its meshes from and the usage field reads its + * obstacles from, so the two cannot disagree. + */ +export function layoutGuardFence(fence: FenceNode): GuardLayout { + const posts: GuardPost[] = [] + const infill: GuardBlock[] = [] + const base: GuardBlock[] = [] + const rail: GuardBlock[] = [] + const length = Math.max(getFenceCenterlineLength(fence), 0.01) + const H = Math.max(fence.height, 0.4) + const postW = Math.max(fence.postSize, 0.02) + const clearance = Math.max(fence.groundClearance, 0) + const gap = Math.max(fence.slatGap ?? 0.09, 0.01) + const infillKind = fence.guardInfill ?? 'balusters' + const through = fence.postThrough === true + const capTop = H + const capBottom = H - GUARD_CAP_T + const topRailBottom = capBottom - GUARD_RAIL_D + const bays = Math.max(1, Math.ceil(length / Math.max(fence.postSpacing, postW * 2))) + const stations: number[] = [] + for (let i = 0; i <= bays; i++) stations.push(i / bays) + + // posts: to the cap's underside, or through it with a cap + const postH = through ? capTop + GUARD_POST_ABOVE_CAP : capBottom + for (const [i, t] of stations.entries()) { + if (i === 0 && fence.startPost === false) continue + if (i === stations.length - 1 && fence.endPost === false) continue + const frame = frameAt(fence, t) + posts.push({ + position: [frame.x, postH / 2, frame.z], + rotationY: -frame.angle, + scale: [postW, postH, postW], + }) + if (through && (fence.postCap ?? 'flat') !== 'none') { + const cap = fence.postCap ?? 'flat' + if (cap === 'pyramid') { + posts.push({ + position: [frame.x, postH + postW * 0.45, frame.z], + rotationY: -frame.angle, + scale: [postW * 1.18, postW * 0.9, postW * 1.18], + shape: 'pyramid', + }) + } else { + posts.push({ + position: [frame.x, postH + GUARD_POST_CAP_T / 2, frame.z], + rotationY: -frame.angle, + scale: [postW + 2 * IN, GUARD_POST_CAP_T, postW + 2 * IN], + }) + } + } + } + + const run = (centerY: number, height: number, depth: number): GuardBlock => ({ + startT: 0, + endT: 1, + centerY, + height, + depth, + split: true, + }) + rail.push(run(capBottom + GUARD_CAP_T / 2, GUARD_CAP_T, GUARD_CAP_W)) + rail.push(run(topRailBottom + GUARD_RAIL_D / 2, GUARD_RAIL_D, GUARD_RAIL_T)) + + const postHalfT = postW / 2 / length + const clearOfPosts = (t: number, halfT: number) => + !stations.some((s) => Math.abs(s - t) < postHalfT + halfT) + + if (infillKind === 'balusters') { + // the 2x4 bottom rail `clearance` over the deck, the balusters on it + const bottomRailTop = clearance + GUARD_RAIL_D + base.push(run(clearance + GUARD_RAIL_D / 2, GUARD_RAIL_D, GUARD_RAIL_T)) + const balH = Math.max(topRailBottom - bottomRailTop, 0.05) + const pitch = GUARD_BALUSTER + gap + const halfT = GUARD_BALUSTER / 2 / length + for (let s = pitch; s < length - GUARD_BALUSTER; s += pitch) { + const t = s / length + if (!clearOfPosts(t, halfT)) continue + if (2 * halfT <= 1e-5) continue + infill.push({ + startT: t - halfT, + endT: t + halfT, + centerY: bottomRailTop + balH / 2, + height: balH, + depth: GUARD_BALUSTER, + split: false, + }) + } + } else if (infillKind === 'cable') { + // ½ in cables `gap` apart from `clearance` up to under the top rail + for (let y = clearance; y < topRailBottom - GUARD_CABLE; y += gap) + infill.push(run(y + GUARD_CABLE / 2, GUARD_CABLE, GUARD_CABLE)) + } else { + // boards `gap` apart from `clearance` up to under the top rail + const boardT = Math.max(fence.thickness, 0.012) + for (let y = clearance; y + GUARD_BOARD_D <= topRailBottom + 1e-6; y += GUARD_BOARD_D + gap) + infill.push(run(y + GUARD_BOARD_D / 2, GUARD_BOARD_D, boardT)) + } + + return { posts, infill, base, rail } +} + +/** + * The fractions a run between `startT` and `endT` is cut at: segments no longer than + * `maxSegmentLength`, so a curved fence bends them. + */ +export function fenceBlockSegments( + fence: FenceNode, + startT: number, + endT: number, + maxSegmentLength: number, +): [number, number][] { + const length = getFenceCenterlineLength(fence) * Math.max(1e-4, endT - startT) + const count = Math.max(1, Math.ceil(length / Math.max(1e-4, maxSegmentLength))) + return Array.from({ length: count }, (_, index) => [ + startT + (endT - startT) * (index / count), + startT + (endT - startT) * ((index + 1) / count), + ]) +} + +type Corner = [number, number] + +/** + * The four plan corners of a run between `startT` and `endT`, `depth` across the centreline and + * shifted `lateralOffset` to the side the frame's normal points: the outer then the inner corner at + * the start, then at the end. + */ +export function fenceBlockCorners( + fence: FenceNode, + startT: number, + endT: number, + depth: number, + lateralOffset = 0, +): [Corner, Corner, Corner, Corner] { + const half = depth / 2 + const at = (t: number): [Corner, Corner] => { + const frame = frameAt(fence, t) + const nx = -Math.sin(frame.angle) + const nz = Math.cos(frame.angle) + return [ + [frame.x + nx * (half + lateralOffset), frame.z + nz * (half + lateralOffset)], + [frame.x - nx * (half - lateralOffset), frame.z - nz * (half - lateralOffset)], + ] + } + const [startOuter, startInner] = at(startT) + const [endOuter, endInner] = at(endT) + return [startOuter, startInner, endOuter, endInner] +} + +/** + * Where a run's end moves to when its fence meets `neighbor` at a corner: the two end corners slide + * along the fence so the run meets the neighbour's in a mitre. `side` is -1 for the inner corner and + * 1 for the outer, `reach` the metres along the unit vector `(ux, uz)`; null where the two run + * nearly straight on, or the mitre would reach absurdly far. + */ +export function fenceMiter( + fence: FenceNode, + endpoint: 'start' | 'end', + neighbor: FenceNode, + depth: number, + lateralOffset = 0, +): { side: -1 | 1; reach: number; ux: number; uz: number }[] | null { + const point = fence[endpoint] + const frame = getFenceCenterlineFrameAt(fence, endpoint === 'start' ? 0 : 1) + const sign = endpoint === 'start' ? 1 : -1 + const ux = frame.tangent.x * sign + const uz = frame.tangent.y * sign + const neighborAtStart = + Math.hypot(neighbor.start[0] - point[0], neighbor.start[1] - point[1]) < 0.001 + const other = getFenceCenterlineFrameAt(neighbor, neighborAtStart ? 0 : 1) + const vx = other.tangent.x * (neighborAtStart ? 1 : -1) + const vz = other.tangent.y * (neighborAtStart ? 1 : -1) + const cross = ux * vz - uz * vx + if (Math.abs(cross) < 0.15) return null + const ratio = Math.max(neighbor.thickness, 0.03) / Math.max(fence.thickness, 0.03) + const out: { side: -1 | 1; reach: number; ux: number; uz: number }[] = [] + for (const side of [-1, 1] as const) { + const offset = lateralOffset + (side * depth) / 2 + const neighborOffset = -offset * sign * ratio + const nx = -uz * offset * sign + const nz = ux * offset * sign + const mx = -vz * neighborOffset + const mz = vx * neighborOffset + const reach = ((mx - nx) * vz - (mz - nz) * vx) / cross + if (Math.abs(reach) > Math.max(depth, depth * ratio) * 4) continue + out.push({ side, reach, ux, uz }) + } + return out +} diff --git a/packages/core/src/systems/stair/stair-clearance.ts b/packages/core/src/systems/stair/stair-clearance.ts index 6fc54e4763..1e656a65ec 100644 --- a/packages/core/src/systems/stair/stair-clearance.ts +++ b/packages/core/src/systems/stair/stair-clearance.ts @@ -50,7 +50,8 @@ function detailError(stair: StairNode, nodes: Record) { ).error } -function sourceFrame(stair: StairNode, nodes: Record) { +/** The level a stair starts from, with its absolute base elevation (building Y of the stair's origin). */ +export function stairSourceFrame(stair: StairNode, nodes: Record) { const levels = getLevelElevations(nodes as Record) const sourceId = nodes[stair.fromLevelId ?? '']?.type === 'level' @@ -167,7 +168,7 @@ export function resolveStairWalkingSurfaces( if (error) throw new RangeError(error) if (countSurfaces(stair, nodes) > MAX_CLEARANCE_SURFACES) throw new RangeError('Detailed stair clearance exceeds the surface query budget') - const frame = sourceFrame(stair, nodes) + const frame = stairSourceFrame(stair, nodes) const point = (x: number, z: number): [number, number] => { const [dx, dz] = rotateXZ(x, z, stair.rotation) return [stair.position[0] + dx, stair.position[2] + dz] @@ -454,7 +455,7 @@ export function measureStairHeadroom( }) if (detailError(stair, nodes) || countSurfaces(stair, nodes) > MAX_CLEARANCE_SURFACES) return unresolved() - const frame = sourceFrame(stair, nodes) + const frame = stairSourceFrame(stair, nodes) const walking = resolveStairWalkingSurfaces(stair, nodes) const obstacles: { nodeId: string @@ -483,7 +484,7 @@ export function measureStairHeadroom( let surfaceCount = walking.length for (const other of Object.values(nodes)) { if (other.type !== 'stair' || other.id === stair.id || !visible(other, nodes)) continue - if (sourceFrame(other, nodes).buildingId !== frame.buildingId) continue + if (stairSourceFrame(other, nodes).buildingId !== frame.buildingId) continue if (detailError(other, nodes)) return unresolved() surfaceCount += countSurfaces(other, nodes) if (surfaceCount > MAX_CLEARANCE_SURFACES) return unresolved() diff --git a/packages/core/src/systems/wall/wall-trim-profiles.ts b/packages/core/src/systems/wall/wall-trim-profiles.ts new file mode 100644 index 0000000000..d6a7762d82 --- /dev/null +++ b/packages/core/src/systems/wall/wall-trim-profiles.ts @@ -0,0 +1,189 @@ +import type { WallTrimKind, WallTrimProfile } from '../../schema/nodes/wall' + +/** + * How a wall trim stands out across its height: `proudAt(t)` is the share of the trim's `proud` + * at height fraction `t` (0 at its bottom edge, 1 at its top), sampled `samples` times. Pure data + * for the wall's skirting, crown and chair rail and for the mouldings of an opening's surround. + */ +export type TrimProfileDefinition = { + samples: number + proudAt: (t: number) => number +} + +function clamp01(value: number) { + return Math.max(0, Math.min(1, value)) +} + +function eased(value: number) { + const t = clamp01(value) + return t * t * (3 - 2 * t) +} + +export const TRIM_PROFILES: Record< + WallTrimKind, + Partial> +> = { + skirting: { + flat: { + samples: 8, + proudAt: (t) => (t < 0.72 ? 0.62 : 0.9), + }, + bevel: { + samples: 10, + proudAt: (t) => 0.48 + 0.42 * eased(t), + }, + triangle: { + samples: 10, + proudAt: (t) => 0.32 + 0.68 * (1 - t), + }, + cove: { + samples: 12, + proudAt: (t) => 0.45 + 0.42 * Math.sin(t * Math.PI * 0.5), + }, + bullnose: { + samples: 12, + proudAt: (t) => 0.35 + 0.65 * Math.sin(Math.PI * t), + }, + 'base-modern': { + samples: 10, + proudAt: (t) => { + if (t < 0.16) return 0.85 + if (t < 0.72) return 0.58 + if (t < 0.9) return 1 + return 0.62 + }, + }, + 'base-colonial': { + samples: 14, + proudAt: (t) => { + if (t < 0.16) return 0.82 + if (t < 0.55) return 0.52 + const capT = (t - 0.55) / 0.45 + return 0.58 + 0.4 * Math.sin(capT * Math.PI) + }, + }, + 'base-shoe': { + samples: 14, + proudAt: (t) => { + const quarterRound = Math.sqrt(Math.max(0, 1 - t * t)) + return 0.28 + 0.72 * quarterRound + }, + }, + 'base-ogee': { + samples: 16, + proudAt: (t) => { + const ogee = 0.5 - 0.5 * Math.cos(Math.PI * t) + const bead = 0.16 * Math.sin(2 * Math.PI * t) + return clamp01(0.42 + 0.5 * ogee + bead) + }, + }, + }, + crown: { + flat: { + samples: 8, + proudAt: (t) => (t < 0.2 ? 0.52 : t < 0.82 ? 0.78 : 1), + }, + bevel: { + samples: 10, + proudAt: (t) => 0.45 + 0.55 * eased(t), + }, + triangle: { + samples: 10, + proudAt: (t) => 0.35 + 0.65 * t, + }, + cove: { + samples: 14, + proudAt: (t) => 0.46 + 0.45 * Math.sin(t * Math.PI * 0.5), + }, + bullnose: { + samples: 14, + proudAt: (t) => 0.38 + 0.62 * Math.sin(Math.PI * t * 0.5), + }, + 'crown-cove': { + samples: 16, + proudAt: (t) => { + if (t < 0.12) return 0.48 + if (t > 0.9) return 1 + return 0.46 + 0.48 * Math.sin(((t - 0.12) / 0.78) * Math.PI * 0.5) + }, + }, + 'crown-ogee': { + samples: 18, + proudAt: (t) => { + const sCurve = 0.5 - 0.5 * Math.cos(Math.PI * t) + const reverse = 0.18 * Math.sin(2 * Math.PI * (t - 0.12)) + return clamp01(0.42 + 0.55 * sCurve + reverse) + }, + }, + 'crown-craftsman': { + samples: 10, + proudAt: (t) => { + if (t < 0.16) return 0.48 + if (t < 0.4) return 0.88 + if (t < 0.78) return 0.64 + return 1 + }, + }, + 'crown-layered': { + samples: 14, + proudAt: (t) => { + if (t < 0.12) return 0.46 + if (t < 0.28) return 0.82 + if (t < 0.48) return 0.56 + if (t < 0.72) return 0.9 + return 1 + }, + }, + }, + chairRail: { + flat: { + samples: 8, + proudAt: (t) => (t < 0.18 || t > 0.82 ? 0.58 : 0.95), + }, + bevel: { + samples: 10, + proudAt: (t) => 0.45 + 0.45 * Math.sin(Math.PI * t), + }, + triangle: { + samples: 10, + proudAt: (t) => 0.35 + 0.65 * (1 - Math.abs(2 * t - 1)), + }, + cove: { + samples: 12, + proudAt: (t) => 0.42 + 0.42 * Math.sin(Math.PI * t), + }, + bullnose: { + samples: 14, + proudAt: (t) => 0.34 + 0.66 * Math.sin(Math.PI * t), + }, + 'rail-rounded': { + samples: 14, + proudAt: (t) => 0.34 + 0.66 * Math.sin(Math.PI * t), + }, + 'rail-ogee': { + samples: 16, + proudAt: (t) => { + const center = Math.sin(Math.PI * t) + const twist = 0.14 * Math.sin(2 * Math.PI * t) + return clamp01(0.36 + 0.58 * center + twist) + }, + }, + 'rail-picture': { + samples: 12, + proudAt: (t) => { + if (t < 0.18) return 0.48 + if (t < 0.4) return 0.92 + if (t < 0.74) return 0.58 + return 1 + }, + }, + 'rail-stepped': { + samples: 10, + proudAt: (t) => { + if (t < 0.22) return 0.55 + if (t < 0.78) return 1 + return 0.62 + }, + }, + }, +} diff --git a/packages/editor/src/lib/geometry-script/client.ts b/packages/editor/src/lib/geometry-script/client.ts index 71896486cb..fdfc87e384 100644 --- a/packages/editor/src/lib/geometry-script/client.ts +++ b/packages/editor/src/lib/geometry-script/client.ts @@ -1,4 +1,5 @@ import type { GeometryScriptParamValue } from '@pascal-app/core' +import { sdfChecksOn } from '@pascal-app/core/usage-field' import type { GeometryScriptCompileOutput } from '@pascal-app/geometry-script' import type { GeometryScriptWorkerRequest, GeometryScriptWorkerResponse } from './protocol' @@ -148,6 +149,8 @@ export async function compileGeometryScriptInWorker(input: { code: input.code, params: input.params, inputs: input.inputs, + // the sandbox is its own context: the flag travels with the request, only when it is on + ...(sdfChecksOn() ? { usageShape: true } : {}), } return new Promise((resolve, reject) => { const timeout = setTimeout(() => { diff --git a/packages/geometry-script/src/blender.ts b/packages/geometry-script/src/blender.ts index a1489fbbf9..1b3bedac4e 100644 --- a/packages/geometry-script/src/blender.ts +++ b/packages/geometry-script/src/blender.ts @@ -87,6 +87,7 @@ export async function compileBlenderBuild(input: { code: string params?: Record run: BlenderRun + usageShape?: boolean }): Promise { assertScriptSize(input.code) const mount = (input.run.mount ?? 'floor') as GeometryScriptMount @@ -102,5 +103,13 @@ export async function compileBlenderBuild(input: { restoreNames(gltf.scene, gltf.animations) const built = gltf.scene built.animations = gltf.animations - return finishBuild({ built, mount, specs, params, code: input.code, language: 'bpy' }) + return finishBuild({ + built, + mount, + specs, + params, + code: input.code, + language: 'bpy', + usageShape: input.usageShape, + }) } diff --git a/packages/geometry-script/src/compile.ts b/packages/geometry-script/src/compile.ts index bc7bcd49b2..0cc702a819 100644 --- a/packages/geometry-script/src/compile.ts +++ b/packages/geometry-script/src/compile.ts @@ -24,6 +24,7 @@ import { ADDITION, Brush, DIFFERENCE, Evaluator, INTERSECTION, SUBTRACTION } fro import { type Coverage, measureCoverage } from './coverage' import { cutToRegion, hostRegion } from './cut' import { type ModuleTable, transformModule } from './transform' +import { readUsageShape } from './usage-shape' export type { GeometryScriptMount } @@ -39,6 +40,8 @@ export type GeometryScriptCompileInput = { * module lays out, Pascal clips. */ inputs?: Record + /** Also write the manifest's `shape`: what the build occupies in plan at each height, for the usage checks. */ + usageShape?: boolean } export type GeometryScriptCompileOutput = CompiledGeometryScript & { glb: ArrayBuffer } @@ -1017,6 +1020,7 @@ export async function finishBuild({ code, language, inputs, + usageShape, }: { built: THREE.Object3D mount: GeometryScriptMount @@ -1029,6 +1033,7 @@ export async function finishBuild({ * stands, in the host's frame, and is cut to the floor or face they describe. */ inputs?: Record + usageShape?: boolean }): Promise { const root = new THREE.Group() root.name = 'pascal_script_root' @@ -1078,6 +1083,7 @@ export async function finishBuild({ } const { surfaces, undersides } = analyseGeometry(root, conventions.parts) + const shape = usageShape ? readUsageShape(visibleMeshes(root)) : null mergeByPartAndMaterial(root, animated) weldVertices(root) const bounds = visibleBounds(root) @@ -1106,6 +1112,7 @@ export async function finishBuild({ cutout: conventions.cutout, collider: conventions.collider, triangles: conventions.triangles, + ...(shape ? { shape } : {}), ...coverage, }), } @@ -1165,5 +1172,6 @@ export async function compileGeometryScript( code: input.code, language: 'three', inputs: input.inputs, + usageShape: input.usageShape, }) } diff --git a/packages/geometry-script/src/sandbox-worker.ts b/packages/geometry-script/src/sandbox-worker.ts index 5078dab65f..6c61660362 100644 --- a/packages/geometry-script/src/sandbox-worker.ts +++ b/packages/geometry-script/src/sandbox-worker.ts @@ -49,12 +49,13 @@ type Request = { code: string params?: Record inputs?: Record + usageShape?: boolean } self.addEventListener('message', async (event: MessageEvent) => { - const { id, code, params, inputs } = event.data + const { id, code, params, inputs, usageShape } = event.data try { - const output = await compileGeometryScript({ code, params, inputs }) + const output = await compileGeometryScript({ code, params, inputs, usageShape }) post({ id, ok: true, output }, [output.glb]) } catch (error) { post({ id, ok: false, error: error instanceof Error ? error.message : String(error) }) diff --git a/packages/geometry-script/src/usage-shape.test.ts b/packages/geometry-script/src/usage-shape.test.ts new file mode 100644 index 0000000000..cdd020991c --- /dev/null +++ b/packages/geometry-script/src/usage-shape.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { + BoxGeometry, + type BufferGeometry, + CylinderGeometry, + Group, + Mesh, + MeshStandardMaterial, +} from 'three' +import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js' +import { blenderRun, compileBlenderBuild } from './blender' +import { compileGeometryScript } from './compile' +import { readUsageShape, SHAPE_MAX_BYTES } from './usage-shape' + +const material = new MeshStandardMaterial() + +function box(width: number, height: number, depth: number, x: number, y: number, z: number) { + const mesh = new Mesh(new BoxGeometry(width, height, depth), material) + mesh.position.set(x, y, z) + return mesh +} + +function shapeOf(...meshes: Mesh[]) { + const group = new Group() + group.add(...meshes) + group.updateWorldMatrix(true, true) + return readUsageShape(meshes)! +} + +const extent = (ring: [number, number][], axis: 0 | 1) => { + const values = ring.map((p) => p[axis]) + return [Math.min(...values), Math.max(...values)] as const +} + +describe('the usage shape of a build', () => { + test('a table is four legs below its top and one slab above them', () => { + const legs = [-0.55, 0.55].flatMap((x) => + [-0.3, 0.3].map((z) => box(0.05, 0.7, 0.05, x, 0.35, z)), + ) + const top = box(1.2, 0.05, 0.7, 0, 0.725, 0) + const { bands, tolerance } = shapeOf(...legs, top) + expect(bands).toHaveLength(2) + expect(bands[0]!.y0).toBeCloseTo(0, 2) + expect(bands[0]!.y1).toBeCloseTo(0.7, 1) + expect(bands[0]!.polygons).toHaveLength(4) + for (const polygon of bands[0]!.polygons) { + const [x0, x1] = extent(polygon.outer, 0) + const [z0, z1] = extent(polygon.outer, 1) + expect(x1 - x0).toBeGreaterThanOrEqual(0.05 - 1e-6) + expect(x1 - x0).toBeLessThanOrEqual(0.05 + tolerance) + expect(z1 - z0).toBeGreaterThanOrEqual(0.05 - 1e-6) + } + expect(bands[1]!.y0).toBeCloseTo(0.7, 1) + expect(bands[1]!.y1).toBeCloseTo(0.75, 1) + expect(bands[1]!.polygons).toHaveLength(1) + const [x0, x1] = extent(bands[1]!.polygons[0]!.outer, 0) + expect(x1 - x0).toBeGreaterThanOrEqual(1.2 - 1e-6) + expect(x1 - x0).toBeLessThanOrEqual(1.2 + 0.02) + }) + + test('an L-shaped sofa keeps its notch', () => { + const { bands } = shapeOf(box(2, 0.4, 0.9, 0, 0.2, 0), box(0.9, 0.4, 1.2, -0.55, 0.2, 1.05)) + expect(bands).toHaveLength(1) + const outline = bands[0]!.polygons[0]!.outer + expect(outline.length).toBeGreaterThanOrEqual(6) + // the notch: nothing at x = +0.5, z = +1.0 although the long side reaches x = +1 + const inside = (x: number, z: number) => { + let result = false + for (let i = 0, j = outline.length - 1; i < outline.length; j = i++) { + const a = outline[i]! + const b = outline[j]! + if (a[1] > z !== b[1] > z && x < ((b[0] - a[0]) * (z - a[1])) / (b[1] - a[1]) + a[0]) + result = !result + } + return result + } + expect(inside(0.5, 1.0)).toBe(false) + expect(inside(0.5, 0.2)).toBe(true) + expect(inside(-0.6, 1.3)).toBe(true) + }) + + test('a ring keeps its hole', () => { + const ring = new Mesh(new CylinderGeometry(0.5, 0.5, 0.3, 48, 1, true), material) + ring.position.y = 0.15 + // the inner wall faces the hole, as a tube's does + const inner = new Mesh( + new CylinderGeometry(0.3, 0.3, 0.3, 48, 1, true).scale(-1, 1, 1), + material, + ) + inner.position.y = 0.15 + const { bands } = shapeOf(ring, inner) + const polygon = bands[0]!.polygons.find((p) => p.holes?.length) + expect(polygon).toBeDefined() + const [x0, x1] = extent(polygon!.holes![0]!, 0) + expect(x1 - x0).toBeGreaterThan(0.5) + expect(x1 - x0).toBeLessThan(0.65) + }) + + test('a build turned half way round the corner has an outline never inside it', () => { + const slab = box(1, 0.1, 0.2, 0, 0.05, 0) + slab.rotation.y = Math.PI / 4 + const { bands, tolerance } = shapeOf(slab) + const outline = bands[0]!.polygons[0]!.outer + const [x0, x1] = extent(outline, 0) + const reach = (1 + 0.2) / Math.SQRT2 + expect(x1 - x0).toBeGreaterThanOrEqual(reach - 1e-6) + expect(x1 - x0).toBeLessThanOrEqual(reach + 2 * tolerance) + }) + + test('a shape that would outgrow its budget is coarsened, never dropped or left oversize', () => { + const steps = Array.from({ length: 60 }, (_, i) => + box(1 - i * 0.01, 0.02, 0.5 + (i % 7) * 0.05, 0, 0.01 + i * 0.02, 0), + ) + const shape = shapeOf(...steps) + expect(new TextEncoder().encode(JSON.stringify(shape)).byteLength).toBeLessThanOrEqual( + SHAPE_MAX_BYTES, + ) + expect(shape.bands.length).toBeGreaterThan(0) + expect(shape.bands.at(-1)!.y1).toBeGreaterThanOrEqual(1.18) + }) + + describe('solid whatever the winding', () => { + const flipped = (geometry: BufferGeometry) => { + const soup = geometry.toNonIndexed() + const position = soup.getAttribute('position') + for (let i = 0; i + 2 < position.count; i += 3) { + const [x, y, z] = [position.getX(i + 1), position.getY(i + 1), position.getZ(i + 1)] + position.setXYZ(i + 1, position.getX(i + 2), position.getY(i + 2), position.getZ(i + 2)) + position.setXYZ(i + 2, x, y, z) + } + return soup + } + const solidBox = (geometry: BufferGeometry) => { + const { bands } = shapeOf(new Mesh(geometry, material)) + expect(bands).toHaveLength(1) + expect(bands[0]!.polygons).toHaveLength(1) + expect(bands[0]!.polygons[0]!.holes).toBeUndefined() + } + + test('a box with its back faces baked in as a flipped copy', () => { + const box = new BoxGeometry(1, 0.3, 0.6) + solidBox(mergeGeometries([box.toNonIndexed(), flipped(box)])!) + }) + + test('an inside-out box', () => { + solidBox(flipped(new BoxGeometry(1, 0.3, 0.6))) + }) + + test('an inside-out shell inside an outward one does not hollow it', () => { + const outer = new Mesh(new BoxGeometry(1, 0.3, 0.6), material) + const inner = new Mesh(flipped(new BoxGeometry(0.4, 0.3, 0.3)), material) + const { bands } = shapeOf(outer, inner) + expect(bands).toHaveLength(1) + expect(bands[0]!.polygons[0]!.holes).toBeUndefined() + }) + + test('boxes that overlap inside one mesh', () => { + const top = new BoxGeometry(1.2, 0.2, 0.7) + const leg = new BoxGeometry(0.1, 0.5, 0.1).translate(0.3, 0.1, 0) + const { bands } = shapeOf( + new Mesh(mergeGeometries([top.toNonIndexed(), leg.toNonIndexed()])!, material), + ) + for (const band of bands) + for (const polygon of band.polygons) expect(polygon.holes).toBeUndefined() + }) + }) + + test('nothing built reads as no shape', () => { + expect(readUsageShape([])).toBeNull() + }) +}) + +const TABLE_SCRIPT = ` +export const mount = 'floor' +export default function build({ THREE }) { + const group = new THREE.Group() + const mat = new THREE.MeshStandardMaterial() + for (const x of [-0.55, 0.55]) for (const z of [-0.3, 0.3]) { + const leg = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.7, 0.05), mat) + leg.position.set(x, 0.35, z) + group.add(leg) + } + const top = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.05, 0.7), mat) + top.position.set(0, 0.725, 0) + group.add(top) + return group +} +` + +describe('the usage shape in the manifest', () => { + test('a three.js build writes it only when asked', async () => { + const without = await compileGeometryScript({ code: TABLE_SCRIPT }) + expect(without.manifest.shape).toBeUndefined() + const asked = await compileGeometryScript({ code: TABLE_SCRIPT, usageShape: true }) + expect(asked.manifest.shape?.bands).toHaveLength(2) + expect(asked.manifest.shape!.bands[0]!.polygons).toHaveLength(4) + // the rest of the manifest is what it was + expect({ ...asked.manifest, shape: undefined }).toEqual({ + ...without.manifest, + shape: undefined, + }) + }) + + test('a Blender build writes it through the same path', async () => { + const fixture = (name: string) => new URL(`./__fixtures__/blender/${name}`, import.meta.url) + const code = readFileSync(fixture('cabinet.py'), 'utf8') + const report = JSON.parse(readFileSync(fixture('cabinet.json'), 'utf8')) + const glb = new Uint8Array(readFileSync(fixture('cabinet.glb'))) + const run = blenderRun(report, glb) + const asked = await compileBlenderBuild({ code, params: { width: 1.5 }, run, usageShape: true }) + const shape = asked.manifest.shape! + expect(shape.bands.length).toBeGreaterThan(0) + const [x0, x1] = extent(shape.bands[0]!.polygons[0]!.outer, 0) + expect(x1 - x0).toBeGreaterThanOrEqual(1.5 - 0.05) + expect( + (await compileBlenderBuild({ code, params: { width: 1.5 }, run })).manifest.shape, + ).toBeUndefined() + }) +}) diff --git a/packages/geometry-script/src/usage-shape.ts b/packages/geometry-script/src/usage-shape.ts new file mode 100644 index 0000000000..a45244921f --- /dev/null +++ b/packages/geometry-script/src/usage-shape.ts @@ -0,0 +1,729 @@ +import type { GeometryShape } from '@pascal-app/core/schema' +import type * as THREE from 'three' + +type Point = [number, number] +type Ring = Point[] + +/** What the shape may weigh in the manifest, which rides inline in the node (24 KiB in all). */ +export const SHAPE_MAX_BYTES = 10 * 1024 + +const CELL_M = 0.005 +const LAYER_M = 0.02 +const MAX_LAYERS = 200 +const MAX_CELLS_TOTAL = 48_000_000 +const MAX_BANDS = 24 +const EDGE_EPSILON = 1e-9 + +/** + * Looser and looser readings of the same layers, tried in turn until the shape fits its budget: how + * much a layer may differ from the band it joins (a share of the band's cells), and how far the + * traced outline may leave the raster's, in cells. + */ +const LEVELS = [ + { grow: 0.03, simplify: 0.75 }, + { grow: 0.06, simplify: 2 }, + { grow: 0.12, simplify: 4 }, + { grow: 0.25, simplify: 8 }, +] as const + +type Triangles = { vertices: Float32Array; count: number; kinds: Int8Array } + +function collect(meshes: THREE.Mesh[]): Triangles { + let count = 0 + for (const mesh of meshes) { + const position = mesh.geometry.getAttribute('position') + const index = mesh.geometry.getIndex() + count += Math.floor((index ? index.count : position.count) / 3) + } + const vertices = new Float32Array(count * 9) + let at = 0 + const p = [0, 0, 0] + for (const mesh of meshes) { + mesh.updateWorldMatrix(true, false) + const e = mesh.matrixWorld.elements + const position = mesh.geometry.getAttribute('position') + const index = mesh.geometry.getIndex() + const triangles = Math.floor((index ? index.count : position.count) / 3) + for (let t = 0; t < triangles; t++) + for (let k = 0; k < 3; k++) { + const v = index ? index.getX(t * 3 + k) : t * 3 + k + const x = position.getX(v) + const y = position.getY(v) + const z = position.getZ(v) + p[0] = e[0]! * x + e[4]! * y + e[8]! * z + e[12]! + p[1] = e[1]! * x + e[5]! * y + e[9]! * z + e[13]! + p[2] = e[2]! * x + e[6]! * y + e[10]! * z + e[14]! + vertices[at++] = p[0]! + vertices[at++] = p[1]! + vertices[at++] = p[2]! + } + } + return { vertices, count, kinds: classify(vertices, count) } +} + +const OUTWARD = 1 +const INWARD = -1 +const TWIN = 2 +const REDUNDANT = 0 + +/** + * How each triangle takes part in the solid fill. A face baked twice, once wound each way (the + * back faces of a double-sided material, `bakeBackFaces`), says nothing of which side is out: one + * of the two stands for the pair, to be filled by parity (TWIN), the other is left out. Every other + * triangle is OUTWARD, or INWARD where its closed shell has a negative signed volume (components + * are triangles sharing vertices; an open one is left as authored), so that a shell, an inside-out + * one and shells overlapping inside one mesh all add up as solid. + */ +function classify(vertices: Float32Array, count: number): Int8Array { + const kinds = new Int8Array(count).fill(OUTWARD) + const ids = new Map() + const corner = new Int32Array(count * 3) + for (let t = 0; t < count; t++) + for (let k = 0; k < 3; k++) { + const o = t * 9 + k * 3 + const key = `${Math.round(vertices[o]! * 1e4)},${Math.round(vertices[o + 1]! * 1e4)},${Math.round(vertices[o + 2]! * 1e4)}` + let id = ids.get(key) + if (id === undefined) { + id = ids.size + ids.set(key, id) + } + corner[t * 3 + k] = id + } + + const faces = new Map() + for (let t = 0; t < count; t++) { + const [a, b, c] = [corner[t * 3]!, corner[t * 3 + 1]!, corner[t * 3 + 2]!] + const sorted = [a, b, c].sort((x, y) => x - y) + const key = sorted.join(',') + // wound as the sorted triple is, or the other way + const even = + (a === sorted[0] && b === sorted[1]) || + (b === sorted[0] && c === sorted[1]) || + (c === sorted[0] && a === sorted[1]) + const entry = faces.get(key) ?? { forward: -1, backward: -1 } + if (even) entry.forward = entry.forward < 0 ? t : entry.forward + else entry.backward = entry.backward < 0 ? t : entry.backward + faces.set(key, entry) + } + for (const { forward, backward } of faces.values()) + if (forward >= 0 && backward >= 0) { + kinds[forward] = TWIN + kinds[backward] = REDUNDANT + } + + const parent = Int32Array.from({ length: count }, (_, i) => i) + const find = (i: number): number => { + while (parent[i] !== i) { + parent[i] = parent[parent[i]!]! + i = parent[i]! + } + return i + } + const owner = new Int32Array(ids.size).fill(-1) + for (let t = 0; t < count; t++) { + if (kinds[t] !== OUTWARD) continue + for (let k = 0; k < 3; k++) { + const id = corner[t * 3 + k]! + if (owner[id] === -1) owner[id] = t + else parent[find(t)] = find(owner[id]!) + } + } + const width = ids.size + 1 + const edges = new Map() + const edge = (t: number, k: number) => { + const a = corner[t * 3 + k]! + const b = corner[t * 3 + ((k + 1) % 3)]! + return Math.min(a, b) * width + Math.max(a, b) + } + for (let t = 0; t < count; t++) + if (kinds[t] === OUTWARD) + for (let k = 0; k < 3; k++) edges.set(edge(t, k), (edges.get(edge(t, k)) ?? 0) + 1) + const component = new Map() + for (let t = 0; t < count; t++) { + if (kinds[t] !== OUTWARD) continue + const entry = component.get(find(t)) ?? { volume: 0, open: false } + const o = t * 9 + const v = (i: number) => vertices[o + i]! + entry.volume += + (v(0) * (v(4) * v(8) - v(5) * v(7)) - + v(1) * (v(3) * v(8) - v(5) * v(6)) + + v(2) * (v(3) * v(7) - v(4) * v(6))) / + 6 + for (let k = 0; k < 3; k++) if ((edges.get(edge(t, k)) ?? 0) % 2 === 1) entry.open = true + component.set(find(t), entry) + } + for (let t = 0; t < count; t++) { + if (kinds[t] !== OUTWARD) continue + const entry = component.get(find(t))! + if (!entry.open && entry.volume < 0) kinds[t] = INWARD + } + return kinds +} + +/** Sutherland–Hodgman against one half-space of a convex polygon of `stride`-wide vertices. */ +function clip(polygon: number[], stride: number, axis: number, bound: number, keepAbove: boolean) { + const out: number[] = [] + const n = polygon.length / stride + const side = (v: number) => (keepAbove ? v - bound : bound - v) + for (let i = 0; i < n; i++) { + const a = i * stride + const b = ((i + 1) % n) * stride + const sa = side(polygon[a + axis]!) + const sb = side(polygon[b + axis]!) + if (sa >= 0) for (let k = 0; k < stride; k++) out.push(polygon[a + k]!) + if (sa >= 0 !== sb >= 0) { + const t = sa / (sa - sb) + for (let k = 0; k < stride; k++) + out.push(polygon[a + k]! + (polygon[b + k]! - polygon[a + k]!) * t) + } + } + return out +} + +type Raster = { + minX: number + minZ: number + cell: number + nx: number + nz: number +} + +/** Marks every cell the polygon (x, z pairs) touches: a conservative fill, a cell wider than the build at worst. */ +function fill(grid: Uint8Array, raster: Raster, polygon: number[]) { + const { minX, minZ, cell, nx, nz } = raster + const n = polygon.length / 2 + if (n === 0) return + let zLow = Number.POSITIVE_INFINITY + let zHigh = Number.NEGATIVE_INFINITY + for (let i = 0; i < n; i++) { + zLow = Math.min(zLow, polygon[i * 2 + 1]!) + zHigh = Math.max(zHigh, polygon[i * 2 + 1]!) + } + const j0 = Math.max(0, Math.floor((zLow - minZ) / cell)) + const j1 = Math.min(nz - 1, Math.max(j0, Math.floor((zHigh - minZ) / cell - EDGE_EPSILON))) + for (let j = j0; j <= j1; j++) { + let strip = polygon + if (j1 > j0) { + strip = clip(polygon, 2, 1, minZ + j * cell, true) + strip = clip(strip, 2, 1, minZ + (j + 1) * cell, false) + } + let xLow = Number.POSITIVE_INFINITY + let xHigh = Number.NEGATIVE_INFINITY + for (let i = 0; i < strip.length; i += 2) { + xLow = Math.min(xLow, strip[i]!) + xHigh = Math.max(xHigh, strip[i]!) + } + if (xLow > xHigh) continue + const i0 = Math.max(0, Math.floor((xLow - minX) / cell)) + const i1 = Math.min(nx - 1, Math.max(i0, Math.floor((xHigh - minX) / cell - EDGE_EPSILON))) + grid.fill(1, j * nx + i0, j * nx + i1 + 1) + } +} + +type Crossings = { + oriented: Map + parity: Map +} + +/** + * Where a triangle that spans the layer's middle plane crosses the horizontal rays along x through + * each raster row's centre. An oriented triangle also says which way: a surface whose normal points + * back along the ray is one the ray enters through, +1; one it leaves through, -1. + */ +function cross( + vertices: Float32Array, + o: number, + kind: number, + y: number, + raster: Raster, + crossings: Crossings, +) { + const { minZ, cell, nz } = raster + const ax = vertices[o]!, + ay = vertices[o + 1]!, + az = vertices[o + 2]! + const bx = vertices[o + 3]!, + by = vertices[o + 4]!, + bz = vertices[o + 5]! + const cx = vertices[o + 6]!, + cy = vertices[o + 7]!, + cz = vertices[o + 8]! + const normalX = (by - ay) * (cz - az) - (bz - az) * (cy - ay) + if (Math.abs(normalX) < 1e-12) return + const wind = (normalX < 0 ? 1 : -1) * (kind === INWARD ? -1 : 1) + const at: [number, number][] = [] + const edge = (px: number, py: number, pz: number, qx: number, qy: number, qz: number) => { + if (py > y === qy > y) return + const t = (y - py) / (qy - py) + at.push([px + (qx - px) * t, pz + (qz - pz) * t]) + } + edge(ax, ay, az, bx, by, bz) + edge(bx, by, bz, cx, cy, cz) + edge(cx, cy, cz, ax, ay, az) + if (at.length !== 2) return + const [p, q] = at as [[number, number], [number, number]] + if (p[1] === q[1]) return + const [zLow, zHigh] = p[1] < q[1] ? [p[1], q[1]] : [q[1], p[1]] + const j0 = Math.max(0, Math.ceil((zLow - minZ) / cell - 0.5)) + const j1 = Math.min(nz - 1, Math.ceil((zHigh - minZ) / cell - 0.5) - 1) + for (let j = j0; j <= j1; j++) { + const z = minZ + (j + 0.5) * cell + const x = p[0] + ((z - p[1]) / (q[1] - p[1])) * (q[0] - p[0]) + if (kind === TWIN) { + const row = crossings.parity.get(j) + if (row) row.push(x) + else crossings.parity.set(j, [x]) + } else { + const row = crossings.oriented.get(j) + if (row) row.push({ x, wind }) + else crossings.oriented.set(j, [{ x, wind }]) + } + } +} + +/** + * Fills each row between the crossings where the surfaces enclose something: a nonzero winding for + * the oriented ones, so overlapping solids read as solid, and an odd count for the unoriented pairs. + */ +function solid(grid: Uint8Array, raster: Raster, crossings: Crossings) { + const { minX, cell, nx } = raster + const span = (j: number, from: number, to: number) => { + const i0 = Math.max(0, Math.floor((from - minX) / cell)) + const i1 = Math.min(nx - 1, Math.max(i0, Math.floor((to - minX) / cell - EDGE_EPSILON))) + grid.fill(1, j * nx + i0, j * nx + i1 + 1) + } + for (const [j, row] of crossings.oriented) { + row.sort((a, b) => a.x - b.x) + let winding = 0 + for (let k = 0; k + 1 < row.length; k++) { + winding += row[k]!.wind + if (winding !== 0) span(j, row[k]!.x, row[k + 1]!.x) + } + } + for (const [j, row] of crossings.parity) { + row.sort((a, b) => a - b) + for (let k = 0; k + 1 < row.length; k += 2) span(j, row[k]!, row[k + 1]!) + } +} + +type Layers = { + grids: Uint8Array + cells: number + count: number + layer: number + minY: number + raster: Raster +} + +/** The plan footprint of everything the build has in each thin layer of its height. */ +function rasterise(triangles: Triangles): Layers | null { + const { vertices, count, kinds } = triangles + if (count === 0) return null + let minX = Number.POSITIVE_INFINITY + let minY = Number.POSITIVE_INFINITY + let minZ = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let maxY = Number.NEGATIVE_INFINITY + let maxZ = Number.NEGATIVE_INFINITY + for (let i = 0; i < vertices.length; i += 3) { + minX = Math.min(minX, vertices[i]!) + maxX = Math.max(maxX, vertices[i]!) + minY = Math.min(minY, vertices[i + 1]!) + maxY = Math.max(maxY, vertices[i + 1]!) + minZ = Math.min(minZ, vertices[i + 2]!) + maxZ = Math.max(maxZ, vertices[i + 2]!) + } + if (![minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite)) return null + const height = maxY - minY + const layers = Math.min(MAX_LAYERS, Math.max(1, Math.ceil(height / LAYER_M))) + const layer = Math.max(height / layers, 1e-6) + let cell = CELL_M + const size = (c: number) => + (Math.floor((maxX - minX) / c) + 1) * (Math.floor((maxZ - minZ) / c) + 1) + while (size(cell) * layers > MAX_CELLS_TOTAL) cell *= 1.25 + const nx = Math.floor((maxX - minX) / cell) + 1 + const nz = Math.floor((maxZ - minZ) / cell) + 1 + const cells = nx * nz + const raster: Raster = { minX, minZ, cell, nx, nz } + const grids = new Uint8Array(cells * layers) + + const first = new Int32Array(count) + const last = new Int32Array(count) + const perLayer = new Int32Array(layers + 1) + for (let t = 0; t < count; t++) { + const o = t * 9 + const low = Math.min(vertices[o + 1]!, vertices[o + 4]!, vertices[o + 7]!) + const high = Math.max(vertices[o + 1]!, vertices[o + 4]!, vertices[o + 7]!) + first[t] = Math.min(layers - 1, Math.max(0, Math.floor((low - minY) / layer))) + last[t] = Math.min( + layers - 1, + Math.max(first[t]!, Math.floor((high - minY) / layer - EDGE_EPSILON)), + ) + for (let l = first[t]!; l <= last[t]!; l++) perLayer[l + 1]! += 1 + } + for (let l = 0; l < layers; l++) perLayer[l + 1]! += perLayer[l]! + const lists = new Int32Array(perLayer[layers]!) + const cursor = perLayer.slice(0, layers) + for (let t = 0; t < count; t++) + for (let l = first[t]!; l <= last[t]!; l++) lists[cursor[l]!++] = t + + for (let l = 0; l < layers; l++) { + const grid = grids.subarray(l * cells, (l + 1) * cells) + const y0 = minY + l * layer + const y1 = y0 + layer + const middle = (y0 + y1) / 2 + const crossings: Crossings = { oriented: new Map(), parity: new Map() } + for (let i = perLayer[l]!; i < perLayer[l + 1]!; i++) { + if (kinds[lists[i]!] === REDUNDANT) continue + const o = lists[i]! * 9 + let polygon = [ + vertices[o]!, + vertices[o + 1]!, + vertices[o + 2]!, + vertices[o + 3]!, + vertices[o + 4]!, + vertices[o + 5]!, + vertices[o + 6]!, + vertices[o + 7]!, + vertices[o + 8]!, + ] + const low = Math.min(polygon[1]!, polygon[4]!, polygon[7]!) + const high = Math.max(polygon[1]!, polygon[4]!, polygon[7]!) + if (low <= middle && high > middle) + cross(vertices, o, kinds[lists[i]!]!, middle, raster, crossings) + if (low < y0) polygon = clip(polygon, 3, 1, y0, true) + if (high > y1) polygon = clip(polygon, 3, 1, y1, false) + const plan: number[] = [] + for (let k = 0; k < polygon.length; k += 3) plan.push(polygon[k]!, polygon[k + 2]!) + fill(grid, raster, plan) + } + solid(grid, raster, crossings) + } + return { grids, cells, count: layers, layer, minY, raster } +} + +type Band = { from: number; to: number; cells: Uint8Array } + +/** Runs of layers whose footprints differ by less than `grow` of the run's: a run reads as the union of its layers. */ +function band(layers: Layers, grow: number): Band[] { + const { grids, cells, count } = layers + const bands: Band[] = [] + let current: Band | null = null + let area = 0 + for (let l = 0; l < count; l++) { + const grid = grids.subarray(l * cells, (l + 1) * cells) + let layerArea = 0 + for (let i = 0; i < cells; i++) layerArea += grid[i]! + if (layerArea === 0) { + current = null + continue + } + if (current) { + let added = 0 + let missing = 0 + for (let i = 0; i < cells; i++) { + if (grid[i] && !current.cells[i]) added++ + else if (!grid[i] && current.cells[i]) missing++ + } + const allowed = Math.max(4, grow * area) + if (added <= allowed && missing <= allowed) { + for (let i = 0; i < cells; i++) if (grid[i]) current.cells[i] = 1 + current.to = l + area += added + continue + } + } + current = { from: l, to: l, cells: Uint8Array.from(grid) } + area = layerArea + bands.push(current) + } + return bands +} + +const signedArea = (ring: Ring) => { + let a = 0 + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) + a += ring[j]![0] * ring[i]![1] - ring[i]![0] * ring[j]![1] + return a / 2 +} + +/** The boundary of the filled cells as closed rings, filled side on the left: outer rings turn counter-clockwise, holes clockwise. */ +function trace(cells: Uint8Array, raster: Raster): Ring[] { + const { nx, nz } = raster + const filled = (i: number, j: number) => + i >= 0 && j >= 0 && i < nx && j < nz && cells[j * nx + i] === 1 + const next = new Map() + const key = (i: number, j: number) => j * (nx + 1) + i + const add = (i0: number, j0: number, i1: number, j1: number) => { + const k = key(i0, j0) + const list = next.get(k) + if (list) list.push(key(i1, j1)) + else next.set(k, [key(i1, j1)]) + } + for (let j = 0; j < nz; j++) + for (let i = 0; i < nx; i++) { + if (!cells[j * nx + i]) continue + if (!filled(i, j - 1)) add(i, j, i + 1, j) + if (!filled(i + 1, j)) add(i + 1, j, i + 1, j + 1) + if (!filled(i, j + 1)) add(i + 1, j + 1, i, j + 1) + if (!filled(i - 1, j)) add(i, j + 1, i, j) + } + const rings: Ring[] = [] + const w = nx + 1 + for (const [start] of next) { + while (next.get(start)?.length) { + const ring: Ring = [] + let at = start + let heading: number | null = null + do { + const options = next.get(at) + if (!options?.length) break + const here = [at % w, Math.floor(at / w)] + // Take the leftmost turn so cells touching at a corner stay separate rings. + let pick = 0 + if (options.length > 1) { + let best = -Infinity + options.forEach((to, index) => { + const dx = (to % w) - here[0]! + const dz = Math.floor(to / w) - here[1]! + const angle = Math.atan2(dz, dx) + const turn = + heading === null ? 0 : ((angle - heading + 3 * Math.PI) % (2 * Math.PI)) - Math.PI + if (turn > best) { + best = turn + pick = index + } + }) + } + const to = options.splice(pick, 1)[0]! + ring.push([here[0]!, here[1]!]) + heading = Math.atan2(Math.floor(to / w) - here[1]!, (to % w) - here[0]!) + at = to + } while (at !== start) + if (ring.length >= 4) rings.push(ring) + } + } + return rings +} + +/** Douglas–Peucker over a closed ring. */ +function simplify(ring: Ring, tolerance: number): Ring { + if (ring.length <= 4) return ring + const distance = (p: Point, a: Point, b: Point) => { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const length = Math.hypot(dx, dz) + return length < 1e-12 + ? Math.hypot(p[0] - a[0], p[1] - a[1]) + : Math.abs((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / length + } + const keep = new Array(ring.length).fill(false) + const run = (from: number, to: number) => { + let far = -1 + let best = tolerance + for (let i = from + 1; i < to; i++) { + const d = distance(ring[i]!, ring[from]!, ring[to % ring.length]!) + if (d > best) { + best = d + far = i + } + } + if (far < 0) return + keep[far] = true + run(from, far) + run(far, to) + } + let farthest = 0 + let reach = -1 + for (let i = 1; i < ring.length; i++) { + const d = Math.hypot(ring[i]![0] - ring[0]![0], ring[i]![1] - ring[0]![1]) + if (d > reach) { + reach = d + farthest = i + } + } + keep[0] = true + keep[farthest] = true + run(0, farthest) + run(farthest, ring.length) + const out = ring.filter((_, i) => keep[i]) + return out.length >= 3 ? out : ring +} + +function inside(point: Point, ring: Ring) { + let result = false + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const a = ring[i]! + const b = ring[j]! + if ( + a[1] > point[1] !== b[1] > point[1] && + point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0] + ) + result = !result + } + return result +} + +type Shaped = GeometryShape['bands'][number]['polygons'] + +const mm = (v: number) => Math.round(v * 1000) / 1000 + +function polygons(cells: Uint8Array, raster: Raster, simplifyCells: number): Shaped { + const { minX, minZ, cell } = raster + const world = (ring: Ring): Ring => ring.map(([i, j]) => [minX + i * cell, minZ + j * cell]) + const rings = trace(cells, raster) + .map((ring) => + world( + simplify( + ring.map(([i, j]) => [i, j] as Point), + simplifyCells, + ), + ).map(([x, z]) => [mm(x), mm(z)] as Point), + ) + .filter((ring) => ring.length >= 3 && Math.abs(signedArea(ring)) >= 2 * cell * cell) + const outers = rings.filter((ring) => signedArea(ring) > 0) + const holes = rings.filter((ring) => signedArea(ring) < 0) + const result = outers.map((outer) => ({ outer, holes: [] as Ring[] })) + for (const hole of holes) { + const owner = result + .filter((candidate) => inside(hole[0]!, candidate.outer)) + .sort((a, b) => Math.abs(signedArea(a.outer)) - Math.abs(signedArea(b.outer)))[0] + if (owner) owner.holes.push(hole) + } + return result.map(({ outer, holes: h }) => (h.length ? { outer, holes: h } : { outer })) +} + +const bytes = (shape: GeometryShape) => new TextEncoder().encode(JSON.stringify(shape)).byteLength + +/** One box over the whole build: the last resort when nothing finer fits the budget. */ +function box(bounds: { + min: [number, number, number] + max: [number, number, number] +}): GeometryShape { + return { + tolerance: mm(Math.max(bounds.max[0] - bounds.min[0], bounds.max[2] - bounds.min[2])), + bands: [ + { + y0: mm(bounds.min[1]), + y1: mm(bounds.max[1]), + polygons: [ + { + outer: [ + [mm(bounds.min[0]), mm(bounds.min[2])], + [mm(bounds.max[0]), mm(bounds.min[2])], + [mm(bounds.max[0]), mm(bounds.max[2])], + [mm(bounds.min[0]), mm(bounds.max[2])], + ], + }, + ], + }, + ], + } +} + +/** Adjacent bands merged, the pair that adds the fewest cells first, until `target` remain. */ +function merged(bands: Band[], target: number): Band[] { + const out = bands.map((b) => ({ ...b, cells: Uint8Array.from(b.cells) })) + while (out.length > Math.max(1, target)) { + let best = 0 + let least = Number.POSITIVE_INFINITY + for (let i = 0; i + 1 < out.length; i++) { + const a = out[i]! + const b = out[i + 1]! + let extra = 0 + for (let k = 0; k < a.cells.length; k++) if (a.cells[k] !== b.cells[k]) extra++ + // a taller gap between them costs more, so equal differences merge the nearer pair first + const cost = extra + (b.from - a.to - 1) * 0.5 + if (cost < least) { + least = cost + best = i + } + } + const a = out[best]! + const b = out[best + 1]! + for (let k = 0; k < a.cells.length; k++) if (b.cells[k]) a.cells[k] = 1 + a.to = b.to + out.splice(best + 1, 1) + } + return out +} + +/** The cells within `radius` cells of a filled one (a separable box dilation, by prefix sums). */ +function dilate(cells: Uint8Array, raster: Raster, radius: number): Uint8Array { + const { nx, nz } = raster + const pass = ( + source: Uint8Array, + lines: number, + length: number, + at: (line: number, i: number) => number, + ) => { + const out = new Uint8Array(source.length) + const sums = new Int32Array(length + 1) + for (let line = 0; line < lines; line++) { + for (let i = 0; i < length; i++) sums[i + 1] = sums[i]! + source[at(line, i)]! + for (let i = 0; i < length; i++) + out[at(line, i)] = + sums[Math.min(length, i + radius + 1)]! - sums[Math.max(0, i - radius)]! > 0 ? 1 : 0 + } + return out + } + const across = pass(cells, nz, nx, (line, i) => line * nx + i) + return pass(across, nx, nz, (line, i) => i * nx + line) +} + +const shapeOf = (layers: Layers, bands: Band[], simplifyCells: number): GeometryShape => ({ + tolerance: mm(layers.raster.cell * (1 + simplifyCells)), + bands: bands.map((b) => ({ + y0: mm(layers.minY + b.from * layers.layer), + y1: mm(layers.minY + (b.to + 1) * layers.layer), + polygons: polygons(b.cells, layers.raster, simplifyCells), + })), +}) + +/** + * What the build occupies in plan at each height, for the usage checks: the footprint of everything + * it has in each 2 cm layer, runs of near-identical layers read as bands, each band traced to + * outlines. The fill is conservative, so an outline is never inside the build and at worst a cell + * (5 mm) outside it, plus the simplification; `tolerance` states that bound. A build too intricate + * for its budget is read ever more coarsely, bands merged and outlines simplified, and in the end as + * one box. Frames are the meshes' world frame, so call it on a built object in the artifact's frame. + * Null for an empty one. + */ +export function readUsageShape(meshes: THREE.Mesh[]): GeometryShape | null { + const layers = rasterise(collect(meshes)) + if (!layers) return null + const fits = (shape: GeometryShape) => bytes(shape) <= SHAPE_MAX_BYTES + let finest: Band[] | null = null + for (const level of LEVELS) { + const bands = band(layers, level.grow) + finest ??= bands + if (bands.length > MAX_BANDS) continue + const shape = shapeOf(layers, bands, level.simplify) + if (fits(shape)) return shape + } + // Too intricate to trace within the budget (foliage, a screen of slats): thicken it until nearby + // pieces merge into blobs, which only ever adds to the shape, and say so in the tolerance. + const loosest = LEVELS.at(-1)! + for (const radius of [0, 2, 4, 8, 16, 32]) { + const base = band(layers, loosest.grow).map((b) => ({ + ...b, + cells: radius ? dilate(b.cells, layers.raster, radius) : b.cells, + })) + for (const target of [MAX_BANDS, 12, 6, 3, 1]) { + const bands = merged(base, target) + for (const simplifyCells of [loosest.simplify, loosest.simplify * 2, loosest.simplify * 4]) { + const shape = shapeOf(layers, bands, simplifyCells + radius) + if (fits(shape)) return shape + } + } + } + const { raster } = layers + return box({ + min: [raster.minX, layers.minY, raster.minZ], + max: [ + raster.minX + raster.nx * raster.cell, + layers.minY + layers.count * layers.layer, + raster.minZ + raster.nz * raster.cell, + ], + }) +} diff --git a/packages/mcp/src/bin/pascal-mcp.ts b/packages/mcp/src/bin/pascal-mcp.ts index 43d7ce0dfb..3233a67632 100644 --- a/packages/mcp/src/bin/pascal-mcp.ts +++ b/packages/mcp/src/bin/pascal-mcp.ts @@ -4,6 +4,7 @@ import '../bridge/node-shims' import { readFileSync } from 'node:fs' import { parseArgs } from 'node:util' +import { sdfChecksFromEnv, setSdfChecks } from '@pascal-app/core/usage-field' import { SceneBridge } from '../bridge/scene-bridge' import { version } from '../index' import { createPascalMcpServer } from '../server' @@ -54,6 +55,7 @@ async function main(): Promise { process.exit(0) } + setSdfChecks(sdfChecksFromEnv(process.env.PASCAL_SDF_CHECKS)) const store = await createSceneStore() const createServer = () => { const bridge = new SceneBridge() diff --git a/packages/mcp/src/tools/local-geometry-scripts.ts b/packages/mcp/src/tools/local-geometry-scripts.ts index 99ce78d4cb..c8ea722e72 100644 --- a/packages/mcp/src/tools/local-geometry-scripts.ts +++ b/packages/mcp/src/tools/local-geometry-scripts.ts @@ -1,6 +1,7 @@ import { spawn } from 'node:child_process' import { fileURLToPath } from 'node:url' import type { CompiledGeometryScript } from '@pascal-app/core' +import { sdfChecksOn } from '@pascal-app/core/usage-field' import { compileBlenderBuild } from '@pascal-app/geometry-script/blender' import { runBlenderLocally } from '@pascal-app/geometry-script/blender-local' import { DiskArtifactStore } from '../storage/disk-artifact-store' @@ -20,7 +21,11 @@ export function localGeometryScripts(projectPath: string): GeometryScriptHost { if (!blender) throw new Error('bpy scripts need PASCAL_BLENDER, the path to a Blender binary') const run = await runBlenderLocally({ blender, code: input.code, params: input.params }) - const { glb, ...compiled } = await compileBlenderBuild({ ...input, run }) + const { glb, ...compiled } = await compileBlenderBuild({ + ...input, + run, + ...(sdfChecksOn() ? { usageShape: true } : {}), + }) return { ...compiled, glb: new Uint8Array(glb) } } if (process.env.PASCAL_SERVER_SCRIPT_COMPILE !== '1') { @@ -62,7 +67,9 @@ export function localGeometryScripts(projectPath: string): GeometryScriptHost { reject(new Error(`Geometry script compilation failed: ${stderr}`)) } }) - child.stdin.end(JSON.stringify(input)) + child.stdin.end( + JSON.stringify({ ...input, ...(sdfChecksOn() ? { usageShape: true } : {}) }), + ) }) }, storeArtifact: async ({ sha256, bytes }) => { From cb9250c04b4df157de25ed4d058cec82342a97f4 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 17:10:00 +0100 Subject: [PATCH 05/40] verify_scene names the surfaces a room owes: tile, skirting, a floor, a finish on its faces Room checks, run with every verify_scene and quiet where the nodes cannot be read to the end: a wet room (bathroom, shower room, WC, laundry) whose walls are not tiled as one is, to a height on the walls its fixtures stand against and to the ceiling around its shower; rooms with no skirting, and a room skirted on some of its faces only; a room with no floor under it; every room at its default floor, and every wall face at its default, said once when there are three or more; the finish of an outside face showing on the inside face of the same wall; and a piece hung on the face of the wall that looks into another room than the one it names. The readings they stand on: what each room shows (floor, walls, tile, skirting, its pieces), the faces that look into a room, a wall face's finishes stretch by stretch (`describeWallFaceFinishes`), and which stretch a fixture stands against. A registered scene check now receives the verify_scene context, for the materials of the scene. Read against what main has: the announced-against-built findings and the dressing reading wait for the brief's rooms section, and two rooms furnished alike is not read. Rule tests, and the shared finished test room (walls painted on both faces, a floor and wall finish, a painted ceiling) so a case that says "clean" says it of the checks it is about. Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/dressing-scenes.ts | 113 ++++ .../__fixtures__/room-check-scenes.ts | 188 +++++++ .../__fixtures__/scene-check-cases.ts | 70 ++- .../src/agent-operations/dress-targets.ts | 52 ++ packages/core/src/agent-operations/index.ts | 1 + .../src/agent-operations/plan-geometry.ts | 12 + .../src/agent-operations/room-checks.test.ts | 449 +++++++++++++++ .../core/src/agent-operations/room-checks.ts | 307 +++++++++++ .../src/agent-operations/room-faces.test.ts | 43 ++ .../core/src/agent-operations/room-faces.ts | 56 ++ .../agent-operations/room-finishes.test.ts | 291 ++++++++++ .../src/agent-operations/room-finishes.ts | 309 +++++++++++ .../src/agent-operations/room-readings.ts | 518 ++++++++++++++++++ .../core/src/agent-operations/room-tile.ts | 35 ++ .../core/src/agent-operations/room-wet.ts | 269 +++++++++ .../core/src/agent-operations/verify-scene.ts | 8 +- .../agent-operations/wall-face-defaults.ts | 300 ++++++++++ .../agent-operations/wall-item-faces.test.ts | 155 ++++++ .../src/agent-operations/wall-item-faces.ts | 73 +++ .../wall-outside-finish.test.ts | 136 +++++ .../agent-operations/wall-outside-finish.ts | 137 +++++ packages/core/src/building/room-use.ts | 120 ++++ .../__fixtures__/enclosure-scenes.ts | 85 +++ packages/core/src/systems/wall/wall-finish.ts | 104 ++++ 24 files changed, 3810 insertions(+), 21 deletions(-) create mode 100644 packages/core/src/agent-operations/__fixtures__/dressing-scenes.ts create mode 100644 packages/core/src/agent-operations/__fixtures__/room-check-scenes.ts create mode 100644 packages/core/src/agent-operations/dress-targets.ts create mode 100644 packages/core/src/agent-operations/room-checks.test.ts create mode 100644 packages/core/src/agent-operations/room-checks.ts create mode 100644 packages/core/src/agent-operations/room-faces.test.ts create mode 100644 packages/core/src/agent-operations/room-faces.ts create mode 100644 packages/core/src/agent-operations/room-finishes.test.ts create mode 100644 packages/core/src/agent-operations/room-finishes.ts create mode 100644 packages/core/src/agent-operations/room-readings.ts create mode 100644 packages/core/src/agent-operations/room-tile.ts create mode 100644 packages/core/src/agent-operations/room-wet.ts create mode 100644 packages/core/src/agent-operations/wall-face-defaults.ts create mode 100644 packages/core/src/agent-operations/wall-item-faces.test.ts create mode 100644 packages/core/src/agent-operations/wall-item-faces.ts create mode 100644 packages/core/src/agent-operations/wall-outside-finish.test.ts create mode 100644 packages/core/src/agent-operations/wall-outside-finish.ts create mode 100644 packages/core/src/building/room-use.ts create mode 100644 packages/core/src/coherence/__fixtures__/enclosure-scenes.ts diff --git a/packages/core/src/agent-operations/__fixtures__/dressing-scenes.ts b/packages/core/src/agent-operations/__fixtures__/dressing-scenes.ts new file mode 100644 index 0000000000..abe35f66d4 --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/dressing-scenes.ts @@ -0,0 +1,113 @@ +import { building, graph, storey } from '../../coherence/__fixtures__/enclosure-scenes' +import { type AnyNode, ItemNode, WallNode, ZoneNode } from '../../schema' + +/** + * Two rooms side by side for the room-dressing rules, with a wall that both look at: a salon + * (zone_salon, 0..4 m) and a bath (zone_bath, 4..8 m), 3 m deep, walls 2.5 m high. The south wall + * runs the whole 8 m, so a stretch of one face belongs to each room; the partition wall_p has a room + * on each of its faces. Plan axes: x east, z south. + * + * wall_w 0,3 -> 0,0 salon wall_s 0,0 -> 8,0 both (t 0..0.5 salon, 0.5..1 bath) + * wall_an 4,3 -> 0,3 salon wall_p 4,0 -> 4,3 both + * wall_e 8,0 -> 8,3 bath wall_bn 8,3 -> 4,3 bath + */ + +export const WALL_HEIGHT = 2.5 + +type Pt = [number, number] + +export const SALON: Pt[] = [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], +] +export const BATH: Pt[] = [ + [4, 0], + [8, 0], + [8, 3], + [4, 3], +] + +const WALLS: [id: string, start: Pt, end: Pt][] = [ + ['wall_s', [0, 0], [8, 0]], + ['wall_p', [4, 0], [4, 3]], + ['wall_an', [4, 3], [0, 3]], + ['wall_w', [0, 3], [0, 0]], + ['wall_e', [8, 0], [8, 3]], + ['wall_bn', [8, 3], [4, 3]], +] + +export type DressingOptions = { + /** Fields merged into walls by id before they are parsed (a hand-drawn region, a trim, a curtain wall). */ + walls?: Record> + /** Fields set on walls by id as they are, past the schema (a face script is too large to build). */ + raw?: Record> + /** Items standing in the level, by id: [category, plan x, plan z, size w, d] */ + items?: Record + /** Fields merged into the rooms by id before they are parsed (a wall finish for the room). */ + zones?: Record> + /** Nodes added as they are (a cabinet run and its modules). */ + extra?: AnyNode[] +} + +export function twoRooms({ + walls = {}, + raw = {}, + zones = {}, + items = {}, + extra = [], +}: DressingOptions = {}) { + const nodes: AnyNode[] = [building(), storey(3)] + for (const [id, start, end] of WALLS) + nodes.push({ + ...WallNode.parse({ + id, + parentId: 'level_0', + start, + end, + height: WALL_HEIGHT, + thickness: 0.1, + ...walls[id], + }), + ...raw[id], + } as AnyNode) + nodes.push( + ZoneNode.parse({ + id: 'zone_salon', + parentId: 'level_0', + name: 'Salon', + polygon: SALON, + spaceRole: 'room', + boundaryWallIds: ['wall_s', 'wall_p', 'wall_an', 'wall_w'], + ...zones.zone_salon, + }), + ZoneNode.parse({ + id: 'zone_bath', + parentId: 'level_0', + name: 'Salle de bains', + polygon: BATH, + spaceRole: 'room', + boundaryWallIds: ['wall_s', 'wall_e', 'wall_bn', 'wall_p'], + ...zones.zone_bath, + }), + ) + for (const [id, [category, x, z, width, depth, name]] of Object.entries(items)) + nodes.push( + ItemNode.parse({ + id, + parentId: 'level_0', + name: name ?? category, + position: [x, 0, z], + asset: { + id: `asset_${id}`, + category, + name: name ?? category, + thumbnail: '', + src: 'https://example.com/x.glb', + dimensions: [width, 2, depth], + }, + }), + ) + return graph(...nodes, ...extra) +} diff --git a/packages/core/src/agent-operations/__fixtures__/room-check-scenes.ts b/packages/core/src/agent-operations/__fixtures__/room-check-scenes.ts new file mode 100644 index 0000000000..eacd1d998f --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/room-check-scenes.ts @@ -0,0 +1,188 @@ +import { building, graph, rectangleWalls, storey } from '../../coherence/__fixtures__/enclosure-scenes' +import { type AnyNode, CeilingNode, ItemNode, SlabNode, WallNode, ZoneNode } from '../../schema' + +/** + * Houses of rooms side by side, for the room checks: each room is four walls, its zone, the floor + * plate under it and the pieces standing in it. A room is what a check reads: a name, a floor and a wall finish, whether + * its walls carry skirting, and the pieces as [category, design] (a catalog item) with, for an item an + * agent authored, the script that made it and its size, finishes and name. + */ + +/** An item an agent authored: the script that made it, which a copy for another room shares. */ +export type Authored = { + script?: string + size?: [number, number, number] + slots?: Record + name?: string + /** Where it stands in its room, metres from the room's north-west corner; absent, in the row of pieces. */ + at?: [number, number] +} +export type PieceSpec = [category: string, design: string, authored?: Authored] + +export type RoomSpec = { + name: string + /** A finish ref; null writes none, so the floor shows the default. */ + floor?: string | null + /** A finish ref; null writes none, so the wall faces show the default. */ + walls?: string | null + /** A finish ref for the outside face of its walls (paint by default); null writes none. */ + outside?: string | null + /** `some`: the north and east walls only. */ + skirting?: boolean | 'some' + /** A ceiling over the room: `default` leaves its surface unwritten, a ref paints it; absent, no ceiling. */ + ceiling?: 'default' | string + /** What is under the room: its own plate (the default), a drawn slab it was taken from, or nothing. */ + under?: 'plate' | 'drawn' | 'none' + /** Paint regions on the faces that look in: one wall (0 north, 1 east, 2 south, 3 west) or all four. */ + regions?: { wall?: number; u0?: number; u1?: number; v0?: number; v1?: number; finish: string }[] + pieces?: PieceSpec[] + /** Designs placed with place_design, by recipe name. */ + designs?: string[] +} + +const ROOM = 4 +const PITCH = 5 + +export const TILE = 'library:flooring-tiles3' +export const MARBLE = 'library:flooring-statuarettowhite' +export const PARQUET = 'library:wood-woodparquet14' +export const PAINT = 'library:preset-softwhite' + +const piece = ( + id: string, + [category, design, authored]: PieceSpec, + at: [number, number, number], +): ItemNode => { + const node = ItemNode.parse({ + id, + parentId: 'level_0', + name: authored?.name ?? `${category} ${id}`, + position: at, + ...(authored?.slots ? { slots: authored.slots } : {}), + asset: { + id: design, + category, + name: category, + thumbnail: '', + src: 'https://example.com/x.glb', + dimensions: authored?.size ?? [0.5, 0.5, 0.5], + }, + }) + return authored?.script + ? ({ ...node, source: { kind: 'script', script: authored.script, params: {} } } as ItemNode) + : node +} + +/** A placed design, as the store holds it: a recipe and its parameters, standing on the floor. */ +const design = (id: string, recipe: string, at: [number, number, number]) => + ({ + object: 'node', + type: 'procedural-item', + id, + parentId: 'level_0', + visible: true, + metadata: {}, + name: recipe, + recipe: { name: recipe }, + parameters: {}, + slots: {}, + position: at, + rotation: [0, 0, 0], + children: [], + attachments: {}, + }) as unknown as AnyNode + +export function house(...rooms: RoomSpec[]) { + const nodes: AnyNode[] = [building(), storey(3)] + rooms.forEach((room, index) => { + const x0 = index * PITCH + const walls = rectangleWalls('level_0', [x0, 0, x0 + ROOM, ROOM], undefined, 'interior', `wall_r${index}`) + nodes.push( + ...walls.map((wall, at) => + WallNode.parse({ + ...wall, + ...(room.outside === null ? {} : { slots: { b: room.outside ?? PAINT } }), + ...(room.skirting === true || (room.skirting === 'some' && at < 2) + ? { skirting: { enabled: true, sides: 'both' } } + : {}), + faceRegions: (room.regions ?? []) + .filter((region) => region.wall === undefined || region.wall === at) + .map(({ wall: _wall, ...region }, n) => ({ id: `region_${at}_${n}`, face: 'a', ...region })), + }), + ), + ...(room.under === 'none' + ? [] + : [ + SlabNode.parse({ + id: `slab_${index}`, + parentId: 'level_0', + polygon: [ + [x0, 0], + [x0 + ROOM, 0], + [x0 + ROOM, ROOM], + [x0, ROOM], + ], + ...(room.under === 'drawn' ? {} : { zoneIds: [`zone_${index}`], plateRole: 'base' }), + }), + ]), + ...(room.ceiling + ? [ + CeilingNode.parse({ + id: `ceiling_${index}`, + parentId: 'level_0', + polygon: [ + [x0, 0], + [x0 + ROOM, 0], + [x0 + ROOM, ROOM], + [x0, ROOM], + ], + zoneId: `zone_${index}`, + ...(room.ceiling === 'default' ? {} : { slots: { surface: room.ceiling } }), + }), + ] + : []), + ZoneNode.parse({ + id: `zone_${index}`, + parentId: 'level_0', + name: room.name, + polygon: [ + [x0, 0], + [x0 + ROOM, 0], + [x0 + ROOM, ROOM], + [x0, ROOM], + ], + spaceRole: 'room', + autoFromWalls: true, + boundaryWallIds: walls.map((wall) => wall.id), + floor: { + ...(room.floor === null ? {} : { finish: room.floor ?? PARQUET }), + ...(room.under === 'drawn' ? { sourceSlabId: `slab_${index}` } : {}), + }, + ...(room.walls === null ? {} : { wallMaterial: room.walls ?? PAINT }), + }), + ...(room.designs ?? []).map((recipe, at) => + design(`procedural-item_${index}_${at}`, recipe, [x0 + 1 + (at % 3), 0, 3]), + ), + ...(room.pieces ?? []).map((spec, at) => + piece( + `item_${index}_${at}`, + spec, + spec[2]?.at + ? [x0 + spec[2].at[0], 0, spec[2].at[1]] + : [x0 + 1 + (at % 3), 0, 1 + Math.floor(at / 3)], + ), + ), + ) + }) + return graph(...nodes) +} + +const BED: [string, string] = ['bed', 'bed-a'] +const NIGHTSTAND: [string, string] = ['nightstand', 'nightstand-a'] +const WARDROBE: [string, string] = ['wardrobe', 'wardrobe-a'] +export const BEDROOM_SET: [string, string][] = [BED, NIGHTSTAND, WARDROBE] +export const BATH_SET: [string, string][] = [ + ['toilets', 'toilet'], + ['sinks', 'sink'], + ['showers', 'shower'], +] diff --git a/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts b/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts index 9aca12349c..c84052ec32 100644 --- a/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/scene-check-cases.ts @@ -61,12 +61,27 @@ const roomZone = (id: string, levelId: string, name: string, polygon: Pt[], extr const ground = (...nodes: AnyNode[]) => scene(building(), level('level_0', 0), ...nodes) -/** A finished room on the ground floor: its walls, a door, its room zone, floor and ceiling. */ +/** A finished room on the ground floor: its walls painted on both faces, a door, its room zone with a floor and a wall finish, a floor plate and a painted ceiling. */ const finished = (tag: string, name: string, ring: Pt[] = ROOM) => [ - ...wallRing('level_0', tag, ring), - roomZone(`zone_${tag}`, 'level_0', name, ring), + ...wallRing('level_0', tag, ring).map((wall) => + wall.type === 'wall' + ? WallNode.parse({ + ...wall, + slots: { a: 'library:preset-softwhite', b: 'library:preset-softwhite' }, + }) + : wall, + ), + roomZone(`zone_${tag}`, 'level_0', name, ring, { + floor: { finish: 'library:wood-woodparquet14' }, + wallMaterial: 'library:preset-softwhite', + }), SlabNode.parse({ id: `slab_${tag}`, parentId: 'level_0', polygon: ring }), - CeilingNode.parse({ id: `ceiling_${tag}`, parentId: 'level_0', polygon: ring }), + CeilingNode.parse({ + id: `ceiling_${tag}`, + parentId: 'level_0', + polygon: ring, + slots: { surface: 'library:preset-softwhite' }, + }), ] const living = () => finished('living', 'Living') @@ -105,20 +120,39 @@ type Expect = { check?: (result: Record) => string[] } -const verify = (name: string, build: () => SceneGraph, expect: Expect): AgentToolCase => ({ - name, - tool: 'verify_scene', - scene: build, - input: {}, - ...(expect.surfaces && { surfaces: expect.surfaces }), - expect: { - result: expect.result ?? {}, - ...(expect.contains && { contains: { issues: expect.contains } }), - ...(expect.lacks && { lacks: { issues: expect.lacks } }), - ...(expect.mentions && { mentions: expect.mentions }), - ...(expect.check && { check: (result) => expect.check!(result) }), - }, -}) +/** + * A case that says "the scene is clean" (`hasIssues: false`) says it of the checks the case is + * about: these scenes have rooms and no roof, which `verify_scene` states as a fact of its own + * (`missing_roof`), so the case holds that no other issue stands. + */ +const cleanBesidesRoof = (result: Record) => + (result.issues as { type: string; severity?: string }[]) + .filter((issue) => issue.type !== 'missing_roof' && issue.severity !== 'info') + .map((issue) => `an issue stands: ${issue.type}`) + +const verify = (name: string, build: () => SceneGraph, expect: Expect): AgentToolCase => { + const { hasIssues, ...rest } = (expect.result ?? {}) as Record + const clean = hasIssues === false + return { + name, + tool: 'verify_scene', + scene: build, + input: {}, + ...(expect.surfaces && { surfaces: expect.surfaces }), + expect: { + result: clean ? rest : (expect.result ?? {}), + ...(expect.contains && { contains: { issues: expect.contains } }), + ...(expect.lacks && { lacks: { issues: expect.lacks } }), + ...(expect.mentions && { mentions: expect.mentions }), + ...((expect.check || clean) && { + check: (result: Record) => [ + ...(expect.check ? expect.check(result) : []), + ...(clean ? cleanBesidesRoof(result) : []), + ], + }), + }, + } +} const issuesOf = (result: Record, type: string) => (result.issues as { type: string; [key: string]: unknown }[]).filter( diff --git a/packages/core/src/agent-operations/dress-targets.ts b/packages/core/src/agent-operations/dress-targets.ts new file mode 100644 index 0000000000..e79a60c394 --- /dev/null +++ b/packages/core/src/agent-operations/dress-targets.ts @@ -0,0 +1,52 @@ +import type { WallNode } from '../schema' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import type { RoomWallFace } from './room-faces' + +type Plan = [number, number] + +/** What a layer is laid against: the plan corners of a fixture or a cabinet run, and the worktop of a run. */ +export type DressTarget = { id: string; corners: Plan[]; worktop?: number } + +/** How far a footprint's edge may stand from a face and still stand against it, metres. */ +export const STANDS_AGAINST_M = 0.15 + +/** The slack a footprint may sink into a face before it stands behind it instead, metres. */ +const SINK_M = 0.03 + +const millimetre = (metres: number) => Math.round(metres * 1000) / 1000 + +const aabbCorners = (box: { minX: number; maxX: number; minZ: number; maxZ: number }): Plan[] => [ + [box.minX, box.minZ], + [box.maxX, box.minZ], + [box.maxX, box.maxZ], + [box.minX, box.maxZ], +] + +/** + * The stretch of a face a target stands against, widened by `margin` and held to the stretch the room + * stands on, in metres along the wall; undefined when the target is not at the face. A target stands + * against a face when its nearest corner is within `STANDS_AGAINST_M` of the face's plane on the room's + * side. A curved face has no straight plane to measure: the caller skips it. + */ +export function standsAgainst( + wall: WallNode, + stretch: RoomWallFace, + corners: readonly Plan[], + margin: number, +): { u0: number; u1: number } | undefined { + const length = stretch.length + const dx = (wall.end[0] - wall.start[0]) / length + const dz = (wall.end[1] - wall.start[1]) / length + // Face a is on the left of start to end; both normals point into the room. + const sign = stretch.face === 'a' ? 1 : -1 + const plane = sign * getWallFaceOffsets(wall)[stretch.face] + const along = corners.map(([x, z]) => (x - wall.start[0]) * dx + (z - wall.start[1]) * dz) + const into = corners.map( + ([x, z]) => sign * (-(x - wall.start[0]) * dz + (z - wall.start[1]) * dx), + ) + const gap = Math.min(...into) - plane + if (gap > STANDS_AGAINST_M || gap < -SINK_M) return undefined + const u0 = Math.max(stretch.u0, millimetre(Math.min(...along) - margin)) + const u1 = Math.min(stretch.u1, millimetre(Math.max(...along) + margin)) + return u1 - u0 > 1e-6 ? { u0, u1 } : undefined +} diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index e598da8175..d8ddb1039b 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -36,6 +36,7 @@ import type { AgentOperation, AgentOperations } from './types' import { createUnit, listUnits, setUnitMembers } from './units' import { verifyScene } from './verify-scene' import { setWallType } from './wall-type' +import './room-checks' import './usage-checks' export * from './achieved' diff --git a/packages/core/src/agent-operations/plan-geometry.ts b/packages/core/src/agent-operations/plan-geometry.ts index 385f38f73d..ca4fff2f51 100644 --- a/packages/core/src/agent-operations/plan-geometry.ts +++ b/packages/core/src/agent-operations/plan-geometry.ts @@ -96,6 +96,18 @@ export function pointInBoundsWithPadding( ) } +/** The shortest distance from a point to the segment a–b. */ +export function distanceToSegment(point: Vec2, a: Vec2, b: Vec2): number { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const length2 = dx * dx + dz * dz + const t = + length2 === 0 + ? 0 + : Math.max(0, Math.min(1, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dz) / length2)) + return Math.hypot(point[0] - (a[0] + t * dx), point[1] - (a[1] + t * dz)) +} + export function pointOnSegment(point: Vec2, a: Vec2, b: Vec2, tolerance = 1e-6): boolean { // A segment of no length (an outline's repeated corner) is its one point, not every point. if (a[0] === b[0] && a[1] === b[1]) return distance2D(point, a) <= tolerance diff --git a/packages/core/src/agent-operations/room-checks.test.ts b/packages/core/src/agent-operations/room-checks.test.ts new file mode 100644 index 0000000000..22b04ee9ba --- /dev/null +++ b/packages/core/src/agent-operations/room-checks.test.ts @@ -0,0 +1,449 @@ +import { describe, expect, test } from 'bun:test' +import { graph } from '../coherence/__fixtures__/enclosure-scenes' +import { type AnyNode, WallNode } from '../schema' +import { + house, + MARBLE, + PAINT, + PARQUET, + type PieceSpec, + type RoomSpec, + TILE, +} from './__fixtures__/room-check-scenes' +import './index' +import { roomCheckIssues } from './room-checks' +import { finishTiled } from './room-tile' +import type { SceneNodes } from './types' + +const issuesOf = (rooms: RoomSpec[]) => roomCheckIssues(house(...rooms).nodes as SceneNodes) +const typesOf = (rooms: RoomSpec[]) => issuesOf(rooms).map((issue) => issue.type) + +describe('a wet room owes tile on its walls', () => { + const bath = (floor: string, walls: string): RoomSpec => ({ + name: 'Salle de bains', + floor, + walls, + skirting: true, + }) + test.each([ + ['bare floor and bare walls', bath(PARQUET, PAINT), ['room_wet_untiled']], + ['a tiled floor does not make up for bare walls', bath(TILE, PAINT), ['room_wet_untiled']], + ['marble underfoot does not either', bath(MARBLE, PAINT), ['room_wet_untiled']], + ['tiled walls', bath(PARQUET, TILE), []], + ['walls the nodes cannot name are not read as bare', bath(TILE, 'scene:unknown'), []], + ['a laundry is wet too', { ...bath(PARQUET, PAINT), name: 'Buanderie' }, ['room_wet_untiled']], + ['a bedroom is not', { ...bath(PARQUET, PAINT), name: 'Chambre 2' }, []], + ])('%s', (_, room, expected) => { + expect(typesOf([room]).filter((type) => type === 'room_wet_untiled')).toEqual(expected) + }) + + describe('tile to a height, and to the ceiling around the shower', () => { + const room = (extra: Partial): RoomSpec => ({ ...bath(TILE, PAINT), ...extra }) + const SHOWER: PieceSpec = [ + 'showers', + 'shower', + { size: [0.9, 2, 0.9], at: [3.5, 3.5], name: 'Douche' }, + ] + const SINK: PieceSpec = ['sinks', 'sink', { at: [2, 0.3] }] + /** The shower's corner: its stretch of the east wall and of the south wall, full height. */ + const SURROUND = [ + { wall: 1, u0: 2.95, u1: 4, finish: TILE }, + { wall: 2, u0: 0, u1: 1.05, finish: TILE }, + ] + const wet = (spec: RoomSpec) => + issuesOf([spec]).find((issue) => issue.type === 'room_wet_untiled') + + test.each([ + [ + 'a splash of 0.30 m', + room({ regions: [{ v1: 0.3, finish: TILE }] }), + 'has tile up to 0.30 m', + ], + ['tile to 0.90 m', room({ regions: [{ v1: 0.9, finish: TILE }] }), 'has tile up to 0.90 m'], + [ + 'tile to 1.2 m on a quarter of the walls', + room({ regions: [{ u1: 1, v1: 1.2, finish: TILE }] }), + 'has tile on part of its walls', + ], + ])('%s does not make a wet room tiled', (_, spec, lead) => { + expect(wet(spec)?.message).toContain(lead) + expect(wet(spec)?.message).toContain( + "dress_room ({ zoneIds: ['zone_0'], layers: [{ kind: 'tiles'", + ) + }) + + test.each([ + ['tile to 1.2 m on every wall', room({ regions: [{ v1: 1.2, finish: TILE }] })], + ['tile the full height', room({ walls: TILE })], + ['tile the full height, with a shower', room({ walls: TILE, pieces: [SHOWER] })], + [ + 'tile to 1.2 m and the shower surround to the ceiling', + room({ regions: [{ v1: 1.2, finish: TILE }, ...SURROUND], pieces: [SHOWER] }), + ], + [ + 'tile to 1.2 m where no shower stands', + room({ + regions: [{ v1: 1.2, finish: TILE }], + pieces: [['showers', 'shower', { size: [0.9, 2, 0.9], at: [2, 2] }]], + }), + ], + ])('%s does', (_, spec) => { + expect(wet(spec)).toBeUndefined() + }) + + test('a shower whose surround stops at 1.2 m is named, with the call that tiles around it', () => { + const issue = wet(room({ regions: [{ v1: 1.2, finish: TILE }], pieces: [SHOWER] })) + expect(issue?.message).toContain('not to the ceiling around its shower (Douche)') + expect(issue?.message).toContain("to: 'full', where: { around: ['item_0_0'] }") + }) + + test('the walls read are those the fixtures stand against, else all of them', () => { + const northOnly = { wall: 0, v1: 1.2, finish: TILE } + expect(wet(room({ regions: [northOnly], pieces: [SINK] }))).toBeUndefined() + expect(wet(room({ regions: [northOnly], pieces: [['sinks', 'sink']] }))).toBeDefined() + expect( + wet(room({ regions: [{ ...northOnly, wall: 1 }], pieces: [SINK] }))?.message, + ).toContain('shows no tile on the walls its fixtures stand against') + }) + }) + + describe('a finish reads as tile or not', () => { + const made = (material: object) => ({ mat_x: { id: 'mat_x', name: 'x', material } }) + const flat = { properties: { color: '#eee9df' } } + test.each([ + [ + 'a library finish of the tile kind', + { ref: 'library:flooring-tiles3', name: 'Checker Tiles', kind: 'tile' }, + undefined, + 'yes', + ], + [ + 'a library wood', + { ref: 'library:wood-woodparquet14', name: 'Wood Parquet 14', kind: 'wood' }, + undefined, + 'no', + ], + [ + 'a French tile word, accents folded', + { ref: 'scene:mat_a', name: 'Mosaïque bleue' }, + {}, + 'yes', + ], + ['grès cérame', { ref: 'scene:mat_b', name: 'Grès cérame anthracite' }, {}, 'yes'], + ['a written colour is paint', { ref: '#2f5f3f', name: '#2f5f3f' }, undefined, 'no'], + [ + 'a generated material of the tile preset', + { ref: 'scene:mat_x', name: 'Fond' }, + made({ preset: 'tile' }), + 'yes', + ], + [ + 'a generated flat colour is paint, whatever it is called', + { ref: 'scene:mat_x', name: 'Ivoire mat' }, + made(flat), + 'no', + ], + [ + 'a generated texture could be either', + { ref: 'scene:mat_x', name: 'Fond' }, + made({ ...flat, texture: { url: '/t.png' } }), + 'unknown', + ], + [ + 'a generated material the scene does not hold', + { ref: 'scene:mat_gone', name: 'scene:mat_gone' }, + {}, + 'unknown', + ], + ['an inline material', { ref: null, name: 'an inline material' }, undefined, 'unknown'], + ] as const)('%s', (_, fact, materials, expected) => { + expect(finishTiled(fact, materials as never)).toBe(expected) + }) + }) + + test('the finding names the room and what its surfaces show', () => { + const [issue] = issuesOf([bath(PARQUET, PAINT)]) + expect(issue?.message).toContain('Salle de bains (bathroom, Ground)') + expect(issue?.message).toContain('Wood Parquet 14') + expect(issue?.nodeIds).toEqual(['zone_0']) + }) +}) + +describe('rooms owe skirting', () => { + const room = (name: string, skirting: boolean): RoomSpec => ({ name, skirting }) + test.each([ + [ + 'no room of a house has any', + [room('Chambre 2', false), room('Grand salon', false), room('Bureau', false)], + 'No room of the scene', + ], + [ + 'some rooms have it and this one has not', + [room('Chambre 2', true), room('Grand salon', false)], + 'Grand salon have no skirting while Chambre 2 do', + ], + ])('%s', (_, rooms, wording) => { + const issues = issuesOf(rooms).filter((issue) => issue.type === 'rooms_no_skirting') + expect(issues).toHaveLength(1) + expect(issues[0]?.message).toContain(wording) + }) + + test.each([ + ['every room has it', [room('Chambre 2', true), room('Grand salon', true)]], + [ + 'wet rooms and garages are not asked for it', + [room('Salle de bains', false), room('Garage', false)], + ], + ['a room or two is not a house', [room('Chambre 2', false), room('Grand salon', false)]], + ])('%s: nothing to say', (_, rooms) => { + expect(typesOf(rooms)).not.toContain('rooms_no_skirting') + }) +}) + +describe('surfaces nobody gave a finish', () => { + const bed = (name: string, extra: Partial = {}): RoomSpec => ({ + name, + skirting: true, + ceiling: PAINT, + ...extra, + }) + const finding = (rooms: RoomSpec[], type: string) => + issuesOf(rooms).find((issue) => issue.type === type) + const four = (extra: Partial, name = 'Robe 2') => [ + bed('Bed 1'), + bed('Bed 2'), + bed('Bed 3'), + bed(name, extra), + ] + + test('wall faces at the default are named by wall, with where they run and the room they face', () => { + const issue = finding(four({ walls: null }), 'wall_faces_default') + expect(issue?.message).toBe( + 'Wall faces at the default, no finish written for them: “wall_r3_0” (Ground): face a 3.90 m facing Robe 2, from 15.05, 0 to 18.95, 0, “wall_r3_1” (Ground): face a 3.90 m facing Robe 2, from 19, 0.05 to 19, 3.95, “wall_r3_2” (Ground): face a 3.90 m facing Robe 2, from 18.95, 4 to 15.05, 4, “wall_r3_3” (Ground): face a 3.90 m facing Robe 2, from 15, 3.95 to 15, 0.05; 4 of 32 wall faces read (15.6 of 126.4 m) show the default.', + ) + expect(issue?.nodeIds).toEqual(['wall_r3_0', 'wall_r3_1', 'wall_r3_2', 'wall_r3_3']) + expect(typesOf(four({}))).not.toContain('wall_faces_default') + }) + + test('a face with a painted stretch, or in a room that wrote a finish, is not at the default there', () => { + const painted = four({ walls: null, regions: [{ wall: 0, v1: 1.2, finish: TILE }] }) + expect(finding(painted, 'wall_faces_default')?.message).toContain('3 of 32') + expect(finding(painted, 'wall_faces_default')?.nodeIds).toEqual([ + 'wall_r3_1', + 'wall_r3_2', + 'wall_r3_3', + ]) + const halfPainted = four({ walls: null, regions: [{ wall: 0, u1: 1.5, finish: TILE }] }) + expect(finding(halfPainted, 'wall_faces_default')?.message).toContain( + '“wall_r3_0” (Ground): face a 2.45 m facing Robe 2, from 16.5, 0 to 18.95, 0', + ) + expect(typesOf(four({ walls: PAINT }))).not.toContain('wall_faces_default') + }) + + describe('a face is read on the wall, whatever room looks at it', () => { + const wall = (extra: Record) => + WallNode.parse({ + parentId: 'level_0', + frontSide: 'interior', + backSide: 'interior', + ...extra, + }) + const rooms = [bed('Bed 1'), bed('Bed 2'), bed('Bed 3')] + const withWalls = (...extra: WallNode[]) => + graph(...(Object.values(house(...rooms).nodes) as AnyNode[]), ...extra).nodes as SceneNodes + const read = (...extra: WallNode[]) => + roomCheckIssues(withWalls(...extra), {}).find((issue) => issue.type === 'wall_faces_default') + const FINISHED = { slots: { a: PAINT, b: PAINT } } + + test('a stub that stands inside a room, on no boundary, is named with the room it stands in', () => { + const stub = wall({ id: 'wall_stub', name: 'Hall stub', start: [1, 2], end: [2, 2] }) + expect(read(stub)?.message).toBe( + 'Wall faces at the default, no finish written for them: “Hall stub” (Ground): both faces 1.00 m inside Bed 1, from 1, 2 to 2, 2; 2 of 26 wall faces read (2.0 of 96.8 m) show the default.', + ) + expect(read(stub)?.nodeIds).toEqual(['wall_stub']) + expect( + read(wall({ id: 'wall_stub', start: [1, 2], end: [2, 2], ...FINISHED })), + ).toBeUndefined() + }) + + test('a face with no room on its side is read: a free wall, an outside face', () => { + const free = wall({ id: 'wall_free', name: 'Garden wall', start: [30, 0], end: [33, 0] }) + expect(read(free)?.message).toContain( + '“Garden wall” (Ground): both faces 3.00 m with no room on that side, from 30, 0 to 33, 0', + ) + const outside = roomCheckIssues( + house(...rooms.slice(0, 2), bed('Bed 3', { outside: null })).nodes as SceneNodes, + {}, + ).find((issue) => issue.type === 'wall_faces_default') + expect(outside?.message).toContain('face b 4.00 m with no room on that side') + expect(outside?.nodeIds).toEqual(['wall_r2_0', 'wall_r2_1', 'wall_r2_2', 'wall_r2_3']) + }) + + test('an outside face shows its assembly cladding, so it is not at the default', () => { + const clad = (assembly: object) => + wall({ + id: 'wall_clad', + thickness: 0.2524, + start: [30, 0], + end: [33, 0], + backSide: 'exterior', + assembly, + slots: { a: PAINT }, + }) + const layers = (finish: boolean) => ({ + layers: [ + { id: 'lining', role: 'lining', thickness: 0.0127 }, + { id: 'studs', role: 'structure', thickness: 0.1397, core: true }, + ...(finish ? [{ id: 'brick', role: 'finish', material: 'brick', thickness: 0.1 }] : []), + ], + }) + expect(read(clad(layers(true)))).toBeUndefined() + expect(read(clad(layers(false)))?.message).toContain('“wall_clad” (Ground): face b 3.00 m') + }) + + test('a stretch of a face inside another wall’s body is no face', () => { + // The stub runs on into a 0.3 m wall whose centre line is at z = 1: its last 0.15 m is buried. + const body = wall({ + id: 'wall_body', + start: [0.5, 1], + end: [3.5, 1], + thickness: 0.3, + ...FINISHED, + }) + const stub = wall({ id: 'wall_stub', name: 'Hall stub', start: [2, 2.5], end: [2, 1] }) + expect(read(body, stub)?.message).toContain( + '“Hall stub” (Ground): both faces 1.35 m inside Bed 1, from 2, 2.5 to 2, 1.15', + ) + // A wall lower than the stub buries nothing of it; one at its own height or more does. + const low = wall({ + id: 'wall_body', + start: [0.5, 1], + end: [3.5, 1], + thickness: 0.3, + height: 1, + ...FINISHED, + }) + expect(read(low, stub)?.message).toContain('both faces 1.50 m') + // A stretch that is all buried is not read at all. + const buried = wall({ id: 'wall_buried', start: [2, 1.1], end: [2, 0.9] }) + expect(read(body, buried)).toBeUndefined() + }) + + test('the end of a wall that overshoots its neighbour is no face, so a finished wall is no finding', () => { + const long = wall({ id: 'wall_long', start: [0.5, 3.8], end: [3.5, 3.8], ...FINISHED }) + const over = wall({ id: 'wall_over', start: [2, 1.5], end: [2, 3.9], ...FINISHED }) + expect(read(long, over)).toBeUndefined() + const bare = wall({ id: 'wall_over', start: [2, 1.5], end: [2, 3.9] }) + expect(read(long, bare)?.message).toContain('both faces 2.25 m') + }) + }) + + test('a floor at the default is a finding; a ceiling at its default is normal and is not', () => { + const rooms = [ + bed('Bed 1'), + bed('Bed 2'), + bed('Bed 3'), + bed('Robe 2', { floor: null, ceiling: 'default' }), + ] + expect(finding(rooms, 'rooms_floors_default')?.message).toBe( + 'Floors at the default, no finish written for them: Robe 2; the other 3 rooms read show a finish.', + ) + expect(typesOf(rooms).filter((type) => type.includes('ceiling'))).toEqual([]) + }) + + test('a room whose floor is a drawn slab with a surface of its own has a floor', () => { + const drawn = bed('Garage', { floor: null, under: 'drawn' }) + expect(typesOf([bed('Bed 1'), bed('Bed 2'), bed('Bed 3'), drawn])).toContain( + 'rooms_floors_default', + ) + const slab = house(bed('Bed 1'), bed('Bed 2'), bed('Bed 3'), drawn).nodes + const painted = { + ...slab, + slab_3: { ...slab.slab_3, slots: { surface: PARQUET } }, + } + expect(roomCheckIssues(painted as SceneNodes, {}).map((issue) => issue.type)).not.toContain( + 'rooms_floors_default', + ) + }) + + test('every room at the default is said when there are three, and not for a room or two', () => { + const bare = (name: string): RoomSpec => ({ + name, + floor: null, + walls: null, + outside: null, + ceiling: 'default', + }) + const three = issuesOf([bare('Bed 1'), bare('Bed 2'), bare('Bed 3')]) + expect(three.find((issue) => issue.type === 'rooms_floors_default')?.message).toBe( + 'Floors at the default, no finish written for them: Bed 1, Bed 2, Bed 3 (all 3 rooms read).', + ) + expect(three.find((issue) => issue.type === 'wall_faces_default')?.message).toContain( + '24 of 24 wall faces read (94.8 of 94.8 m) show the default', + ) + expect(three.filter((issue) => issue.type.includes('ceiling'))).toEqual([]) + const two = typesOf([bare('Bed 1'), bare('Bed 2')]) + for (const type of ['wall_faces_default', 'rooms_floors_default']) + expect(two).not.toContain(type) + }) + + test('an outdoor room is owed no floor, and its walls are read like any wall', () => { + const rooms = [ + bed('Bed 1'), + bed('Bed 2'), + bed('Bed 3'), + { name: 'Alfresco', floor: null, walls: null } as RoomSpec, + ] + expect(typesOf(rooms)).not.toContain('rooms_floors_default') + expect(finding(rooms, 'wall_faces_default')?.message).toContain('facing Alfresco') + }) +}) + +describe('skirting on part of a room', () => { + const bed = (name: string, skirting: RoomSpec['skirting']): RoomSpec => ({ name, skirting }) + + test('a room skirted on some of its faces is named with how many, and is not a room with none', () => { + const issues = issuesOf([bed('Bed 1', true), bed('Bed 2', 'some'), bed('Bed 3', true)]) + expect(issues.find((issue) => issue.type === 'rooms_skirting_partial')).toMatchObject({ + message: + 'Skirting is on part of the wall faces of Bed 2 (2 of 4 faces): 1 room of the 3 rooms that owe it.', + nodeIds: ['zone_1'], + }) + expect(issues.map((issue) => issue.type)).not.toContain('rooms_no_skirting') + }) + + test('every face, or none, is not part', () => { + expect(typesOf([bed('Bed 1', true), bed('Bed 2', true), bed('Bed 3', true)])).not.toContain( + 'rooms_skirting_partial', + ) + const none = typesOf([bed('Bed 1', false), bed('Bed 2', false), bed('Bed 3', false)]) + expect(none).toContain('rooms_no_skirting') + expect(none).not.toContain('rooms_skirting_partial') + }) + + test('a room that owes none (a robe, a garage) is not read', () => { + expect( + typesOf([bed('Bed 1', true), bed('Robe 1', 'some'), bed('Garage', 'some')]), + ).not.toContain('rooms_skirting_partial') + }) +}) + +describe('a room with nothing under it', () => { + const room = (name: string, under?: RoomSpec['under']): RoomSpec => ({ name, under }) + const issue = (rooms: RoomSpec[]) => issuesOf(rooms).find((i) => i.type === 'room_no_floor') + + test('no plate and no slab under it is named, with its level', () => { + expect(issue([room('Bed 1'), room('Bed 2', 'none')])).toMatchObject({ + message: expect.stringContaining('No floor plate or slab is under Bed 2 (Ground)'), + nodeIds: ['zone_1'], + }) + }) + + test('a drawn slab it was taken from is a floor: a garage slab lowered by hand', () => { + expect(issue([room('Bed 1'), room('Garage', 'drawn')])).toBeUndefined() + }) + + test('an outdoor room is not read', () => { + expect(issue([room('Bed 1'), room('Alfresco', 'none')])).toBeUndefined() + }) +}) diff --git a/packages/core/src/agent-operations/room-checks.ts b/packages/core/src/agent-operations/room-checks.ts new file mode 100644 index 0000000000..76b73450ff --- /dev/null +++ b/packages/core/src/agent-operations/room-checks.ts @@ -0,0 +1,307 @@ +import { isSkirtedRoomUse, isWetRoomUse } from '../building/room-use' +import type { SceneMaterial } from '../schema' +import { finishWords } from './room-finishes' +import { type RoomReading, readRooms } from './room-readings' +import { WET_TILED_TO_M } from './room-wet' +import type { SceneNodes } from './types' +import { registerSceneCheck } from './verify-scene' +import { type DefaultWallFace, readWallFaces, type WallFaceReading } from './wall-face-defaults' +import { wallItemFaceIssues } from './wall-item-faces' +import { outsideFinishInside } from './wall-outside-finish' + +/** + * What the rooms of a scene owe, checked at the end of a turn: a wet room with no tile, rooms with no + * skirting, a piece hung on the face of the wall that looks into another room than the one it names. + * Like the coherence checks they guide and never forbid: each says what the scene shows and leaves + * the maker to fix it or keep it. A finding fires only where the nodes can be read to the end (an + * inline material, a script-built face or a scene ref with no scene materials is `unknown`, and + * unknown fires nothing). + */ + +export const ROOM_CHECK_CODES = [ + 'room_wet_untiled', + 'rooms_no_skirting', + 'rooms_skirting_partial', + 'wall_faces_default', + 'rooms_floors_default', + 'room_no_floor', + 'walls_outside_finish_inside', + 'room_wall_item_wrong_face', +] as const +export type RoomCheckCode = (typeof ROOM_CHECK_CODES)[number] + +export type RoomCheckIssue = { + type: RoomCheckCode + message: string + severity: 'warning' + nodeIds: string[] +} + +const WORDS_SHOWN = 6 + +/** Names as a sentence lists them: the first few, then how many more. */ +const listed = (names: readonly string[]) => + names.length <= WORDS_SHOWN + ? names.join(', ') + : `${names.slice(0, WORDS_SHOWN).join(', ')} and ${names.length - WORDS_SHOWN} more` + +const finishes = (room: RoomReading) => + `its floor is ${room.floor.finish} and its walls ${room.walls.finishes.join(', ') || 'unfinished'}` + +const metres = (value: number) => `${value.toFixed(2)} m` + +/** + * A wet room (bathroom, shower room, WC, laundry) whose walls are not tiled as a wet room is: to + * `WET_TILED_TO_M` on the walls its fixtures stand against, and to the ceiling around its shower. A + * tiled floor does not make up for walls that splash. + */ +export function wetRoomIssues(rooms: readonly RoomReading[]): RoomCheckIssue[] { + return rooms.flatMap((room): RoomCheckIssue[] => { + const wet = room.wet + if (wet?.verdict !== 'no' || !isWetRoomUse(room.use)) return [] + const where = wet.byFixtures ? 'the walls its fixtures stand against' : 'its walls' + const dress = (layer: string) => + `dress_room ({ zoneIds: ['${room.id}'], layers: [{ kind: 'tiles', finish: '', ${layer} }] }) lays it` + const bareShower = wet.showers.find((shower) => shower.full === 'no') + const [lead, fix] = + wet.tiled === 'no' + ? [ + !wet.anyTile + ? `shows no tile on ${where}` + : wet.tiledTo && wet.tiledTo > 0.05 + ? `has tile up to ${metres(wet.tiledTo)} on ${where}` + : `has tile on part of ${where}, along less than most of their length`, + dress(`to: ${WET_TILED_TO_M}`), + ] + : [ + `is tiled to ${metres(WET_TILED_TO_M)} but not to the ceiling around its shower (${bareShower?.name})`, + dress(`to: 'full', where: { around: ['${bareShower?.id}'] }`), + ] + return [ + { + type: 'room_wet_untiled', + message: `${room.name} (${room.use}, ${room.levelName}) ${lead}: ${finishes(room)}. A wet room is usually tiled to ${metres(WET_TILED_TO_M)} on the walls its fixtures stand against and to the ceiling around its shower, whatever its floor; ${fix}, or keep the finish if it is intended.`, + severity: 'warning', + nodeIds: [room.id], + }, + ] + }) +} + +/** + * Fewer rooms than this are a room or two, not a house: bare wall bases there say nothing of a + * finishing recipe, and a scene of one room is mostly a test or a demonstration. + */ +const HOUSE_MIN_ROOMS = 3 + +/** + * Skirting, from the faces of a room's walls: the rooms a finished floor meets in view (bedrooms, + * living and dining rooms, offices, hallways) that have none on any face. When some rooms have it + * the finding names the ones left bare; when none has it, it is about the scene, and only for a + * house of at least `HOUSE_MIN_ROOMS` such rooms. Rooms with no known wall face are not read. + */ +export function skirtingIssue(rooms: readonly RoomReading[]): RoomCheckIssue | null { + const bare = rooms.filter( + (room) => isSkirtedRoomUse(room.use) && room.skirting.faces > 0 && !room.skirting.withSkirting, + ) + if (!bare.length) return null + const skirted = rooms.filter((room) => room.skirting.withSkirting > 0) + const nodeIds = bare.map((room) => room.id) + if (!skirted.length) + return bare.length < HOUSE_MIN_ROOMS + ? null + : { + type: 'rooms_no_skirting', + message: `No room of the scene has skirting: ${listed(bare.map((room) => room.name))} (${bare.length}) show bare wall bases. set_wall_trim sets it ({ kind: 'skirting', zoneIds } with these rooms' ids), as does a skirting layer of dress_room, or keep the bare bases if they are intended.`, + severity: 'warning', + nodeIds, + } + return { + type: 'rooms_no_skirting', + message: `${listed(bare.map((room) => room.name))} have no skirting while ${listed(skirted.map((room) => room.name))} do. set_wall_trim sets it ({ kind: 'skirting', zoneIds } with these rooms' ids), as does a skirting layer of dress_room, or keep them bare if that is intended.`, + severity: 'warning', + nodeIds, + } +} + +/** + * Skirting on part of a room's faces: a room the skirting is owed in (see `skirtingIssue`) that has it + * on some of the wall faces looking in and not on the others. A room with none is `skirtingIssue`'s. + */ +export function partialSkirtingIssue(rooms: readonly RoomReading[]): RoomCheckIssue | null { + const partial = rooms.filter( + (room) => + isSkirtedRoomUse(room.use) && + room.skirting.withSkirting > 0 && + room.skirting.withSkirting < room.skirting.faces, + ) + if (!partial.length) return null + return { + type: 'rooms_skirting_partial', + message: `Skirting is on part of the wall faces of ${listed( + partial.map( + (room) => `${room.name} (${room.skirting.withSkirting} of ${room.skirting.faces} faces)`, + ), + )}: ${plural(partial.length, 'room')} of the ${plural(rooms.filter((room) => isSkirtedRoomUse(room.use)).length, 'room')} that owe it.`, + severity: 'warning', + nodeIds: partial.map((room) => room.id), + } +} + +/** Rooms with no floor under them: no plate of their own, no drawn slab they were taken from, and slabs over less than half their footprint. */ +export function noFloorIssue(rooms: readonly RoomReading[]): RoomCheckIssue | null { + const bare = rooms.filter((room) => room.indoor && !room.floor.held) + if (!bare.length) return null + return { + type: 'room_no_floor', + message: `No floor plate or slab is under ${listed(bare.map((room) => `${room.name} (${room.levelName})`))}: slabs cover less than half of ${bare.length === 1 ? 'its footprint' : 'each footprint'}.`, + severity: 'warning', + nodeIds: bare.map((room) => room.id), + } +} + +const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}` + +/** + * The floors of the indoor rooms that show the default, as one finding that names the rooms and + * says how many other rooms show a finish. Fewer than `HOUSE_MIN_ROOMS` rooms all at the default + * are a test or a demonstration and say nothing. A ceiling at its default is normal and is not + * read; the wall faces are read apart (`wallFaceDefaultIssue`): by wall, not through a room. + */ +export function floorDefaultIssue(rooms: readonly RoomReading[]): RoomCheckIssue | null { + const indoor = rooms.filter((room) => room.indoor) + const bare = indoor.filter((room) => room.floor.atDefault) + if (!bare.length || (bare.length === indoor.length && indoor.length < HOUSE_MIN_ROOMS)) + return null + return { + type: 'rooms_floors_default', + message: `Floors at the default, no finish written for them: ${listed(bare.map((room) => room.name))}${ + bare.length === indoor.length + ? ` (all ${plural(indoor.length, 'room')} read)` + : `; the other ${plural(indoor.length - bare.length, 'room')} read show a finish` + }.`, + severity: 'warning', + nodeIds: bare.map((room) => room.id), + } +} + +const two = (value: number) => value.toFixed(2) +const spot = (point: readonly [number, number]) => `${point[0]}, ${point[1]}` + +/** Where a default face is, as the finding says it: the rooms it faces, or the room its wall stands in. */ +const placeOf = (face: DefaultWallFace) => + face.facing.length + ? `facing ${listed(face.facing)}` + : face.standsIn.length + ? `inside ${listed(face.standsIn)}` + : 'with no room on that side' + +/** One wall's default faces as a clause: both faces together when they are alike, else each face. */ +function wallClause(faces: readonly DefaultWallFace[]): string { + const [one] = faces + const alike = + faces.length === 2 && + Math.abs(faces[0]!.metres - faces[1]!.metres) < 0.01 && + placeOf(faces[0]!) === placeOf(faces[1]!) + const how = alike + ? `both faces ${two(faces[0]!.metres)} m ${placeOf(faces[0]!)}` + : faces.map((face) => `face ${face.face} ${two(face.metres)} m ${placeOf(face)}`).join(', ') + const first = faces.reduce((a, b) => (b.stretches[0]![0] < a.stretches[0]![0] ? b : a)) + const last = faces.reduce((a, b) => (b.stretches.at(-1)![1] > a.stretches.at(-1)![1] ? b : a)) + return `“${one!.wallName}” (${one!.levelName}): ${how}, from ${spot(first.from)} to ${spot(last.to)}` +} + +/** + * The wall faces nobody gave a finish, read from the walls themselves (`readWallFaces`): one finding + * that names each wall with its default faces, how long they are, where they run in plan and which + * room they face (or stand inside), and how many of the faces read show the default. The walls of a + * scene of fewer than `HOUSE_MIN_ROOMS` rooms whose faces are all at the default are a test or a + * demonstration and say nothing. + */ +export function wallFaceDefaultIssue( + read: WallFaceReading, + roomsRead: number, +): RoomCheckIssue | null { + if (!read.defaults.length) return null + const bare = new Set(read.defaults.map((face) => `${face.wallId}/${face.face}`)).size + if (bare >= read.faces && roomsRead < HOUSE_MIN_ROOMS) return null + const byWall = new Map() + for (const face of read.defaults) + byWall.set(face.wallId, [...(byWall.get(face.wallId) ?? []), face]) + const metres = read.defaults.reduce((sum, face) => sum + face.metres, 0) + const total = (faces: readonly DefaultWallFace[]) => + Math.round(faces.reduce((sum, face) => sum + face.metres, 0) * 100) + const longest = [...byWall.values()].sort((p, q) => total(q) - total(p)) + return { + type: 'wall_faces_default', + message: `Wall faces at the default, no finish written for them: ${listed(longest.map(wallClause))}; ${bare} of ${plural(read.faces, 'wall face')} read (${metres.toFixed(1)} of ${read.metres.toFixed(1)} m) show the default.`, + severity: 'warning', + nodeIds: [...byWall.keys()], + } +} + +/** + * The finish of an outside face on the inside face of the same wall: the walls whose two faces show + * one finish, indoor rooms on one face and none on the other, where no partition of the scene shows + * that finish. One finding per finish, with the walls' total length and the rooms that look at them. + */ +export function outsideFinishInsideIssues( + nodes: SceneNodes, + materials?: Readonly>, +): RoomCheckIssue[] { + return outsideFinishInside(nodes, materials).map(({ finish, walls, partitions }) => { + const rooms = [...new Set(walls.flatMap((wall) => wall.rooms))] + const metres = walls.reduce((sum, wall) => sum + wall.lengthM, 0) + return { + type: 'walls_outside_finish_inside', + message: `${finishWords(finish)} shows on both faces of ${plural(walls.length, 'wall')} (${metres.toFixed(1)} m): the outside face and the inside face, which looks into ${listed(rooms)}${ + partitions.length + ? `; the partitions of the scene show ${partitions.map((other) => other.name).join(' and ')}` + : '' + }.`, + severity: 'warning', + nodeIds: walls.map((wall) => wall.id), + } + }) +} + +/** Every room check on a scene. */ +export function roomCheckIssues( + nodes: SceneNodes, + options: { materials?: Readonly> } = {}, +): RoomCheckIssue[] { + const rooms = readRooms(nodes, { materials: options.materials }) + const wallFaces = wallFaceDefaultIssue( + readWallFaces(nodes), + rooms.filter((room) => room.indoor).length, + ) + if (!rooms.length) return wallFaces ? [wallFaces] : [] + const skirting = skirtingIssue(rooms) + const partial = partialSkirtingIssue(rooms) + const noFloor = noFloorIssue(rooms) + const floors = floorDefaultIssue(rooms) + return [ + ...wetRoomIssues(rooms), + ...(skirting ? [skirting] : []), + ...(partial ? [partial] : []), + ...(noFloor ? [noFloor] : []), + ...(wallFaces ? [wallFaces] : []), + ...(floors ? [floors] : []), + ...outsideFinishInsideIssues(nodes, options.materials), + ...wallItemFaceIssues(nodes), + ] +} + +registerSceneCheck({ + name: 'room checks', + order: 70, + run: (nodes, _input, context) => { + try { + return roomCheckIssues(nodes as SceneNodes, { materials: context?.materials }) + } catch { + // A scene the readers cannot walk (a wall stored without its start) is the schema check's to + // report, not a reason for verify_scene to fail. + return [] + } + }, +}) diff --git a/packages/core/src/agent-operations/room-faces.test.ts b/packages/core/src/agent-operations/room-faces.test.ts new file mode 100644 index 0000000000..1f760e0778 --- /dev/null +++ b/packages/core/src/agent-operations/room-faces.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from 'bun:test' +import type { ZoneNode } from '../schema' +import { twoRooms } from './__fixtures__/dressing-scenes' +import { roomBoundaryWalls, roomWallFaces } from './room-faces' +import type { SceneNodes } from './types' + +const faces = (zone: string, overrides?: Parameters[0]) => { + const nodes = twoRooms(overrides).nodes as SceneNodes + return roomWallFaces(nodes, nodes[zone] as ZoneNode) +} +const byWall = (list: ReturnType) => + Object.fromEntries(list.map((f) => [f.wallId, f])) + +describe('the faces that look into a room', () => { + test('a partition gives each room its own face, and the faces are opposite', () => { + const [salon, bath] = [byWall(faces('zone_salon')), byWall(faces('zone_bath'))] + expect(salon.wall_p?.face).toBeDefined() + expect(bath.wall_p?.face).toBeDefined() + expect(salon.wall_p?.face).not.toBe(bath.wall_p?.face) + expect(Object.keys(salon).sort()).toEqual(['wall_an', 'wall_p', 'wall_s', 'wall_w']) + expect(Object.keys(bath).sort()).toEqual(['wall_bn', 'wall_e', 'wall_p', 'wall_s']) + }) + + test('a wall that runs on past the room gives only the stretch the room stands on', () => { + const [salon, bath] = [byWall(faces('zone_salon')), byWall(faces('zone_bath'))] + expect(salon.wall_s).toMatchObject({ t0: 0, t1: 0.5, u0: 0, u1: 4, length: 8, whole: false }) + expect(bath.wall_s).toMatchObject({ t0: 0.5, t1: 1, u0: 4, u1: 8, length: 8, whole: false }) + expect(salon.wall_s?.face).toBe(bath.wall_s?.face) + expect(salon.wall_w).toMatchObject({ u0: 0, u1: 3, length: 3, whole: true }) + }) + + test('a curtain wall carries no finish', () => { + expect( + faces('zone_salon', { walls: { wall_an: { wallType: 'curtain' } } }).map((f) => f.wallId), + ).not.toContain('wall_an') + const nodes = twoRooms({ walls: { wall_an: { wallType: 'curtain' } } }).nodes as SceneNodes + expect(roomBoundaryWalls(nodes, nodes.zone_salon as ZoneNode).map((w) => w.id)).toEqual([ + 'wall_s', + 'wall_p', + 'wall_w', + ]) + }) +}) diff --git a/packages/core/src/agent-operations/room-faces.ts b/packages/core/src/agent-operations/room-faces.ts new file mode 100644 index 0000000000..6f6761421c --- /dev/null +++ b/packages/core/src/agent-operations/room-faces.ts @@ -0,0 +1,56 @@ +import type { WallFace, WallNode, ZoneNode } from '../schema' +import { isCurvedWall } from '../systems/wall/wall-curve' +import { getWallZoneSpans } from '../systems/wall/wall-finish' +import type { SceneNodes } from './types' + +/** + * A stretch of one face of one wall that a room stands on: the unit every room-level wall write + * and read works in. `u0..u1` are metres from the wall's start along its reference line (along the + * chord for a curved wall), the coordinates a face's paint regions use; `whole` is a stretch that + * runs the face's full length, so a region over it can leave `u` unbounded and follow the wall when + * it is lengthened. + */ +export type RoomWallFace = { + wallId: string + face: WallFace + t0: number + t1: number + u0: number + u1: number + /** The wall's reference length (its chord), metres. */ + length: number + whole: boolean + curved: boolean +} + +const WHOLE = 1e-3 + +/** The walls that bound a room and carry a finish: its boundary walls, curtain walls left out. */ +export function roomBoundaryWalls(nodes: SceneNodes, zone: ZoneNode): WallNode[] { + return (zone.boundaryWallIds ?? []) + .map((id) => nodes[id]) + .filter((wall): wall is WallNode => wall?.type === 'wall' && wall.wallType !== 'curtain') +} + +/** + * The faces that look into a room, a stretch each, in the order of the room's boundary walls: for a + * partition the face of this room and not the other's, for a wall that runs on past the room only the + * stretch the room stands on. + */ +export function roomWallFaces(nodes: SceneNodes, zone: ZoneNode): RoomWallFace[] { + return roomBoundaryWalls(nodes, zone).flatMap((wall) => { + const length = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + const curved = isCurvedWall(wall) + return getWallZoneSpans(wall, [zone]).map((span) => ({ + wallId: wall.id, + face: span.face, + t0: span.t0, + t1: span.t1, + u0: span.t0 * length, + u1: span.t1 * length, + length, + whole: span.t0 < WHOLE && span.t1 > 1 - WHOLE, + curved, + })) + }) +} diff --git a/packages/core/src/agent-operations/room-finishes.test.ts b/packages/core/src/agent-operations/room-finishes.test.ts new file mode 100644 index 0000000000..941bfcc94b --- /dev/null +++ b/packages/core/src/agent-operations/room-finishes.test.ts @@ -0,0 +1,291 @@ +import { describe, expect, test } from 'bun:test' +import type { AnyNode, SceneMaterial, ZoneNode } from '../schema' +import { paintedKitchenScene } from './__fixtures__/room-cases' +import { + changedFinishes, + describeFinish, + finishWords, + levelFinishes, + roomFinishes, +} from './room-finishes' +import { nodesOnLevel } from './scene-queries' + +const scene = () => paintedKitchenScene().nodes as Record + +describe('describeFinish', () => { + test('nothing written, an empty string and null read as the default', () => { + for (const none of [undefined, null, '']) + expect(describeFinish(none)).toEqual({ ref: null, name: 'default' }) + }) + + test('a library ref reads as its name, kind and colour', () => { + expect(describeFinish('library:preset-softwhite')).toEqual({ + ref: 'library:preset-softwhite', + name: 'Soft White', + kind: 'colors', + color: '#ebe7df', + }) + }) + + test('a textured library material reads the preview colour the library gives it', () => { + expect(describeFinish('library:wood-floorplank1')).toMatchObject({ + name: 'Floor Plank 1', + kind: 'wood', + color: '#bf8552', + }) + }) + + test('a ref the library does not know, and a bare word, read as themselves', () => { + expect(describeFinish('library:nowhere')).toEqual({ + ref: 'library:nowhere', + name: 'library:nowhere', + }) + expect(describeFinish('wood')).toEqual({ ref: 'wood', name: 'wood' }) + }) + + test('a scene material reads as its name and colour; one the scene lacks reads as its ref', () => { + const limewash: SceneMaterial = { + id: 'mat_lime', + name: 'Warm limewash', + material: { + properties: { + color: '#cfc3ae', + roughness: 0.8, + metalness: 0, + opacity: 1, + transparent: false, + side: 'front', + }, + }, + } + expect(describeFinish('scene:mat_lime', { mat_lime: limewash })).toEqual({ + ref: 'scene:mat_lime', + name: 'Warm limewash', + color: '#cfc3ae', + }) + expect(describeFinish('scene:mat_lime')).toEqual({ + ref: 'scene:mat_lime', + name: 'scene:mat_lime', + }) + }) + + test('an inline material reads as one, with the colour it carries', () => { + expect(describeFinish({ properties: { color: '#112233' } })).toEqual({ + ref: null, + name: 'an inline material', + color: '#112233', + }) + expect(describeFinish({ material: { properties: { color: '#445566' } } })).toMatchObject({ + color: '#445566', + }) + expect(describeFinish({})).toEqual({ ref: null, name: 'an inline material' }) + }) +}) + +describe('finishWords', () => { + test('a name, then the ref and colour it has', () => { + expect(finishWords(describeFinish('library:preset-softwhite'))).toBe( + 'Soft White (library:preset-softwhite, #ebe7df)', + ) + expect(finishWords(describeFinish('library:wood-floorplank1'))).toBe( + 'Floor Plank 1 (library:wood-floorplank1, #bf8552)', + ) + expect(finishWords(describeFinish(undefined))).toBe('default') + expect(finishWords(describeFinish('wood'))).toBe('wood') + }) +}) + +describe('roomFinishes', () => { + test('a room with no floor reads none, and one with no ceiling reads none', () => { + const nodes = scene() + nodes.zone_pantry = { ...(nodes.zone_pantry as ZoneNode), hasFloor: false, hasCeiling: false } + const content = nodesOnLevel(nodes, 'level_rooms') + const shown = roomFinishes(nodes, nodes.zone_pantry as ZoneNode, content) + expect(shown.floor).toBeUndefined() + expect(shown.ceiling).toBeUndefined() + expect(shown.walls?.faces).toBe(2) + }) + + test('the painted parts of a floor are named apart and leave the finish the room shows alone', () => { + const nodes = scene() + nodes.zone_kitchen = { + ...(nodes.zone_kitchen as ZoneNode), + floor: { + finish: 'library:preset-sand', + regions: [ + { + id: 'rug', + polygon: [ + [1, 1], + [2, 1], + [2, 2], + ], + finish: 'library:preset-cream', + }, + ], + }, + } + const shown = roomFinishes( + nodes, + nodes.zone_kitchen as ZoneNode, + nodesOnLevel(nodes, 'level_rooms'), + ) + expect(shown.floor).toMatchObject({ ref: 'library:preset-sand', name: 'Sand' }) + expect(shown.floor?.regions).toEqual([ + { id: 'rug', finish: describeFinish('library:preset-cream') }, + ]) + const palette = levelFinishes(nodes, 'level_rooms') + expect(palette?.floors?.[0]).toEqual({ + finish: describeFinish('library:preset-sand'), + rooms: ['Kitchen'], + }) + }) + + test('a wall with a finish of its own shows it where the room gives none', () => { + const nodes = scene() + nodes.zone_kitchen = { + ...(nodes.zone_kitchen as ZoneNode), + wallMaterial: undefined, + wallOverrides: [], + } + nodes.wall_west = { + ...(nodes.wall_west as AnyNode), + slots: { a: 'library:preset-sage', b: 'library:preset-sage' }, + } as AnyNode + const shown = roomFinishes( + nodes, + nodes.zone_kitchen as ZoneNode, + nodesOnLevel(nodes, 'level_rooms'), + ) + expect(shown.walls?.faces).toBe(4) + expect(shown.walls?.finishes).toEqual([ + { finish: { ref: null, name: 'default' }, faces: 3 }, + { finish: describeFinish('library:preset-sage'), faces: 1 }, + ]) + }) +}) + +describe('a floor plate that carries a surface of its own', () => { + const withPlateSurface = (surface: Record) => { + const nodes = scene() + const plate = Object.values(nodes).find( + (node) => node.type === 'slab' && node.plateRole === 'base', + )! + nodes[plate.id] = { ...plate, ...surface } as AnyNode + return nodes + } + + test('it shows in the rooms that have no floor finish of their own, and not in those that do', () => { + const nodes = withPlateSurface({ slots: { surface: 'library:preset-cream' } }) + nodes.zone_kitchen = { + ...(nodes.zone_kitchen as ZoneNode), + floor: { finish: 'library:preset-sand' }, + } + const floors = levelFinishes(nodes, 'level_rooms')?.floors + expect(floors).toEqual([ + { finish: describeFinish('library:preset-sand'), rooms: ['Kitchen'] }, + { finish: describeFinish('library:preset-cream'), rooms: ['Room 1'] }, + ]) + }) + + test('an older plate reads by its preset, and its inline material as one', () => { + const preset = withPlateSurface({ materialPreset: 'library:preset-sage' }) + expect(levelFinishes(preset, 'level_rooms')?.floors?.[0]?.finish.name).toBe('Sage') + const inline = withPlateSurface({ material: { properties: { color: '#abcdef' } } }) + expect(levelFinishes(inline, 'level_rooms')?.floors?.[0]?.finish).toEqual({ + ref: null, + name: 'an inline material', + color: '#abcdef', + }) + }) +}) + +describe('levelFinishes', () => { + test('a level with no room, and a node that is no level, read nothing', () => { + const nodes = scene() + for (const id of Object.keys(nodes)) if (nodes[id]?.type === 'zone') delete nodes[id] + expect(levelFinishes(nodes, 'level_rooms')).toBeNull() + expect(levelFinishes(nodes, 'wall_north')).toBeNull() + }) + + test("rooms are listed in the level's order under each finish, and a zone that is no room is left out", () => { + const nodes = scene() + nodes.zone_site = { + ...(nodes.zone_pantry as ZoneNode), + id: 'zone_site', + name: 'Lot', + spaceRole: 'generic', + } as ZoneNode + const level = nodes.level_rooms as AnyNode & { children: string[] } + nodes.level_rooms = { ...level, children: [...level.children, 'zone_site'] } as AnyNode + const palette = levelFinishes(nodes, 'level_rooms') + expect(palette?.floors).toEqual([ + { finish: { ref: null, name: 'default' }, rooms: ['Kitchen', 'Room 1'] }, + ]) + expect(JSON.stringify(palette)).not.toContain('Lot') + }) +}) + +describe('levelFinishes by surface', () => { + test('only the surfaces asked for are read, and none read where no room shows them', () => { + const nodes = scene() + expect(Object.keys(levelFinishes(nodes, 'level_rooms', undefined, ['walls']) ?? {})).toEqual([ + 'levelId', + 'walls', + ]) + expect(Object.keys(levelFinishes(nodes, 'level_rooms') ?? {})).toEqual([ + 'levelId', + 'floors', + 'walls', + 'ceilings', + ]) + nodes.zone_kitchen = { ...(nodes.zone_kitchen as ZoneNode), hasCeiling: false } + nodes.zone_pantry = { ...(nodes.zone_pantry as ZoneNode), hasCeiling: false } + expect(levelFinishes(nodes, 'level_rooms', undefined, ['ceilings'])).toBeNull() + }) +}) + +describe('changedFinishes', () => { + const namedRooms = (shown: ReturnType) => + shown.flatMap((level) => + [level.floors, level.walls, level.ceilings].flatMap((groups) => + (groups ?? []).flatMap((group) => group.rooms.map((room) => room.replace(/ \(.*\)$/, ''))), + ), + ) + + test('reads the rooms asked for and no other, the surface asked for and no other', () => { + const shown = changedFinishes(scene(), { walls: ['zone_pantry'] }) + expect(shown).toHaveLength(1) + expect(shown[0]).toMatchObject({ levelId: 'level_rooms' }) + expect(Object.keys(shown[0]!)).toEqual(['levelId', 'walls']) + expect(new Set(namedRooms(shown))).toEqual(new Set(['Room 1'])) + expect(JSON.stringify(shown)).not.toContain('Kitchen') + }) + + test('a room that shows nothing written is no row: the default is not answered', () => { + expect( + changedFinishes(scene(), { floors: ['zone_kitchen'], ceilings: ['zone_kitchen'] }), + ).toEqual([]) + expect(JSON.stringify(changedFinishes(scene(), { walls: ['zone_kitchen'] }))).not.toContain( + '"default"', + ) + }) + + test('each surface reads its own rooms, answered together on the level', () => { + const nodes = scene() + nodes.zone_kitchen = { + ...(nodes.zone_kitchen as ZoneNode), + floor: { finish: 'library:wood-floorplank1' }, + } as ZoneNode + const shown = changedFinishes(nodes, { floors: ['zone_kitchen'], walls: ['zone_pantry'] }) + expect(shown).toHaveLength(1) + expect(shown[0]?.floors?.map((group) => group.rooms)).toEqual([['Kitchen']]) + expect( + new Set(shown[0]?.walls?.flatMap((group) => group.rooms.map((room) => room.slice(0, 6)))), + ).toEqual(new Set(['Room 1'])) + }) + + test('an id that is no room reads nothing', () => { + expect(changedFinishes(scene(), { walls: ['wall_north', 'zone_missing'] })).toEqual([]) + }) +}) diff --git a/packages/core/src/agent-operations/room-finishes.ts b/packages/core/src/agent-operations/room-finishes.ts new file mode 100644 index 0000000000..c682b9fcd0 --- /dev/null +++ b/packages/core/src/agent-operations/room-finishes.ts @@ -0,0 +1,309 @@ +import { roomFloorPlate } from '../lib/room-floor-plate' +import { + getCatalogMaterialById, + getLibraryMaterialIdFromRef, + getSceneMaterialIdFromRef, +} from '../material-library' +import type { + AnyNode, + CeilingNode, + SceneMaterial, + SlabNode, + WallFace, + WallNode, + ZoneNode, +} from '../schema' +import { getWallZoneSpans, resolveWallFaceChain } from '../systems/wall/wall-finish' +import { levelIdOf, nodesOnLevel } from './scene-queries' +import type { SceneNodes } from './types' + +/** + * What the rooms of a level show, read from the scene: the finish of each room's floor, of the + * wall faces that look into it and of its ceiling, and which rooms carry each finish. Pure facts + * for the write tools' results and the reads, as the renderer resolves them: + * + * - a floor shows the room's painted parts over the room's own `floor.finish` over its floor + * plate's own surface (a slot older scenes carry: `paint` does not write a plate rooms derive); + * - a wall face shows its painted parts over the room's override for that face over the room's + * `wallMaterial` over the wall's own finish (what `paint` writes on the wall); + * - a ceiling shows the room's painted parts over the ceiling's own surface. + * + * The painted parts of a floor and a ceiling are named apart, never folded into the finish a room + * shows as a whole; the painted parts of a wall face (`faceRegions`) are not read here. Nothing + * written reads `default`, as `paint` says it. + */ + +export type FinishFact = { + /** The ref the finish is written as; null for the default and for an inline material. */ + ref: string | null + name: string + /** The library's kind (wood, tile, colors…), for a library material. */ + kind?: string + /** The colour the library or the scene gives it, where it gives one. */ + color?: string +} + +type Materials = Readonly> | undefined +type Finish = string | Record | null | undefined + +const DEFAULT_FINISH: FinishFact = { ref: null, name: 'default' } + +/** Nobody chose a finish here: the surface shows what the kind declares. */ +export const isDefaultFinish = (fact: FinishFact) => + fact.ref === null && fact.name === DEFAULT_FINISH.name + +/** The colour an inline material (a stored finish record) or a scene material carries. */ +function colourOf(spec: unknown): string | undefined { + if (!spec || typeof spec !== 'object') return undefined + const record = spec as Record + const own = (record.properties as Record | undefined)?.color ?? record.color + if (typeof own === 'string') return own + return record.material ? colourOf(record.material) : undefined +} + +/** A finish as its words: the library's name and kind, the scene material's name, or the ref. */ +export function describeFinish(finish: Finish, materials?: Materials): FinishFact { + if (finish === undefined || finish === null || finish === '') return DEFAULT_FINISH + if (typeof finish !== 'string') { + const color = colourOf(finish) + return { ref: null, name: 'an inline material', ...(color ? { color } : {}) } + } + const libraryId = getLibraryMaterialIdFromRef(finish) + if (libraryId) { + const item = getCatalogMaterialById(libraryId) + if (!item) return { ref: finish, name: finish } + return { + ref: finish, + name: item.label, + kind: item.category, + ...(item.previewColor ? { color: item.previewColor } : {}), + } + } + const sceneId = getSceneMaterialIdFromRef(finish) + const scene = sceneId ? materials?.[sceneId] : undefined + if (scene) { + const color = colourOf(scene.material) + return { ref: finish, name: scene.name, ...(color ? { color } : {}) } + } + return { ref: finish, name: finish } +} + +/** A finish in a phrase: its name, then its ref and colour where it has them. */ +export function finishWords(fact: FinishFact): string { + const facts = [fact.ref && fact.ref !== fact.name ? fact.ref : undefined, fact.color] + const rest = facts.filter(Boolean).join(', ') + return rest ? `${fact.name} (${rest})` : fact.name +} + +/** One finish's identity, so rooms painted alike group together. */ +const keyOf = (fact: FinishFact) => + fact.ref ?? (fact.name === DEFAULT_FINISH.name ? 'default' : `inline:${fact.color ?? ''}`) + +/** What a plate or a ceiling shows of its own: its surface slot, else its older finish fields. */ +const ownSurface = (node: SlabNode | CeilingNode | undefined): Finish => + node ? (node.slots?.surface ?? node.material ?? node.materialPreset) : undefined + +export type RoomFinishes = { + floor?: FinishFact & { regions?: { id: string; finish: FinishFact }[] } + /** The wall faces that look into the room, by the finish each shows. */ + walls?: { faces: number; finishes: { finish: FinishFact; faces: number }[] } + ceiling?: FinishFact & { regions?: { id: string; finish: FinishFact }[] } +} + +const regionsOf = ( + regions: { id: string; finish: Finish }[] | undefined, + materials: Materials, +): { regions?: { id: string; finish: FinishFact }[] } => + regions?.length + ? { regions: regions.map((r) => ({ id: r.id, finish: describeFinish(r.finish, materials) })) } + : {} + +/** What one face of a wall shows to a room: the room's override for it, the room's finish, else the wall's own. */ +export function wallFaceFinish( + zone: ZoneNode, + wall: WallNode, + face: WallFace, + materials: Materials, +): FinishFact { + const override = zone.wallOverrides?.find( + (entry) => entry.wallId === wall.id && entry.face === face, + ) + let finish: Finish = override?.finish ?? zone.wallMaterial + if (finish === undefined) { + // The wall's own face: a chosen slot, an older finish, or nothing chosen. + const own = resolveWallFaceChain(wall, face) + finish = + own.kind === 'ref' + ? own.ref + : own.kind === 'legacy' + ? (own.spec.materialPreset ?? own.spec.material) + : undefined + } + return describeFinish(finish as Finish, materials) +} + +/** The wall faces that look into a room, and what each shows (the room's finish, else the wall's own). */ +function wallFaceFinishes(nodes: SceneNodes, zone: ZoneNode, materials: Materials) { + const shown = new Map() + let faces = 0 + for (const wallId of zone.boundaryWallIds ?? []) { + const wall = nodes[wallId] + if (wall?.type !== 'wall') continue + const looking = new Set(getWallZoneSpans(wall as WallNode, [zone]).map((span) => span.face)) + for (const face of looking) { + const fact = wallFaceFinish(zone, wall as WallNode, face, materials) + const entry = shown.get(keyOf(fact)) ?? { finish: fact, faces: 0 } + entry.faces += 1 + shown.set(keyOf(fact), entry) + faces += 1 + } + } + return faces ? { faces, finishes: [...shown.values()] } : undefined +} + +/** What one room shows, from the nodes of its level. */ +export function roomFinishes( + nodes: SceneNodes, + zone: ZoneNode, + content: readonly AnyNode[], + materials?: Materials, +): RoomFinishes { + const shown: RoomFinishes = {} + if (zone.hasFloor !== false) { + const slabs = content.filter((node): node is SlabNode => node.type === 'slab') + shown.floor = { + ...describeFinish( + zone.floor?.finish ?? ownSurface(roomFloorPlate(slabs, zone.id)), + materials, + ), + ...regionsOf(zone.floor?.regions, materials), + } + } + const walls = wallFaceFinishes(nodes, zone, materials) + if (walls) shown.walls = walls + if (zone.hasCeiling !== false) { + const ceiling = content.find( + (node): node is CeilingNode => node.type === 'ceiling' && node.zoneId === zone.id, + ) + if (ceiling) + shown.ceiling = { + ...describeFinish(ownSurface(ceiling), materials), + ...regionsOf(zone.ceiling?.regions, materials), + } + } + return shown +} + +/** The finish a surface shows as a whole, its painted parts left aside. */ +const wholeFinish = ({ ref, name, kind, color }: FinishFact): FinishFact => ({ + ref, + name, + ...(kind ? { kind } : {}), + ...(color ? { color } : {}), +}) + +export type FinishGroup = { finish: FinishFact; rooms: string[] } + +export type LevelFinishes = { + levelId: string + levelName?: string + floors?: FinishGroup[] + walls?: FinishGroup[] + ceilings?: FinishGroup[] +} + +const rooms = (content: readonly AnyNode[]) => + content.filter((node): node is ZoneNode => node.type === 'zone' && node.spaceRole === 'room') + +export type FinishSurface = 'floors' | 'walls' | 'ceilings' + +/** + * The rooms of a level by the finish each surface shows: which finish, and the rooms it is in. + * `surfaces` names the ones read and `roomIds` the rooms (all of them by default); null where no + * room read shows any of them. + */ +export function levelFinishes( + nodes: SceneNodes, + levelId: string, + materials?: Materials, + surfaces: readonly FinishSurface[] = ['floors', 'walls', 'ceilings'], + roomIds?: ReadonlySet, +): LevelFinishes | null { + const level = nodes[levelId] + if (level?.type !== 'level') return null + const content = nodesOnLevel(nodes, levelId) + const floors = new Map() + const walls = new Map() + const ceilings = new Map() + const add = (groups: Map, finish: FinishFact, room: string) => { + const group = groups.get(keyOf(finish)) ?? { finish, rooms: [] } + group.rooms.push(room) + groups.set(keyOf(finish), group) + } + const named = rooms(content).filter((zone) => !roomIds || roomIds.has(zone.id)) + if (!named.length) return null + for (const zone of named) { + const shown = roomFinishes(nodes, zone, content, materials) + if (shown.floor) add(floors, wholeFinish(shown.floor), zone.name) + for (const entry of shown.walls?.finishes ?? []) + add( + walls, + entry.finish, + entry.faces < shown.walls!.faces + ? `${zone.name} (${entry.faces} of ${shown.walls!.faces} wall faces)` + : zone.name, + ) + if (shown.ceiling) add(ceilings, wholeFinish(shown.ceiling), zone.name) + } + const read = (surface: FinishSurface, groups: Map) => + surfaces.includes(surface) && groups.size ? { [surface]: [...groups.values()] } : {} + const shown = { + ...read('floors', floors), + ...read('walls', walls), + ...read('ceilings', ceilings), + } + if (!Object.keys(shown).length) return null + return { levelId, ...(level.name ? { levelName: level.name } : {}), ...shown } +} + +/** + * What the rooms a write changed now show, each surface for the rooms it was written on, read from + * the scene as it stands: the rooms the call touched and no others, and no row for a finish none of + * them shows (`default`: the rest of the level is `get_zones`'s). Per level; none where nothing is + * left to say. + */ +export function changedFinishes( + nodes: SceneNodes, + written: Partial>, + materials?: Materials, +): LevelFinishes[] { + const byLevel = new Map() + for (const [surface, roomIds] of Object.entries(written) as [ + FinishSurface, + readonly string[], + ][]) { + const levelIds = [...new Set(roomIds.flatMap((id) => levelIdOf(nodes, id) ?? []))] + for (const levelId of levelIds) { + const shown = levelFinishes(nodes, levelId, materials, [surface], new Set(roomIds)) + const groups = shown?.[surface]?.filter((group) => keyOf(group.finish) !== 'default') + if (shown && groups?.length) + byLevel.set(levelId, { ...byLevel.get(levelId), ...shown, [surface]: groups }) + } + } + return [...byLevel.values()] +} + +/** The rooms that show a painted surface: those a wall's painted faces look into, a ceiling's room. */ +export function roomsShowing(nodes: SceneNodes, node: AnyNode, roles: readonly string[]): string[] { + if (node.type === 'ceiling') return node.zoneId ? [node.zoneId] : [] + if (node.type !== 'wall') return [] + const levelId = levelIdOf(nodes, node.id) + if (!levelId) return [] + return rooms(nodesOnLevel(nodes, levelId)) + .filter( + (zone) => + zone.boundaryWallIds?.includes(node.id) && + getWallZoneSpans(node, [zone]).some((span) => roles.includes(span.face)), + ) + .map((zone) => zone.id) +} diff --git a/packages/core/src/agent-operations/room-readings.ts b/packages/core/src/agent-operations/room-readings.ts new file mode 100644 index 0000000000..d0607616d2 --- /dev/null +++ b/packages/core/src/agent-operations/room-readings.ts @@ -0,0 +1,518 @@ +import { + foldRoomName, + isOutdoorRoom, + isWetRoomUse, + type RoomUse, + roomUseOfName, +} from '../building/room-use' +import { getLevelDisplayName } from '../lib/level-name' +import { area, intersection, type Polygon, union } from '../lib/polygon-boolean' +import { roomDrawnFloor } from '../lib/room-drawn-floor' +import { roomFloorPlate } from '../lib/room-floor-plate' +import { + type AnyNode, + getScaledDimensions, + getWallTrimFaces, + type ItemNode, + type SceneMaterial, + type SlabNode, + type WallFace, + type WallNode, + type ZoneNode, +} from '../schema' +import { getWallZoneSpans } from '../systems/wall/wall-finish' +import { itemLevelPose } from './item-space' +import { pointInPolygon } from './plan-geometry' +import { roomWallFaces } from './room-faces' +import { describeFinish, type FinishFact, isDefaultFinish, roomFinishes } from './room-finishes' +import { finishTiled, type Tiled } from './room-tile' +import { readWet, type WetReading } from './room-wet' +import { levelsOf, nodesOnLevel, queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +/** + * What each room of a scene shows and holds, read from the stored nodes alone (no brief, no model): + * the use its name gives it, whether its floor or its wall faces are tiled, whether those faces + * carry skirting, and the pieces standing in it. The room checks (`room-checks.ts`) judge these. + */ + +export type RoomPiece = { + id: string + /** + * What it is: a catalog or authored item's category, or, where the author gave only a generic one + * ("furniture"), its name without the words of its room and its number; `cabinet-run`, `shelf`, a + * placed design's recipe name. + */ + kind: string + /** + * Which recipe: a catalog item's id; an authored item's script, whatever parameters, size and + * colours it was run with (`script:`); a placed design's recipe; a run's make-up. Two pieces + * made by one function for two rooms have two artifacts and one script. + */ + design: string + /** + * An authored piece's size to 5 cm and its finishes: two pieces of one kind and one look are + * alike though two scripts made them. Absent for a piece with a recipe of its own. + */ + look?: string + name: string + /** A piece hung on a wall: the wall, the face it is on and the metres along the wall. */ + hung?: { wallId: string; face: WallFace; u: number } +} + +export type RoomReading = { + id: string + name: string + levelId: string + levelName: string + use: RoomUse + /** False for a porch, alfresco, balcony or any room open on a side: no finish is owed there as indoors. */ + indoor: boolean + /** + * `fact` is what the floor shows as a whole, its painted parts (rugs) left aside; `atDefault` where nobody chose a finish and no + * script lays it; `held` where a floor plate of its own, a drawn slab it was taken from, or slabs over half its footprint are under it. + */ + floor: { finish: string; tiled: Tiled; fact: FinishFact; atDefault: boolean; held: boolean } + /** + * `facts` are the finishes the wall faces that look in show, each once. + */ + walls: { + finishes: string[] + tiled: Tiled + faces: number + facts: FinishFact[] + } + /** How its walls are dressed, kind by kind, in the brief's words. */ + /** A wet room's walls read against what a wet room is tiled to; absent for the other rooms. */ + wet?: WetReading + skirting: { faces: number; withSkirting: number } + pieces: RoomPiece[] +} + +type Materials = Readonly> | undefined + +const strongest = (readings: readonly Tiled[]): Tiled => + readings.includes('yes') ? 'yes' : readings.includes('unknown') ? 'unknown' : 'no' + +/** Tiled on the floor or on the walls; `unknown` while either surface cannot be read and none is tile. */ +export const roomTiled = (room: Pick): Tiled => + strongest([room.floor.tiled, room.walls.tiled]) + +const finishWord = (fact: FinishFact) => fact.name + +function readFloor(zone: ZoneNode, shown: ReturnType, materials: Materials) { + const facts = [ + shown.floor ?? { ref: null, name: 'default' }, + ...(shown.floor?.regions?.map((region) => region.finish) ?? []), + ] + const readings = facts.map((fact) => finishTiled(fact, materials)) + // A floor built by a script lays its own boards or tiles, and its words are not read here. + if (zone.floor?.script) readings.push('unknown') + const base = facts[0]! + return { + finish: finishWord(base), + tiled: strongest(readings), + fact: base, + atDefault: isDefaultFinish(base) && !zone.floor?.script, + } +} + +const footprintOf = (node: { + polygon: [number, number][] + holes?: [number, number][][] +}): Polygon => ({ + outer: node.polygon, + holes: node.holes ?? [], +}) + +/** Whether anything is under a room: its own plate, the drawn slab its floor was taken from, or slabs under most of its footprint. */ +function floorHeld(nodes: SceneNodes, zone: ZoneNode): boolean { + if (zone.floor?.support === 'open') return true + const slabs = queryNodes(nodes, { type: 'slab', parentId: zone.parentId }).filter( + (node) => node.visible !== false && node.support !== 'open', + ) + if (roomFloorPlate(slabs, zone.id) || roomDrawnFloor(nodes, zone.id)) return true + const room = footprintOf(zone) + const roomArea = area([room]) + return ( + roomArea > 1e-4 && + area(intersection(room, union(slabs.map((slab) => footprintOf(slab))))) >= roomArea / 2 + ) +} + +/** The floor a room shows, and, for a room whose floor is a drawn slab, that slab's surface when the room itself chose none. */ +function floorOf( + nodes: SceneNodes, + zone: ZoneNode, + shown: ReturnType, + materials: Materials, +): RoomReading['floor'] { + const floor = readFloor(zone, shown, materials) + const drawn = floor.atDefault ? roomDrawnFloor(nodes, zone.id) : null + const slab = drawn ? nodes[drawn.slabId] : undefined + const underSlab = + slab?.type === 'slab' + ? describeFinish(slab.slots?.surface ?? slab.material ?? slab.materialPreset, materials) + : undefined + return { + ...floor, + atDefault: floor.atDefault && (!underSlab || isDefaultFinish(underSlab)), + held: floorHeld(nodes, zone), + } +} + +type WallPass = { walls: RoomReading['walls']; skirting: RoomReading['skirting'] } + +/** The wall faces that look into a room: their finishes, and whether they carry skirting. */ +function readWalls( + nodes: SceneNodes, + zone: ZoneNode, + shown: ReturnType, + materials: Materials, +): WallPass { + const shownFacts = (shown.walls?.finishes ?? []).map((entry) => entry.finish) + const facts = new Map(shownFacts.map((fact) => [finishWord(fact), fact])) + const finishes = new Set(facts.keys()) + const tiled: Tiled[] = (shown.walls?.finishes ?? []).map((entry) => + finishTiled(entry.finish, materials), + ) + let faces = 0 + let withSkirting = 0 + const seen = new Set() + for (const { wallId, face } of roomWallFaces(nodes, zone)) { + if (seen.has(`${wallId}/${face}`)) continue + seen.add(`${wallId}/${face}`) + const wall = nodes[wallId] as WallNode + faces += 1 + if (wall.skirting?.enabled && getWallTrimFaces(wall.skirting.sides).includes(face)) + withSkirting += 1 + for (const region of wall.faceRegions ?? []) { + if (region.face !== face) continue + const fact = describeFinish(region.finish, materials) + finishes.add(finishWord(fact)) + facts.set(finishWord(fact), fact) + tiled.push(finishTiled(fact, materials)) + } + if (wall.finishScripts?.[face]) tiled.push('unknown') + } + return { + walls: { + finishes: [...finishes], + // No wall faces known (a zone with no boundary walls) is not a wall read as bare. + tiled: faces ? strongest(tiled) : 'unknown', + faces, + facts: [...facts.values()], + }, + skirting: { faces, withSkirting }, + } +} + +const fnv = (text: string) => { + let hash = 0x811c9dc5 + for (let index = 0; index < text.length; index++) { + hash ^= text.charCodeAt(index) + hash = Math.imul(hash, 0x01000193) >>> 0 + } + return hash.toString(16).padStart(8, '0') +} + +const round = (value: unknown) => + typeof value === 'number' ? Math.round(value * 100) / 100 : value + +/** A cabinet run's make-up, without where it stands: the same run laid elsewhere is the same design. */ +function runDesign(nodes: SceneNodes, run: AnyNode & { type: 'cabinet' }): string { + const modules = run.children.flatMap((id) => { + const module = nodes[id] + if (module?.type !== 'cabinet-module') return [] + return [ + [ + module.moduleKind, + module.cabinetType, + round(module.width), + (module.stack ?? []).map((compartment) => compartment.type), + ], + ] + }) + return fnv(JSON.stringify([run.frontStyle, run.handleStyle, run.runTier, modules])) +} + +type RawPiece = Omit & { category: string } +type Placed = { piece: RawPiece; point: [number, number] | null; zoneId?: string } + +/** Where a catalog or scripted item stands in its level's plan, or the room it is already in. */ +function placeItem( + nodes: SceneNodes, + byId: Map, + item: ItemNode, + roomsOnLevel: readonly ZoneNode[], +): { point?: [number, number]; zoneId?: string; hung?: RoomPiece['hung'] } | null { + let attached = item + let root = item.parentId ? nodes[item.parentId] : undefined + while (root?.type === 'item') { + attached = root + root = root.parentId ? nodes[root.parentId] : undefined + } + if (!root) return null + if (root.type === 'ceiling' && root.zoneId && roomsOnLevel.some((z) => z.id === root.zoneId)) + return { zoneId: root.zoneId } + if (root.type === 'wall') return placeOnWall(attached, root as WallNode, roomsOnLevel) + if (root.type !== 'level' && root.type !== 'slab' && root.type !== 'ceiling') return null + const pose = itemLevelPose(item, byId) + return pose ? { point: [pose.position[0], pose.position[2]] } : null +} + +/** An item hosted on a wall belongs to the room whose face it is on, at its station along the wall. */ +function placeOnWall( + item: { position: readonly number[]; side?: 'front' | 'back' }, + wall: WallNode, + roomsOnLevel: readonly ZoneNode[], +): { zoneId: string; hung: NonNullable } | null { + const length = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + if (!(length > 0)) return null + const station = (item.position[0] ?? 0) / length + const faces: WallFace[] = + item.side === 'front' ? ['a'] : item.side === 'back' ? ['b'] : ['a', 'b'] + for (const face of faces) + for (const zone of roomsOnLevel) { + const span = getWallZoneSpans(wall, [zone]).find( + (s) => s.face === face && station >= s.t0 - 1e-6 && station <= s.t1 + 1e-6, + ) + if (span) + return { zoneId: zone.id, hung: { wallId: wall.id, face, u: item.position[0] ?? 0 } } + } + return null +} + +const planArea = (zone: ZoneNode) => + Math.abs( + zone.polygon.reduce((sum, [x, z], index) => { + const next = zone.polygon[(index + 1) % zone.polygon.length]! + return sum + x * next[1] - next[0] * z + }, 0), + ) / 2 + +/** The room whose plan holds a point; the smallest when rooms overlap (a landing inside a hall). */ +function roomAt(point: [number, number], rooms: readonly ZoneNode[]): ZoneNode | undefined { + return rooms + .filter( + (zone) => + pointInPolygon(point, zone.polygon as [number, number][]) && + !(zone.holes ?? []).some((hole) => + pointInPolygon(point, hole as [number, number][], false), + ), + ) + .sort((a, b) => planArea(a) - planArea(b))[0] +} + +/** An authored item's size to 5 cm and its finishes, which two scripts' pieces can share. */ +function itemLook(item: ItemNode): string { + const size = getScaledDimensions(item) + .map((metres) => (Math.round(metres / 0.05) * 0.05).toFixed(2)) + .join('x') + const finishes = Object.entries(item.slots ?? {}).sort(([a], [b]) => a.localeCompare(b)) + return `${size}|${JSON.stringify(finishes)}` +} + +const GENERIC_CATEGORIES = new Set([ + '', + 'furniture', + 'decor', + 'decoration', + 'object', + 'item', + 'other', + 'misc', + 'custom', + 'accessory', + 'accessories', +]) + +/** Words of a name, accents folded; the digits and the words of the room are what a piece is not. */ +const wordsOf = (text: string) => + foldRoomName(text) + .split(/[^a-z0-9]+/) + .filter(Boolean) + +/** Two words are one when equal or when long enough to share five letters ("parental", "parentale"). */ +const sameWord = (a: string, b: string) => + a === b || (a.length >= 5 && b.length >= 5 && a.slice(0, 5) === b.slice(0, 5)) + +/** + * What a piece is: its category, or, where the author gave only "furniture", its name without its + * room's words and numbers ("Lit Chambre 3" and "Lit Chambre 4" are both a "lit"). + */ +function pieceKind(category: string, name: string, roomName: string): string { + if (!GENERIC_CATEGORIES.has(foldRoomName(category))) return category + const room = wordsOf(roomName).filter((word) => word.length >= 3) + const kept = wordsOf(name).filter( + (word) => !/^\d+$/.test(word) && !room.some((other) => sameWord(word, other)), + ) + return kept.join(' ') || 'piece' +} + +/** The pieces standing in each room: catalog and scripted items, cabinet runs and shelves. */ +function readPieces(nodes: SceneNodes, rooms: readonly ZoneNode[]): Map { + const byLevel = new Map() + for (const zone of rooms) { + const list = byLevel.get(zone.parentId ?? '') ?? [] + list.push(zone) + byLevel.set(zone.parentId ?? '', list) + } + // biome-ignore lint/plugin: every piece, of any kind, is filed under the room it stands in + const byId = new Map(Object.entries(nodes)) + const found = new Map() + const put = (zoneId: string, piece: RawPiece) => + found.set(zoneId, [...(found.get(zoneId) ?? []), piece]) + // biome-ignore lint/plugin: every piece, of any kind, is filed under the room it stands in + for (const node of Object.values(nodes)) { + let placed: Placed | null = null + if (node.type === 'item') { + const levelId = levelOfNode(nodes, node) + const here = byLevel.get(levelId ?? '') ?? [] + const where = here.length ? placeItem(nodes, byId, node, here) : null + if (where) + placed = { + piece: { + id: node.id, + category: node.asset.category, + design: node.source?.script ? `script:${node.source.script}` : node.asset.id, + ...(node.source ? { look: itemLook(node) } : {}), + name: node.name ?? node.asset.name, + ...(where.hung ? { hung: where.hung } : {}), + }, + point: where.point ?? null, + zoneId: where.zoneId, + } + } else if (node.type === 'procedural-item') { + // A design placed with place_design: on the floor, a slab or a ceiling, or hung on a wall. + const parent = node.parentId ? nodes[node.parentId] : undefined + const here = byLevel.get(levelOfNode(nodes, node) ?? '') ?? [] + const where = + parent?.type === 'wall' + ? placeOnWall(node, parent as WallNode, here) + : parent?.type === 'level' || parent?.type === 'slab' || parent?.type === 'ceiling' + ? { point: [node.position[0], node.position[2]] as [number, number] } + : null + if (where) + placed = { + piece: { + id: node.id, + category: node.recipe.name, + design: `recipe:${fnv(JSON.stringify(node.recipe))}`, + name: node.name ?? node.recipe.name, + ...('hung' in where && where.hung ? { hung: where.hung } : {}), + }, + point: 'point' in where ? where.point : null, + zoneId: 'zoneId' in where ? where.zoneId : undefined, + } + } else if (node.type === 'cabinet' || node.type === 'shelf') { + if (node.parentId && nodes[node.parentId]?.type === 'level') + placed = { + piece: { + id: node.id, + category: node.type === 'cabinet' ? 'cabinet-run' : 'shelf', + design: + node.type === 'cabinet' + ? runDesign(nodes, node) + : fnv(JSON.stringify([node.style, node.rows, node.columns, round(node.width)])), + name: node.name ?? node.type, + }, + point: [node.position[0], node.position[2]], + } + } + if (!placed) continue + const here = byLevel.get(levelOfNode(nodes, node) ?? '') ?? [] + const zoneId = placed.zoneId ?? (placed.point ? roomAt(placed.point, here)?.id : undefined) + if (zoneId) put(zoneId, placed.piece) + } + return found +} + +function levelOfNode(nodes: SceneNodes, node: AnyNode): string | null { + const seen = new Set() + let at: AnyNode | undefined = node + while (at && !seen.has(at.id)) { + if (at.type === 'level') return at.id + seen.add(at.id) + at = at.parentId ? nodes[at.parentId] : undefined + } + return null +} + +/** Room contents and openings along its wall spans, including either side of a shared doorway. */ +export function roomIssueScope(nodes: SceneNodes, requested: string) { + const wanted = requested.trim().toLowerCase() + const zones = queryNodes(nodes, { type: 'zone' }) + const matched = zones.filter( + (zone) => zone.id.toLowerCase() === wanted || zone.name.trim().toLowerCase() === wanted, + ) + if (!matched.length) return [] + const pieces = readPieces(nodes, zones) + return matched.map((zone) => { + const nodeIds = new Set([zone.id, ...(pieces.get(zone.id) ?? []).map((piece) => piece.id)]) + for (const opening of queryNodes(nodes, { + type: ['door', 'window'], + })) { + const wall = nodes[opening.parentId ?? ''] + if (wall?.type !== 'wall' || levelOfNode(nodes, wall) !== zone.parentId) continue + const length = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + if (!(length > 0)) continue + const station = opening.position[0] / length + // Drawn rooms can lack derived boundary IDs; the wall-facing span still establishes ownership. + if ( + getWallZoneSpans(wall, [{ ...zone, boundaryWallIds: [wall.id] }]).some( + (span) => station >= span.t0 - 1e-6 && station <= span.t1 + 1e-6, + ) + ) + nodeIds.add(opening.id) + } + return { roomId: zone.id, room: zone.name, nodeIds: [...nodeIds] } + }) +} + +/** + * Every room of the scene (a zone that is a room and has a floor) as the checks read it, in level + * order then by name. `materials` are the scene's, when the host has them, to name `scene:` finishes. + */ +export function readRooms( + nodes: SceneNodes, + options: { materials?: Readonly> } = {}, +): RoomReading[] { + const { materials } = options + const rooms: { zone: ZoneNode; levelName: string }[] = [] + for (const level of levelsOf(nodes)) { + const levelName = getLevelDisplayName(level) + for (const node of nodesOnLevel(nodes, level.id)) + if (node.type === 'zone' && node.spaceRole === 'room' && node.hasFloor !== false) + rooms.push({ zone: node, levelName }) + } + // biome-ignore lint/plugin: every piece, of any kind, is filed under the room it stands in + const byId = new Map(Object.entries(nodes)) + const pieces = readPieces( + nodes, + rooms.map(({ zone }) => zone), + ) + return rooms.map(({ zone, levelName }) => { + const content = nodesOnLevel(nodes, zone.parentId ?? '') + const shown = roomFinishes(nodes, zone, content, materials) + const { walls, skirting } = readWalls(nodes, zone, shown, materials) + const use = roomUseOfName(zone.name) + const roomPieces = (pieces.get(zone.id) ?? []).map(({ category, ...piece }) => ({ + ...piece, + kind: pieceKind(category, piece.name, zone.name), + })) + return { + id: zone.id, + name: zone.name, + levelId: zone.parentId ?? '', + levelName, + use, + indoor: !isOutdoorRoom(zone), + floor: floorOf(nodes, zone, shown, materials), + walls, + ...(isWetRoomUse(use) ? { wet: readWet(nodes, byId, zone, roomPieces, materials) } : {}), + skirting, + pieces: roomPieces, + } + }) +} diff --git a/packages/core/src/agent-operations/room-tile.ts b/packages/core/src/agent-operations/room-tile.ts new file mode 100644 index 0000000000..23811ac89e --- /dev/null +++ b/packages/core/src/agent-operations/room-tile.ts @@ -0,0 +1,35 @@ +import { foldRoomName } from '../building/room-use' +import { getSceneMaterialIdFromRef } from '../material-library' +import type { SceneMaterial } from '../schema' +import type { FinishFact } from './room-finishes' + +/** `unknown` is a finish the nodes cannot name (an inline material, a scene ref with no scene + * materials at hand, a script-built face): a check never fires on what it cannot read. */ +export type Tiled = 'yes' | 'no' | 'unknown' + +type Materials = Readonly> | undefined + +const TILE_WORDS = + /tile|ceramic|cerame|mosaic|mosaique|terracotta|terre cuite|tomette|zellige|azulejo|porcelain|\bgres\b|marble|statuar|carrel|carreau|faience|marbre/ + +/** + * Whether one finish is tile: the library's own kind, else its words. "Stone Tile" is filed under + * stone and "Statuaretto White" (white marble flooring) under stone too, so the kind alone misses + * both. A material the maker generated is read from what it is made of, as its name may say + * anything: a tile or marble preset is tile, a flat colour is paint, and a texture could be either. + */ +export function finishTiled(fact: FinishFact, materials?: Materials): Tiled { + if (fact.ref === null) return fact.name === 'default' ? 'no' : 'unknown' + if (fact.kind === 'tile') return 'yes' + // A written colour (#rrggbb, what a dressing layer paints with) is flat paint. + if (/^#[0-9a-f]{6}$/i.test(fact.ref)) return 'no' + if (TILE_WORDS.test(foldRoomName(`${fact.name} ${fact.ref}`))) return 'yes' + const sceneId = getSceneMaterialIdFromRef(fact.ref) + if (sceneId) { + const made = materials?.[sceneId]?.material + if (!made) return 'unknown' + if (made.preset === 'tile' || made.preset === 'marble') return 'yes' + return made.texture ? 'unknown' : 'no' + } + return fact.name === fact.ref ? 'unknown' : 'no' +} diff --git a/packages/core/src/agent-operations/room-wet.ts b/packages/core/src/agent-operations/room-wet.ts new file mode 100644 index 0000000000..bb9ef3493b --- /dev/null +++ b/packages/core/src/agent-operations/room-wet.ts @@ -0,0 +1,269 @@ +import { foldRoomName } from '../building/room-use' +import type { AnyNode, SceneMaterial, WallNode, ZoneNode } from '../schema' +import { standsAgainst } from './dress-targets' +import { itemPlanAabbInLevel } from './item-space' +import { wallResolvedHeight } from './level-reads' +import { type RoomWallFace, roomWallFaces } from './room-faces' +import { describeFinish, wallFaceFinish } from './room-finishes' +import type { RoomPiece } from './room-readings' +import { finishTiled, type Tiled } from './room-tile' +import type { SceneNodes } from './types' + +/** + * What a wet room is tiled to: a bathroom, shower room, WC or laundry counts tiled when the walls its + * fixtures stand against are tiled to `WET_TILED_TO_M`, and to the ceiling around its shower. The + * wall faces read are the stretches a shower, bath, basin or toilet stands against (within + * `STANDS_AGAINST_M` of the face), else, when none can be placed, every face of the room. A face is + * tiled to a height when tile covers at least `COVERED` of its stretch up to there; what covers it is + * read as the renderer layers it (the base finish, then the face's regions, a later one over an + * earlier). A face a script builds, or a finish the nodes cannot name, is `unknown`, and unknown + * never fails a room. + */ + +/** A wet room's walls are tiled up to this, metres. */ +export const WET_TILED_TO_M = 1.2 +/** The share of a face's stretch tile must cover to count as tiled there. */ +export const COVERED = 0.8 +/** Tile may stop this short of a height and still count as reaching it, metres. */ +const SLACK_M = 0.02 +/** Where "to the ceiling" begins, metres under the top of the wall. */ +const CEILING_SLACK_M = 0.05 +/** How far a shower's stretch reaches past it each side, metres. */ +const SHOWER_MARGIN_M = 0.1 +/** A shower hung on a wall has no footprint: this much of the wall each side of it is its stretch. */ +const HUNG_REACH_M = 0.45 +const STEP_M = 0.05 + +const FIXTURE_WORDS = new Set([ + 'shower', + 'showers', + 'douche', + 'douches', + 'bath', + 'baths', + 'bathtub', + 'bathtubs', + 'tub', + 'tubs', + 'baignoire', + 'baignoires', + 'sink', + 'sinks', + 'basin', + 'basins', + 'washbasin', + 'washbasins', + 'lavabo', + 'lavabos', + 'vasque', + 'vasques', + 'vanity', + 'vanities', + 'toilet', + 'toilets', + 'wc', + 'cuvette', + 'bidet', + 'bidets', + 'washer', + 'washing', + 'lave', + 'laundry', +]) +const SHOWER_WORDS = new Set(['shower', 'showers', 'douche', 'douches']) + +/** What a piece is, in words: its kind (a category, else its name without its room's words), never its name, so a "shower mirror" is a mirror. */ +const wordsOf = (piece: Pick) => + foldRoomName(piece.kind) + .split(/[^a-z0-9]+/) + .filter(Boolean) + +const isFixture = (piece: RoomPiece) => wordsOf(piece).some((word) => FIXTURE_WORDS.has(word)) +const isShower = (piece: RoomPiece) => wordsOf(piece).some((word) => SHOWER_WORDS.has(word)) + +export type WetReading = { + /** True when the faces read are those fixtures stand against; false when every face was read. */ + byFixtures: boolean + /** The least height tile reaches over the faces read, covering 80% of each stretch, metres; null when unreadable. */ + tiledTo: number | null + /** Whether tile shows anywhere on those faces. */ + anyTile: boolean + /** Whether those faces are tiled to `WET_TILED_TO_M`. */ + tiled: Tiled + /** The showers standing against a wall, and whether tile reaches the ceiling around each. */ + showers: { id: string; name: string; full: Tiled }[] + /** `no` when the walls are short of the height or a shower's surround is: what the finding reads. */ + verdict: Tiled +} + +type Cover = { u0: number; u1: number; v0: number; v1: number; state: Tiled } + +/** The layers a face shows, bottom to top. */ +function layersOf( + zone: ZoneNode, + wall: WallNode, + stretch: RoomWallFace, + height: number, + materials: Readonly> | undefined, +): Cover[] { + const { face, length } = stretch + const layers: Cover[] = [ + { + u0: 0, + u1: length, + v0: 0, + v1: height, + state: finishTiled(wallFaceFinish(zone, wall, face, materials), materials), + }, + ] + const script = wall.finishScripts?.[face] + if (script) + layers.push({ + u0: 0, + u1: length, + v0: 0, + v1: Math.min(height, script.toHeight ?? height), + state: 'unknown', + }) + for (const region of wall.faceRegions ?? []) { + if (region.face !== face) continue + layers.push({ + u0: region.u0 ?? 0, + u1: region.u1 ?? length, + v0: region.v0 ?? 0, + v1: Math.min(height, region.v1 ?? height), + state: finishTiled(describeFinish(region.finish, materials), materials), + }) + } + return layers +} + +/** How high tile runs unbroken from the floor at one point along a face, and whether what stops it is unreadable. */ +function tileRun(layers: readonly Cover[], u: number, height: number) { + const here = layers.filter((layer) => u >= layer.u0 && u <= layer.u1) + const stops = [...new Set([0, height, ...here.flatMap((layer) => [layer.v0, layer.v1])])] + .filter((v) => v >= 0 && v <= height) + .sort((a, b) => a - b) + for (let index = 0; index + 1 < stops.length; index++) { + const [low, high] = [stops[index]!, stops[index + 1]!] + if (high - low < 1e-6) continue + const mid = (low + high) / 2 + const state = here.filter((layer) => mid >= layer.v0 && mid <= layer.v1).at(-1)?.state ?? 'no' + if (state !== 'yes') return { top: low, open: state === 'unknown' } + } + return { top: height, open: false } +} + +/** Tile heights sampled along a stretch of a face: where the unbroken run from the floor ends at each point, and whether an unreadable finish stops it. */ +export type Read = { tops: number[]; open: boolean[] } + +export function readStretch( + nodes: SceneNodes, + zone: ZoneNode, + stretch: RoomWallFace, + range: { u0: number; u1: number }, + materials: Readonly> | undefined, +): Read & { height: number } { + const wall = nodes[stretch.wallId] as WallNode + const height = wallResolvedHeight(nodes, wall) + const layers = layersOf(zone, wall, stretch, height, materials) + const count = Math.max(1, Math.ceil((range.u1 - range.u0) / STEP_M)) + const runs = Array.from({ length: count }, (_, index) => + tileRun(layers, range.u0 + ((index + 0.5) * (range.u1 - range.u0)) / count, height), + ) + return { height, tops: runs.map((run) => run.top), open: runs.map((run) => run.open) } +} + +/** Whether tile covers 80% of the samples up to `target`: yes, no, or unknown where unreadable parts could. */ +export function reaches(read: Read, target: number): Tiled { + const n = read.tops.length + const yes = read.tops.filter((top) => top >= target - SLACK_M).length + const maybe = read.tops.filter((top, i) => top < target - SLACK_M && read.open[i]).length + if (yes >= COVERED * n - 1e-9) return 'yes' + return yes + maybe >= COVERED * n - 1e-9 ? 'unknown' : 'no' +} + +/** The height 80% of the samples reach at least. */ +export const coveredTo = (read: Read) => + [...read.tops].sort((a, b) => a - b)[Math.floor((1 - COVERED) * read.tops.length - 1e-9)] ?? + read.tops[0]! + +const combine = (states: readonly Tiled[]): Tiled => + states.includes('no') ? 'no' : states.includes('unknown') ? 'unknown' : 'yes' + +/** The stretch of a face a piece stands against, margin added, or undefined when it does not. */ +function against( + nodes: SceneNodes, + byId: Map, + stretch: RoomWallFace, + piece: RoomPiece, + margin: number, +): { u0: number; u1: number } | undefined { + if (stretch.curved) return undefined + if (piece.hung) { + if (piece.hung.wallId !== stretch.wallId || piece.hung.face !== stretch.face) return undefined + const u0 = Math.max(stretch.u0, piece.hung.u - HUNG_REACH_M) + const u1 = Math.min(stretch.u1, piece.hung.u + HUNG_REACH_M) + return u1 > u0 ? { u0, u1 } : undefined + } + const item = nodes[piece.id] + const box = item?.type === 'item' ? itemPlanAabbInLevel(item, byId) : null + if (!box) return undefined + const { minX, maxX, minZ, maxZ } = box + return standsAgainst( + nodes[stretch.wallId] as WallNode, + stretch, + [ + [minX, minZ], + [maxX, minZ], + [maxX, maxZ], + [minX, maxZ], + ], + margin, + ) +} + +/** A wet room's walls against what it is tiled to; undefined for a room with no wall face. */ +export function readWet( + nodes: SceneNodes, + byId: Map, + zone: ZoneNode, + pieces: readonly RoomPiece[], + materials: Readonly> | undefined, +): WetReading | undefined { + const stretches = roomWallFaces(nodes, zone) + if (!stretches.length) return undefined + const fixtures = pieces.filter(isFixture) + const wetKeys = new Set() + for (const stretch of stretches) + if (fixtures.some((piece) => against(nodes, byId, stretch, piece, 0))) + wetKeys.add(`${stretch.wallId}/${stretch.face}/${stretch.t0}`) + const byFixtures = wetKeys.size > 0 + const read = stretches.filter( + (stretch) => !byFixtures || wetKeys.has(`${stretch.wallId}/${stretch.face}/${stretch.t0}`), + ) + + const reads = read.map((stretch) => readStretch(nodes, zone, stretch, stretch, materials)) + const tiled = combine(reads.map((r) => reaches(r, WET_TILED_TO_M))) + const readable = reads.every((r) => !r.open.some(Boolean)) + const tiledTo = readable ? Math.min(...reads.map(coveredTo)) : null + + const showers = pieces.filter(isShower).flatMap((piece) => { + const fulls = stretches.flatMap((stretch) => { + const range = against(nodes, byId, stretch, piece, SHOWER_MARGIN_M) + if (!range) return [] + const there = readStretch(nodes, zone, stretch, range, materials) + return [reaches(there, there.height - CEILING_SLACK_M)] + }) + return fulls.length ? [{ id: piece.id, name: piece.name, full: combine(fulls) }] : [] + }) + + return { + byFixtures, + tiledTo, + anyTile: reads.some((r) => r.tops.some((top) => top > SLACK_M)), + tiled, + showers, + verdict: combine([tiled, ...showers.map((shower) => shower.full)]), + } +} diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index eaf579c5ee..7992fa848b 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -39,6 +39,7 @@ import { import { layoutIssuesFromScene } from './layout-clearance' import { wallResolvedHeight } from './level-reads' import { pointInPolygon, polygonContainsPolygon, type Vec2 } from './plan-geometry' +import type { RoomCheckIssue } from './room-checks' import { type RoomFinding, roomFindings } from './room-findings' import { EMPTY_SESSION } from './scene-checkpoint' import { changesSince, type SceneCheckpoint } from './scene-measure' @@ -105,6 +106,7 @@ export type SceneIssue = | WallEndShortIssue | WallNearlyAlignedIssue | UsageIssue + | RoomCheckIssue /** What verify_scene was asked: its contract's input, which other modules may extend. */ export type VerifySceneInput = Readonly> @@ -117,7 +119,7 @@ export type VerifySceneInput = Readonly> export type SceneCheck = { name: string order: number - run: (nodes: SceneNodes, input: VerifySceneInput) => SceneIssue[] + run: (nodes: SceneNodes, input: VerifySceneInput, context: AgentContext) => SceneIssue[] } export const CHECKPOINT_ORDER = 100 @@ -776,7 +778,7 @@ export const verifyScene: AgentOperation = ( issues.push(...ceilingObjectObservations(settled)) issues.push(...wallObjectObservations(settled)) for (const check of checks) - if (check.order < CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {})) + if (check.order < CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {}, context)) // What the edits since the host's checkpoint lost, by place. const hosted = context.checkpoint ? changesSince(context.checkpoint as SceneCheckpoint, scene) @@ -788,7 +790,7 @@ export const verifyScene: AgentOperation = ( const since = typeof input?.since === 'string' ? reviewSince(session, input.since, scene) : null if (since?.places) issues.push(...since.places.issues) for (const check of checks) - if (check.order >= CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {})) + if (check.order >= CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {}, context)) const occupiedStoryCount = levels.filter((level) => level.isOccupiedStory).length return { diff --git a/packages/core/src/agent-operations/wall-face-defaults.ts b/packages/core/src/agent-operations/wall-face-defaults.ts new file mode 100644 index 0000000000..f69969ce6c --- /dev/null +++ b/packages/core/src/agent-operations/wall-face-defaults.ts @@ -0,0 +1,300 @@ +import { getLevelDisplayName } from '../lib/level-name' +import type { WallFace, WallNode, ZoneNode } from '../schema' +import { + resolveWallExteriorSide, + wallAssemblyExposedStructure, + wallAssemblyFinishRef, +} from '../systems/wall/wall-assembly' +import { getWallCurveFrameAt, isCurvedWall } from '../systems/wall/wall-curve' +import { + describeWallFaceFinishes, + getWallLevelZones, + getWallZoneSpans, +} from '../systems/wall/wall-finish' +import { + calculateLevelMiters, + DEFAULT_WALL_HEIGHT, + getWallPlanFootprint, +} from '../systems/wall/wall-footprint' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import { distanceToSegment, pointInPolygon, type Vec2 } from './plan-geometry' +import { levelRole, levelsOf, nodesOnLevel } from './scene-queries' +import type { SceneNodes } from './types' + +/** + * Every visible wall face at the default finish, read from the walls themselves and not through a + * room: a stub that stands inside a room on no boundary, a partition side no zone looks at, an outside + * face, all show the viewer's fallback finish the same. A face is read where somebody wrote nothing for + * it: no slot, no legacy finish, no room finish over it, no paint region on the stretch, no finish + * script, and, on the exterior side, no assembly cladding. What is not visible is not read: the end + * of a wall that runs into another wall's body (a face inside a body of the same height or more) is + * no face. What is not modelled: a paint region that covers part of a face's height counts as covering + * its stretch, and a curved wall's buried ends are not cut. + */ + +type Interval = [number, number] + +/** A default stretch shorter than this is a sliver at a join, not a face. */ +const MIN_STRETCH_M = 0.1 +/** A point of a face this far inside another wall's outline is in its body; closer is on its surface. */ +const BURIED_MARGIN_M = 0.01 +/** How far in front of a face a probe looks for the room it stands in. */ +const LOOK_AHEAD_M = 0.05 +/** Another wall buries a face only when it is not lower than the wall by more than this. */ +const HEIGHT_SLACK_M = 0.05 + +export type DefaultWallFace = { + wallId: string + wallName: string + levelId: string + levelName: string + face: WallFace + /** Metres of the face at the default, visible stretches only. */ + metres: number + /** Metres along the wall's reference line, each stretch. */ + stretches: Interval[] + /** Plan points (x, z) on the wall's reference line where the first stretch starts and the last ends. */ + from: [number, number] + to: [number, number] + /** The rooms that stand on this face along its default stretches. */ + facing: string[] + /** With none facing: the rooms the wall stands inside, on no boundary. */ + standsIn: string[] +} + +export type WallFaceReading = { + /** Visible wall faces read (a face with a visible stretch of `MIN_STRETCH_M` or more). */ + faces: number + metres: number + defaults: DefaultWallFace[] +} + +const length = (stretches: readonly Interval[]) => + stretches.reduce((sum, [u0, u1]) => sum + u1 - u0, 0) + +function merged(intervals: readonly Interval[]): Interval[] { + const out: Interval[] = [] + for (const [u0, u1] of [...intervals].sort((p, q) => p[0] - q[0])) { + const last = out.at(-1) + if (last && u0 <= last[1] + 1e-9) last[1] = Math.max(last[1], u1) + else out.push([u0, u1]) + } + return out +} + +/** `from` less every `cut`, as intervals longer than `MIN_STRETCH_M`. */ +function subtract(from: readonly Interval[], cut: readonly Interval[]): Interval[] { + const holes = merged(cut) + const out: Interval[] = [] + for (const [a, b] of from) { + let reach = a + for (const [h0, h1] of holes) { + if (h1 <= reach || h0 >= b) continue + if (h0 > reach) out.push([reach, h0]) + reach = Math.max(reach, h1) + } + if (reach < b) out.push([reach, b]) + } + return out.filter(([u0, u1]) => u1 - u0 >= MIN_STRETCH_M) +} + +type Body = { wall: WallNode; ring: Vec2[]; bounds: [number, number, number, number] } + +function bodiesOf(walls: readonly WallNode[]): Body[] { + const usable = walls.filter( + (wall) => + Array.isArray(wall.start) && + Array.isArray(wall.end) && + wall.wallType !== 'curtain' && + wall.visible !== false, + ) + let miters: ReturnType + try { + miters = calculateLevelMiters(usable) + } catch { + return [] + } + return usable.flatMap((wall) => { + const ring = getWallPlanFootprint(wall, miters).map((point): Vec2 => [point.x, point.y]) + if (ring.length < 3) return [] + const xs = ring.map(([x]) => x) + const zs = ring.map(([, z]) => z) + return [ + { wall, ring, bounds: [Math.min(...xs), Math.min(...zs), Math.max(...xs), Math.max(...zs)] }, + ] + }) +} + +const heightOf = (wall: WallNode) => wall.height ?? DEFAULT_WALL_HEIGHT + +/** Whether a point is in a ring's body: inside it and more than `BURIED_MARGIN_M` from its surface. */ +function inBody(point: Vec2, ring: readonly Vec2[]): boolean { + if (!pointInPolygon(point, [...ring], false)) return false + for (let index = 0; index < ring.length; index += 1) + if (distanceToSegment(point, ring[index]!, ring[(index + 1) % ring.length]!) < BURIED_MARGIN_M) + return false + return true +} + +/** + * The stretches of a straight wall's face line (metres along the wall) that lie inside the body of + * another wall of the level, one at least as high: a face there is covered, not seen. + */ +function buriedStretches(wall: WallNode, offset: number, bodies: readonly Body[]): Interval[] { + const dx = wall.end[0] - wall.start[0] + const dz = wall.end[1] - wall.start[1] + const run = Math.hypot(dx, dz) + if (run < 1e-9) return [] + const nx = -dz / run + const nz = dx / run + const p0: Vec2 = [wall.start[0] + nx * offset, wall.start[1] + nz * offset] + const d: Vec2 = [dx, dz] + const box = [ + Math.min(p0[0], p0[0] + dx), + Math.min(p0[1], p0[1] + dz), + Math.max(p0[0], p0[0] + dx), + Math.max(p0[1], p0[1] + dz), + ] + const cross = (ax: number, ay: number, bx: number, by: number) => ax * by - ay * bx + const buried: Interval[] = [] + for (const body of bodies) { + if (body.wall.id === wall.id || heightOf(body.wall) < heightOf(wall) - HEIGHT_SLACK_M) continue + const [x0, z0, x1, z1] = body.bounds + if (x1 < box[0]! - BURIED_MARGIN_M || x0 > box[2]! + BURIED_MARGIN_M) continue + if (z1 < box[1]! - BURIED_MARGIN_M || z0 > box[3]! + BURIED_MARGIN_M) continue + const cuts = [0, 1] + for (let index = 0; index < body.ring.length; index += 1) { + const q0 = body.ring[index]! + const q1 = body.ring[(index + 1) % body.ring.length]! + const e: Vec2 = [q1[0] - q0[0], q1[1] - q0[1]] + const denominator = cross(d[0], d[1], e[0], e[1]) + if (Math.abs(denominator) < 1e-12) continue + const w: Vec2 = [q0[0] - p0[0], q0[1] - p0[1]] + const t = cross(w[0], w[1], e[0], e[1]) / denominator + const s = cross(w[0], w[1], d[0], d[1]) / denominator + if (s >= 0 && s <= 1 && t > 0 && t < 1) cuts.push(t) + } + cuts.sort((p, q) => p - q) + for (let index = 0; index + 1 < cuts.length; index += 1) { + const [t0, t1] = [cuts[index]!, cuts[index + 1]!] + if ((t1 - t0) * run < 1e-4) continue + const middle: Vec2 = [p0[0] + d[0] * ((t0 + t1) / 2), p0[1] + d[1] * ((t0 + t1) / 2)] + if (inBody(middle, body.ring)) buried.push([t0 * run, t1 * run]) + } + } + return merged(buried) +} + +const rounded = (value: number) => Math.round(value * 100) / 100 + +function pointAlong(wall: WallNode, u: number): [number, number] { + const run = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + const { point } = getWallCurveFrameAt(wall, run > 0 ? u / run : 0) + return [rounded(point.x), rounded(point.y)] +} + +const FACES: readonly WallFace[] = ['a', 'b'] + +/** + * Every wall face of the scene read for the default finish. Walls that are hidden, curtain walls and + * walls on a roof level are left out; a scene whose walls cannot be walked reads as no faces. + */ +export function readWallFaces(nodes: SceneNodes): WallFaceReading { + const reading: WallFaceReading = { faces: 0, metres: 0, defaults: [] } + for (const level of levelsOf(nodes)) { + if (levelRole(nodes, level).role === 'roof') continue + const walls = nodesOnLevel(nodes, level.id).filter( + (node): node is WallNode => + node.type === 'wall' && + node.visible !== false && + node.wallType !== 'curtain' && + Array.isArray(node.start) && + Array.isArray(node.end), + ) + if (!walls.length) continue + const bodies = bodiesOf(walls) + const rooms = getWallLevelZones({ parentId: level.id }, nodes).filter( + (zone) => zone.spaceRole === 'room' && zone.polygon.length >= 3, + ) + const levelName = getLevelDisplayName(level) + for (const wall of walls) { + const run = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + if (run < MIN_STRETCH_M) continue + const finishes = describeWallFaceFinishes(wall, nodes) + const offsets = getWallFaceOffsets(wall) + const spans = getWallZoneSpans(wall, rooms) + const exteriorSide = resolveWallExteriorSide(wall) + const clad = + wallAssemblyFinishRef(wall) !== null || wallAssemblyExposedStructure(wall) !== null + for (const face of FACES) { + const buried = isCurvedWall(wall) ? [] : buriedStretches(wall, offsets[face], bodies) + const visible = subtract([[0, run]], buried) + const seen = length(visible) + if (seen < MIN_STRETCH_M) continue + reading.faces += 1 + reading.metres += seen + const written = + wall.finishScripts?.[face] !== undefined || + (clad && exteriorSide !== null && (exteriorSide === 1 ? 'a' : 'b') === face) + if (written) continue + const own = finishes[face].stretches + .filter((stretch) => stretch.source === 'wall_face' && stretch.chain === 'default') + .map((stretch): Interval => [stretch.u0, stretch.u1]) + const painted = finishes[face].paintRegions.map( + (region): Interval => [region.u0 ?? 0, region.u1 ?? run], + ) + const stretches = subtract(subtract(own, painted), buried) + if (!stretches.length) continue + const first = stretches[0]![0] + const last = stretches.at(-1)![1] + const faceSpans = spans.filter( + (span) => + span.face === face && + stretches.some(([u0, u1]) => span.t1 * run > u0 + 0.02 && span.t0 * run < u1 - 0.02), + ) + const facing = [...new Set(faceSpans.map((span) => (nodes[span.zoneId] as ZoneNode).name))] + const standsIn = facing.length + ? [] + : roomsStoodIn(wall, face, offsets[face], stretches, rooms) + reading.defaults.push({ + wallId: wall.id, + wallName: wall.name ?? wall.id, + levelId: level.id, + levelName, + face, + metres: length(stretches), + stretches, + from: pointAlong(wall, first), + to: pointAlong(wall, last), + facing, + standsIn, + }) + } + } + } + return reading +} + +/** The rooms a probe a little in front of the stretches' middle lies in. */ +function roomsStoodIn( + wall: WallNode, + face: WallFace, + offset: number, + stretches: readonly Interval[], + rooms: readonly ZoneNode[], +): string[] { + const widest = [...stretches].sort((p, q) => q[1] - q[0] - (p[1] - p[0]))[0]! + const run = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + const dx = wall.end[0] - wall.start[0] + const dz = wall.end[1] - wall.start[1] + const [x, z] = pointAlong(wall, (widest[0] + widest[1]) / 2) + const ahead = offset + (face === 'a' ? LOOK_AHEAD_M : -LOOK_AHEAD_M) + const probe: Vec2 = [x + (-dz / run) * ahead, z + (dx / run) * ahead] + return rooms + .filter( + (zone) => + pointInPolygon(probe, zone.polygon as Vec2[]) && + !(zone.holes ?? []).some((hole) => pointInPolygon(probe, hole as Vec2[], false)), + ) + .map((zone) => zone.name) +} diff --git a/packages/core/src/agent-operations/wall-item-faces.test.ts b/packages/core/src/agent-operations/wall-item-faces.test.ts new file mode 100644 index 0000000000..27aca413db --- /dev/null +++ b/packages/core/src/agent-operations/wall-item-faces.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, test } from 'bun:test' +import { BuildingNode, ItemNode, LevelNode, WallNode, ZoneNode } from '../schema' +import { roomCheckIssues } from './room-checks' +import type { SceneNodes } from './types' +import { wallItemFaceIssues } from './wall-item-faces' + +/** + * Bed 3 (z 0 to 3) and the Garage (z 3 to 6) share a wall on z = 3 that runs along +x: its face `a` + * (the item's `front`) looks into the Garage, its face `b` (`back`) into Bed 3. The south wall, on z = 0, + * has Bed 3 on its face `a` and the outside on its face `b`. Linen is a room elsewhere. + */ +const scene = (items: Record[]): SceneNodes => { + const asset = (name: string) => ({ + id: name, + name, + category: 'art', + thumbnail: '/t.webp', + src: 'asset://art', + dimensions: [0.6, 0.8, 0.03], + attachTo: 'wall-side', + }) + const hosted = items.map((item, index) => + ItemNode.parse({ + id: `item_${index}`, + parentId: item.wall ?? 'wall_mid', + wallId: item.wall ?? 'wall_mid', + position: [2, 1.5, 0], + side: item.side, + name: item.name, + metadata: item.metadata ?? {}, + asset: asset(String(item.name)), + }), + ) + const walls = [ + WallNode.parse({ + id: 'wall_mid', + parentId: 'level_1', + name: 'Party wall', + start: [0, 3], + end: [4, 3], + children: hosted.filter((h) => h.parentId === 'wall_mid').map((h) => h.id), + }), + WallNode.parse({ + id: 'wall_south', + parentId: 'level_1', + name: 'South wall', + start: [0, 0], + end: [4, 0], + children: hosted.filter((h) => h.parentId === 'wall_south').map((h) => h.id), + }), + ] + const zone = (id: string, name: string, polygon: [number, number][], walls: string[]) => + ZoneNode.parse({ + id, + parentId: 'level_1', + name, + polygon, + spaceRole: 'room', + boundaryWallIds: walls, + }) + const nodes = [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ + id: 'level_1', + parentId: 'building_1', + level: 0, + children: ['wall_mid', 'wall_south', 'zone_bed', 'zone_garage', 'zone_linen'], + }), + ...walls, + zone( + 'zone_bed', + 'Bed 3', + [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ], + ['wall_mid', 'wall_south'], + ), + zone( + 'zone_garage', + 'Garage', + [ + [0, 3], + [4, 3], + [4, 6], + [0, 6], + ], + ['wall_mid'], + ), + zone( + 'zone_linen', + 'Linen', + [ + [6, 0], + [8, 0], + [8, 2], + [6, 2], + ], + [], + ), + ...hosted, + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes +} + +const found = (items: Record[]) => wallItemFaceIssues(scene(items)) + +describe('a piece hung on the face that looks into another room than the one it names', () => { + test('an art print named for Bed 3 on the face that looks into the Garage is a warning that names the item, the face and both rooms', () => { + const [issue] = found([{ name: 'Hot-air balloon art print (Bed 3)', side: 'front' }]) + expect(issue).toMatchObject({ type: 'room_wall_item_wrong_face', severity: 'warning' }) + expect(issue!.message).toBe( + '“Hot-air balloon art print (Bed 3)” hangs on the front face of “Party wall”, which looks into “Garage”, but it names “Bed 3”, the room on the other face.', + ) + expect(issue!.nodeIds).toEqual(['item_0', 'wall_mid', 'zone_garage', 'zone_bed']) + }) + + test('the same print on the other face, or one that names no room, says nothing', () => { + expect(found([{ name: 'Hot-air balloon art print (Bed 3)', side: 'back' }])).toHaveLength(0) + expect(found([{ name: 'Hot-air balloon art print', side: 'front' }])).toHaveLength(0) + }) + + test('the reason it was placed names the room as the name does', () => { + expect( + found([ + { name: 'Mirror', side: 'front', metadata: { reason: 'Mirror over the dresser in Bed 3' } }, + ]), + ).toHaveLength(1) + }) + + test('a word that is also a room elsewhere is no claim: linen curtains are not for the Linen room', () => { + expect(found([{ name: 'Sheer linen curtains', side: 'front' }])).toHaveLength(0) + }) + + test('cladding named for a room is the facade of its wall, whichever face it is on', () => { + expect(found([{ name: 'Bed 3 — vertical cedar cladding', side: 'front' }])).toHaveLength(0) + }) + + test('a curtain named for Bed 3 on the face of the south wall that looks outside is a warning that says outside', () => { + const [issue] = found([{ name: 'Bed 3 curtains', side: 'back', wall: 'wall_south' }]) + expect(issue!.message).toBe( + '“Bed 3 curtains” hangs on the back face of “South wall”, which looks into the outside, but it names “Bed 3”, the room on the other face.', + ) + expect(found([{ name: 'Bed 3 curtains', side: 'front', wall: 'wall_south' }])).toHaveLength(0) + }) + + test('it is one of the room checks', () => { + const types = roomCheckIssues(scene([{ name: 'Art print (Bed 3)', side: 'front' }])).map( + (issue) => issue.type, + ) + expect(types).toContain('room_wall_item_wrong_face') + }) +}) diff --git a/packages/core/src/agent-operations/wall-item-faces.ts b/packages/core/src/agent-operations/wall-item-faces.ts new file mode 100644 index 0000000000..510497c343 --- /dev/null +++ b/packages/core/src/agent-operations/wall-item-faces.ts @@ -0,0 +1,73 @@ +import { resolveLevelId } from '../lib/node-ancestry' +import type { ItemNode, WallNode, ZoneNode } from '../schema' +import { isBuildingElementItem } from '../spatial/usage-field/pieces' +import { getWallZoneSpans } from '../systems/wall/wall-finish' +import type { RoomCheckIssue } from './room-checks' +import { queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +const quote = (name: string) => `“${name}”` +const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** The words an item carries that can name its room: its name, its asset, and every text of its metadata (the reason it was placed, the feature it serves). */ +function textOf(item: ItemNode): string { + const metadata = Object.values(item.metadata ?? {}).filter( + (value): value is string => typeof value === 'string', + ) + return [item.name, item.asset?.name, ...metadata].filter(Boolean).join(' | ') +} + +const mentions = (text: string, name: string) => + new RegExp(`(^|[^\\p{L}\\p{N}])${escaped(name.trim())}($|[^\\p{L}\\p{N}])`, 'iu').test(text) + +/** + * A piece hung on a wall (art, a mirror, a shelf, a screen, a curtain) is on one face of it, and a face + * looks into one room, or the outside. When the item's name, asset or the reason it was placed names the + * room on the other face of its wall, and not the one its own face looks into (or the outside), it is on + * the wrong side: the finding names the item, the face, the room that face looks into and the room on + * the other face. An item that names no room on its wall (a "linen" curtain is not for the Linen room, + * a "kitchen" towel hook may hang in the bath), or whose face is not stored (no `side`), makes no claim, nor does a building element (cladding, trim). + */ +export function wallItemFaceIssues(nodes: SceneNodes): RoomCheckIssue[] { + const out: RoomCheckIssue[] = [] + const zonesOf = new Map() + for (const node of queryNodes(nodes, { type: 'zone' })) + if (node.parentId && String(node.name ?? '').trim()) + zonesOf.set(node.parentId, [...(zonesOf.get(node.parentId) ?? []), node]) + for (const node of queryNodes(nodes, { type: 'item' })) { + // cladding, trim and the like are the building's skin: a facade's is meant to face outside whichever room it is named for + if (!node.side || isBuildingElementItem(node)) continue + const wall = node.parentId ? nodes[node.parentId] : undefined + if (wall?.type !== 'wall') continue + const levelId = resolveLevelId(wall as WallNode, nodes as never) + const zones = zonesOf.get(levelId ?? '') ?? [] + const text = textOf(node) + const named = zones.filter((zone) => mentions(text, String(zone.name))) + if (named.length === 0) continue + const length = Math.hypot( + (wall as WallNode).end[0] - (wall as WallNode).start[0], + (wall as WallNode).end[1] - (wall as WallNode).start[1], + ) + if (!(length > 0)) continue + const station = (node.position[0] ?? 0) / length + const spans = getWallZoneSpans(wall as WallNode, zones).filter( + (span) => station >= span.t0 - 1e-6 && station <= span.t1 + 1e-6, + ) + const face = node.side === 'front' ? 'a' : 'b' + const zoneOn = (which: 'a' | 'b') => + zones.find((zone) => spans.some((span) => span.face === which && span.zoneId === zone.id)) + const here = zoneOn(face) + const across = zoneOn(face === 'a' ? 'b' : 'a') + const namedNames = new Set(named.map((zone) => String(zone.name).toLowerCase())) + if (!across || !namedNames.has(String(across.name).toLowerCase())) continue + if (here && namedNames.has(String(here.name).toLowerCase())) continue + const wall0 = wall as WallNode + out.push({ + type: 'room_wall_item_wrong_face', + message: `${quote(String(node.name ?? node.asset.name))} hangs on the ${node.side} face of ${quote(String(wall0.name ?? wall0.id))}, which looks into ${here ? quote(String(here.name)) : 'the outside'}, but it names ${quote(String(across.name))}, the room on the other face.`, + severity: 'warning', + nodeIds: [node.id, wall0.id, ...(here ? [here.id] : []), across.id], + }) + } + return out +} diff --git a/packages/core/src/agent-operations/wall-outside-finish.test.ts b/packages/core/src/agent-operations/wall-outside-finish.test.ts new file mode 100644 index 0000000000..ac53526a60 --- /dev/null +++ b/packages/core/src/agent-operations/wall-outside-finish.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, BuildingNode, LevelNode, SiteNode, WallNode, ZoneNode } from '../schema' +import { roomCheckIssues } from './room-checks' +import type { SceneNodes } from './types' +import { wallInsideFaces } from './wall-outside-finish' + +/** + * The finish of an outside face shown on the inside face of the same wall. Walls here run so that + * face a is on their left: the outer ring runs counter-clockwise, so a is in and b is out; the + * partitions run north, so a looks west. + */ + +const STUCCO = 'library:concrete-stucco' +const WHITE = 'library:preset-white' + +type Room = { name: string; x0: number; x1: number } +type Wall = { id: string; start: [number, number]; end: [number, number]; slots?: object } + +function scene(rooms: Room[], walls: Wall[]): SceneNodes { + const zones = rooms.map(({ name, x0, x1 }, index) => + ZoneNode.parse({ + id: `zone_${index}`, + parentId: 'level_0', + name, + polygon: [ + [x0, 0], + [x1, 0], + [x1, 4], + [x0, 4], + ], + spaceRole: 'room', + // The rooms list the walls the way the structure reconciler writes them; the spans are cut by geometry. + boundaryWallIds: walls.map((wall) => wall.id), + }), + ) + const parsed = walls.map(({ id, start, end, slots }) => + WallNode.parse({ id, parentId: 'level_0', start, end, ...(slots ? { slots } : {}) }), + ) + const nodes: AnyNode[] = [ + SiteNode.parse({ id: 'site_0', children: ['building_0'] }), + BuildingNode.parse({ id: 'building_0', parentId: 'site_0', children: ['level_0'] }), + LevelNode.parse({ + id: 'level_0', + parentId: 'building_0', + level: 0, + children: [...parsed.map((wall) => wall.id), ...zones.map((zone) => zone.id)], + }), + ...parsed, + ...zones, + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes +} + +const BOTH = { a: STUCCO, b: STUCCO } +/** A house of two bedrooms, 0..3 and 3..6, a partition between them and four outer walls. */ +const house = (outer: object | undefined, mid: object | undefined, extra: Room[] = []) => + scene( + [{ name: 'Bed 1', x0: 0, x1: 3 }, { name: 'Bed 2', x0: 3, x1: 6 }, ...extra], + [ + { id: 'wall_s', start: [0, 0], end: [6, 0], slots: outer }, + { id: 'wall_e', start: [6, 0], end: [6, 4], slots: outer }, + { id: 'wall_n', start: [6, 4], end: [0, 4], slots: outer }, + { id: 'wall_w', start: [0, 4], end: [0, 0], slots: outer }, + { id: 'wall_mid', start: [3, 0], end: [3, 4], slots: mid }, + ], + ) +const found = (nodes: SceneNodes) => + roomCheckIssues(nodes).filter((issue) => issue.type === 'walls_outside_finish_inside') + +describe('the outside finish on the inside of a wall', () => { + test('both faces of the outer walls in one finish, the partition in another: one finding, the walls and rooms named', () => { + const [issue, ...rest] = found(house(BOTH, { a: WHITE, b: WHITE })) + expect(rest).toEqual([]) + expect(issue?.nodeIds.sort()).toEqual(['wall_e', 'wall_n', 'wall_s', 'wall_w']) + expect(issue?.message).toContain('White Stucco') + expect(issue?.message).toContain('shows on both faces of 4 walls (20.0 m)') + expect(issue?.message).toContain('looks into Bed 1, Bed 2') + expect(issue?.message).toContain('the partitions of the scene show White') + }) + + test('the finish on the outside face alone is the outside finish', () => { + expect(found(house({ b: STUCCO }, { a: WHITE, b: WHITE }))).toEqual([]) + }) + + test('the default on both faces writes nothing, so shows no finish twice', () => { + expect(found(house(undefined, undefined))).toEqual([]) + }) + + test('a finish a partition shows is the house’s inside finish', () => { + expect(found(house(BOTH, BOTH))).toEqual([]) + // Plain white inside and out is the same: white is on the partitions. + const white = { a: WHITE, b: WHITE } + expect(found(house(white, white))).toEqual([]) + }) + + test('with no partition there is nothing inside to tell it from', () => { + const studio = scene( + [{ name: 'Studio', x0: 0, x1: 6 }], + [ + { id: 'wall_s', start: [0, 0], end: [6, 0], slots: BOTH }, + { id: 'wall_e', start: [6, 0], end: [6, 4], slots: BOTH }, + { id: 'wall_n', start: [6, 4], end: [0, 4], slots: BOTH }, + { id: 'wall_w', start: [0, 4], end: [0, 0], slots: BOTH }, + ], + ) + expect(found(studio)).toEqual([]) + }) + + test('a wall toward a porch or an alfresco is an outside wall', () => { + const toPorch = scene( + [ + { name: 'Bed 1', x0: 0, x1: 2 }, + { name: 'Bed 2', x0: 2, x1: 4 }, + { name: 'Porch', x0: 4, x1: 6 }, + ], + [ + { id: 'wall_a', start: [2, 0], end: [2, 4], slots: { a: WHITE, b: WHITE } }, + { id: 'wall_b', start: [4, 0], end: [4, 4], slots: BOTH }, + ], + ) + const [issue] = found(toPorch) + expect(issue?.nodeIds).toEqual(['wall_b']) + expect(issue?.message).toContain('looks into Bed 2') + expect(issue?.message).not.toContain('Porch') + expect(wallInsideFaces(toPorch, toPorch.wall_b as WallNode)).toEqual(['a']) + }) + + test('a partition has rooms on both faces, and a wall no room stands on has none to read', () => { + expect(wallInsideFaces(house(BOTH, BOTH), house(BOTH, BOTH).wall_mid as WallNode)).toEqual([ + 'a', + 'b', + ]) + const lone = scene([], [{ id: 'wall_x', start: [0, 0], end: [4, 0], slots: BOTH }]) + expect(wallInsideFaces(lone, lone.wall_x as WallNode)).toBeNull() + }) +}) diff --git a/packages/core/src/agent-operations/wall-outside-finish.ts b/packages/core/src/agent-operations/wall-outside-finish.ts new file mode 100644 index 0000000000..5b7e9cc2f4 --- /dev/null +++ b/packages/core/src/agent-operations/wall-outside-finish.ts @@ -0,0 +1,137 @@ +import { isOutdoorRoom } from '../building/room-use' +import type { SceneMaterial, WallFace, WallNode, ZoneNode } from '../schema' +import { + describeWallFaceFinishes, + getWallLevelZones, + getWallZoneSpans, + type WallFaceStretch, +} from '../systems/wall/wall-finish' +import { describeFinish, type FinishFact } from './room-finishes' +import { queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +/** + * Which walls show the finish of their outside face on their inside face too. A wall is read as + * outside when indoor rooms stand on half or more of one face and not of the other (a face toward a + * porch, an alfresco or open ground is outside); the finish of a face is the one that shows on at + * least half of its length by a ref somebody wrote (a wall left at the default shows none). The + * finish counts as the house's inside finish, and is left alone, when any partition (rooms on both + * faces) shows it: the walls inside are then dressed in it on purpose. + */ + +export type OutsideFinishInside = { + finish: FinishFact + walls: { id: string; levelId: string; lengthM: number; rooms: string[] }[] + /** The finishes the partitions of the scene show, longest first. */ + partitions: FinishFact[] +} + +type Materials = Readonly> | undefined + +/** The share of a face (0 to 1) that indoor rooms stand on. */ +function indoorShare(spans: readonly { t0: number; t1: number }[]): number { + let reach = 0 + let total = 0 + for (const span of [...spans].sort((p, q) => p.t0 - q.t0)) { + const from = Math.max(span.t0, reach) + if (span.t1 > from) total += span.t1 - from + reach = Math.max(reach, span.t1) + } + return total +} + +const lengthOf = (stretch: WallFaceStretch) => Math.max(0, stretch.u1 - stretch.u0) + +/** What a face shows by a ref somebody wrote, metres per ref; the default and a ref-less inline finish are none. */ +function writtenRefs(stretches: readonly WallFaceStretch[]): Map { + const refs = new Map() + for (const stretch of stretches) { + if (stretch.ref === null || (stretch.source === 'wall_face' && stretch.chain === 'default')) + continue + refs.set(stretch.ref, (refs.get(stretch.ref) ?? 0) + lengthOf(stretch)) + } + return refs +} + +/** The ref shown on at least half of the face's length, or null. */ +function dominantRef(stretches: readonly WallFaceStretch[]): string | null { + const total = stretches.reduce((sum, stretch) => sum + lengthOf(stretch), 0) + const [best] = [...writtenRefs(stretches)].sort((p, q) => q[1] - p[1]) + return best && total > 0 && best[1] >= total / 2 ? best[0] : null +} + +const FACES: readonly WallFace[] = ['a', 'b'] + +/** + * The faces of a wall that indoor rooms stand on for half of their length or more, or null when no + * room of the level stands on the wall at all (nothing to read it by: its stored sides are the + * only word on which way it faces). + */ +export function wallInsideFaces(nodes: SceneNodes, wall: WallNode): WallFace[] | null { + const rooms = getWallLevelZones(wall, nodes).filter( + (zone: ZoneNode) => zone.spaceRole === 'room' && zone.polygon.length >= 3, + ) + const spans = getWallZoneSpans(wall, rooms) + if (!spans.length) return null + return FACES.filter( + (face) => + indoorShare( + spans.filter( + (span) => span.face === face && !isOutdoorRoom(nodes[span.zoneId] as ZoneNode), + ), + ) >= 0.5, + ) +} + +export function outsideFinishInside( + nodes: SceneNodes, + materials?: Materials, +): OutsideFinishInside[] { + const groups = new Map() + const partitionRefs = new Map() + let partitions = 0 + for (const wall of queryNodes(nodes, { type: 'wall' })) { + if (wall.wallType === 'curtain' || wall.visible === false) continue + const inside = wallInsideFaces(nodes, wall) + if (!inside?.length) continue + const rooms = getWallLevelZones(wall, nodes).filter( + (zone: ZoneNode) => zone.spaceRole === 'room' && zone.polygon.length >= 3, + ) + const spans = getWallZoneSpans(wall, rooms) + const faces = describeWallFaceFinishes(wall, nodes) + if (inside.length === 2) { + partitions += 1 + for (const face of FACES) + for (const [ref, metres] of writtenRefs(faces[face].stretches)) + partitionRefs.set(ref, (partitionRefs.get(ref) ?? 0) + metres) + continue + } + const [innerFace] = inside as [WallFace] + const outerFace: WallFace = innerFace === 'a' ? 'b' : 'a' + const outer = dominantRef(faces[outerFace].stretches) + if (!outer || outer !== dominantRef(faces[innerFace].stretches)) continue + const lengthM = faces[innerFace].stretches.reduce((sum, s) => sum + lengthOf(s), 0) + const names = [ + ...new Set( + spans + .filter( + (span) => span.face === innerFace && !isOutdoorRoom(nodes[span.zoneId] as ZoneNode), + ) + .map((span) => (nodes[span.zoneId] as ZoneNode).name), + ), + ] + groups.set(outer, [ + ...(groups.get(outer) ?? []), + { id: wall.id, levelId: wall.parentId ?? '', lengthM, rooms: names }, + ]) + } + if (!partitions) return [] + const inPartitions = [...partitionRefs].sort((p, q) => q[1] - p[1]) + return [...groups] + .filter(([ref]) => !partitionRefs.has(ref)) + .map(([ref, walls]) => ({ + finish: describeFinish(ref, materials), + walls, + partitions: inPartitions.slice(0, 2).map(([other]) => describeFinish(other, materials)), + })) +} diff --git a/packages/core/src/building/room-use.ts b/packages/core/src/building/room-use.ts new file mode 100644 index 0000000000..11b0428200 --- /dev/null +++ b/packages/core/src/building/room-use.ts @@ -0,0 +1,120 @@ +/** + * What a room is for, read from its name: zones carry no use, so the name says (as + * `room-habitable.ts` does for windows). The patterns are the scene program's + * (`inferRoomType`, apps/community scene-program/library.ts, English only, first match wins) with the + * French the houses are named in, and `laundry`, which the program folds into `other`. The uses are + * the design brief's (`ROOM_USES`), so a room the brief announces and a room the scene holds are + * compared in one vocabulary. + */ + +import type { ZoneNode } from '../schema' + +/** What a room is for, in the words the scene's own room types use, with laundry besides. */ +export const ROOM_USES = [ + 'bedroom', + 'bathroom', + 'kitchen', + 'living', + 'dining', + 'office', + 'hallway', + 'laundry', + 'garage', + 'other', +] as const + +export type RoomUse = (typeof ROOM_USES)[number] + +/** + * A name as one comparison sees it: lower case, accents stripped, curly apostrophes straight, + * spaces collapsed ("Salle d’eau" and "salle d'eau" are one name). + */ +export function foldRoomName(name: string): string { + return name + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase() + .replace(/[‘’ʼ`´]/g, "'") + .replace(/\s+/g, ' ') + .trim() +} + +/** A name that opens with a circulation word is a hallway whatever follows: "Hall des chambres". */ +const CIRCULATION_FIRST = + /^(hall|halle|couloir|palier|vestibule|galerie|entree|corridor|landing|foyer|passage|degagement)\b/ + +/** + * A name that ends in a circulation noun (and perhaps a number) is a hallway whatever its first word + * says: "Study lobby", "Lower gallery", "Kitchen hall 2". One that ends in a closet is storage. + */ +const CIRCULATION_LAST = + /\b(hall|hallway|entry|entrance|landing|corridor|foyer|vestibule|lobby|gallery|galerie|couloir|palier|entree|degagement)(?: \d+)?$/ +const STORAGE_LAST = /\b(closet|dressing room|walk[- ]?in(?: closet)?)$/ + +/** + * A bed word as a word of its own: "Bed 1", "Bedroom 2", "Chambre". A name with one and a word for what stands beside a bedroom + * without being one (the way into it, its robe, its ensuite) is that other thing: "Bed 1 Entry" is the way into a bedroom, "Bed 3 WIR" + * its walk-in robe. Without this the bedroom pattern, which comes before the others, takes them. + */ +const BED_WORD = /\b(?:beds?|bedrooms?|chambres?)(?![a-z])/g +const BED_ANNEX = + /\b(?:entry|entrance|entree|hall|hallway|passage|corridor|couloir|degagement|vestibule|landing|palier|robes?|wardrobe|walk[- ]?in|wir|ensuite|en-suite)\b/ + +/** + * In order, the first match wins: "family bathroom" is a bathroom, not a living room; "dressing of + * the suite" is storage, not a bedroom. A bare "office" is an office, as the scene program has always + * read it, though in a French house it is the pantry beside the kitchen: an office is owed no + * window and asked for no tile, so the pantry is not wrongly held to either. A cellier is storage. + */ +const PATTERNS: readonly (readonly [RegExp, RoomUse])[] = [ + [ + /bath|shower|\bwc\b|toilet|ensuite|en-suite|powder|\bbains?\b|\bsdb\b|salle d'eau|douche|sanitaire|lavabo|lavatory|washroom|restroom/, + 'bathroom', + ], + [/laundry|buanderie|lingerie|utility|laverie/, 'laundry'], + [/dressing|walk-?in|closet|wardrobe|storage|rangement|placard|cellier|mud ?room/, 'other'], + [/bed(?!side)|nursery|chambre|\bsuite\b|dortoir|dormitory/, 'bedroom'], + [/kitchen|pantry|cuisine|garde-manger/, 'kitchen'], + [/dining|salle a manger/, 'dining'], + [/living|lounge|family|sitting|salon|sejour|piece de vie|great room/, 'living'], + [ + /hall|entry|entrance|landing|corridor|foyer|vestibule|lobby|gallery|stair|entree|palier|couloir|escalier|galerie|degagement|passage/, + 'hallway', + ], + [/office|study|\bden\b|library|workspace|bureau|bibliotheque/, 'office'], + [/garage|carport|parking/, 'garage'], +] + +/** The use a room's name gives it; `other` when the name says none. */ +export function roomUseOfName(name: string): RoomUse { + const folded = foldRoomName(name) + if (CIRCULATION_FIRST.test(folded) || CIRCULATION_LAST.test(folded)) return 'hallway' + if (STORAGE_LAST.test(folded)) return 'other' + if (BED_ANNEX.test(folded) && folded.match(BED_WORD)) { + const beside = roomUseOfName( + folded + .replace(BED_WORD, ' ') + .replace(/\b\d+\b/g, ' ') + .replace(/\s+/g, ' ') + .trim(), + ) + if (beside !== 'bedroom') return beside + } + for (const [pattern, use] of PATTERNS) if (pattern.test(folded)) return use + return 'other' +} + +const OUTDOOR_USE = + /\b(outdoor|outside|exterior|terrace|balcony|patio|porch|courtyard|garden|open air|alfresco|veranda|verandah|deck|pergola|carport|void|shaft|crawl ?space|non ?habitable|uninhabitable|unoccupied)\b/i + +/** A room that is not indoors: open on a side, or named or declared for an outdoor or unoccupied space (porch, alfresco, balcony, void). */ +export const isOutdoorRoom = (zone: Pick) => + zone.enclosureStatus === 'open' || + OUTDOOR_USE.test(`${zone.occupancy ?? ''} ${zone.name ?? ''}`.replace(/[-_]/g, ' ')) + +/** Rooms that are wet: tiled floors or walls are expected of them. */ +export const isWetRoomUse = (use: RoomUse) => use === 'bathroom' || use === 'laundry' + +/** Rooms whose walls meet a finished floor in view: the ones skirting is expected in. */ +export const isSkirtedRoomUse = (use: RoomUse) => + use === 'bedroom' || use === 'living' || use === 'dining' || use === 'office' || use === 'hallway' diff --git a/packages/core/src/coherence/__fixtures__/enclosure-scenes.ts b/packages/core/src/coherence/__fixtures__/enclosure-scenes.ts new file mode 100644 index 0000000000..852ca92994 --- /dev/null +++ b/packages/core/src/coherence/__fixtures__/enclosure-scenes.ts @@ -0,0 +1,85 @@ +import type { z } from 'zod' +import { + type AnyNode, + BuildingNode, + CeilingNode, + DoorNode, + LevelNode, + RoofNode, + RoofSegmentNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../schema' + +/** + * Buildings under a roof, for the Enclosure family: where the roof sits against the wall tops. + * Built from the geometry alone (levels, explicit wall heights, a roof's pitch and seat), so a + * scene can be broken by one number. Plan axes: x east, z south; a wall drawn clockwise has its + * interior on the front side. + */ + +export type EnclosureScene = { nodes: Record; rootNodeIds: string[] } + +export function graph(...nodes: AnyNode[]): EnclosureScene { + const byId = Object.fromEntries(nodes.map((node) => [node.id, { ...node }])) as Record< + string, + AnyNode & { children?: string[] } + > + for (const node of Object.values(byId)) { + const parent = node.parentId ? byId[node.parentId] : undefined + if (parent && Array.isArray(parent.children) && !parent.children.includes(node.id)) + parent.children = [...parent.children, node.id] + } + return { + nodes: byId, + rootNodeIds: nodes.filter((node) => node.type === 'building').map((node) => node.id), + } +} + +type Pt = [number, number] + +/** What a maker declares about a wall that meets a roof. */ +export type Declaration = { roofJunction?: 'parapet'; cap?: boolean } +type Declarations = Declaration | (Declaration | undefined)[] | undefined + +/** The four walls of a rectangle, drawn clockwise so the room is on their front side. */ +export function rectangleWalls( + levelId: string, + [x0, z0, x1, z1]: [number, number, number, number], + heights: [number?, number?, number?, number?] | number | undefined, + sides: 'exterior' | 'interior' = 'exterior', + tag = 'wall', + declare?: Declarations, +): WallNode[] { + const corners: Pt[] = [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], + ] + return corners.map((start, index) => { + const end = corners[(index + 1) % 4]! + const height = Array.isArray(heights) ? heights[index] : heights + return WallNode.parse({ + id: `${tag}_${index}`, + parentId: levelId, + start, + end, + ...(height === undefined ? {} : { height }), + ...(Array.isArray(declare) ? declare[index] : declare), + frontSide: 'interior', + backSide: sides, + }) + }) +} + +export const building = () => BuildingNode.parse({ id: 'building_main' }) +export const storey = (height: number) => + LevelNode.parse({ + id: 'level_0', + parentId: 'building_main', + level: 0, + name: 'Ground', + height, + }) diff --git a/packages/core/src/systems/wall/wall-finish.ts b/packages/core/src/systems/wall/wall-finish.ts index 9e8ee9725f..c360cade8a 100644 --- a/packages/core/src/systems/wall/wall-finish.ts +++ b/packages/core/src/systems/wall/wall-finish.ts @@ -345,6 +345,110 @@ export function resolveWallFaceChain( return { kind: 'default', ref: getWallFaceDefault(wall, face) } } +export type WallFaceStretchSource = 'room_face_override' | 'room_wall_material' | 'wall_face' + +/** A stretch of one wall face that shows one finish. */ +export type WallFaceStretch = { + /** Metres from the wall's start, along its reference line. */ + u0: number + u1: number + source: WallFaceStretchSource + /** The finish ref that shows; null when the wall's own finish is an inline spec naming no preset. */ + ref: string | null + /** The room that gives the finish (a room source only). */ + roomId?: string + roomName?: string + /** How the wall's own face reached `ref` (a `wall_face` source only): chosen, legacy or default. */ + chain?: WallFaceChainFinish['kind'] +} + +/** A paint region on a face: it shows over the stretches it covers (`v` is metres above the face's base). */ +export type WallFacePaintRegion = { + id: string + ref: string + u0?: number + u1?: number + v0?: number + v1?: number +} + +export type WallFaceFinishes = Record< + WallFace, + { stretches: WallFaceStretch[]; paintRegions: WallFacePaintRegion[] } +> + +const toMillimetre = (value: number) => Math.round(value * 1000) / 1000 + +/** + * What each face of a wall shows, for a reader that cannot render it: the resolution order above run + * along the face, with the room that gives each stretch. The renderer and the paint tool resolve a + * face through the same layout, so this agrees with both. Paint regions sit over the stretches and + * are listed apart; what is not modelled here: exterior assembly cladding, a ref that does not resolve. + */ +export function describeWallFaceFinishes( + wall: WallNode, + nodes: Readonly>, +): WallFaceFinishes { + const layout = buildWallFinishLayout(wall, getWallLevelZones(wall, nodes)) + const underRegions: WallFinishLayout = { ...layout, regions: { a: [], b: [] } } + const read = (face: WallFace) => { + const cuts = new Set([0, layout.length]) + for (const span of layout.spans[face]) + for (const u of [span.u0, span.u1]) + if (u > SPLIT_EPSILON && u < layout.length - SPLIT_EPSILON) cuts.add(u) + const stations = [...cuts].sort((x, y) => x - y) + const own = resolveWallFaceChain(wall, face) + const ownRef = own.kind === 'legacy' ? (own.spec.materialPreset ?? null) : own.ref + const stretches: WallFaceStretch[] = [] + const push = (stretch: WallFaceStretch) => { + const last = stretches.at(-1) + if ( + last && + last.source === stretch.source && + last.ref === stretch.ref && + last.roomId === stretch.roomId && + last.chain === stretch.chain && + stretch.u0 - last.u1 < SPLIT_EPSILON + ) + last.u1 = stretch.u1 + else stretches.push(stretch) + } + for (let index = 0; index + 1 < stations.length; index += 1) { + const u0 = toMillimetre(stations[index]!) + const u1 = toMillimetre(stations[index + 1]!) + if (u1 - u0 < SPLIT_EPSILON) continue + const hit = resolveWallFinish(underRegions, face, (u0 + u1) / 2, 0) + if (hit.source === 'override' || hit.source === 'zone') { + const zone = nodes[hit.zoneId] + const roomName = zone?.type === 'zone' ? zone.name : undefined + push({ + u0, + u1, + source: hit.source === 'override' ? 'room_face_override' : 'room_wall_material', + ref: hit.ref, + roomId: hit.zoneId, + ...(roomName ? { roomName } : {}), + }) + } else push({ u0, u1, source: 'wall_face', ref: ownRef, chain: own.kind }) + } + // A wall with no length has no stretch to read; its own face is what it would show. + if (stretches.length === 0) + stretches.push({ u0: 0, u1: 0, source: 'wall_face', ref: ownRef, chain: own.kind }) + const paintRegions = layout.regions[face].map( + (region): WallFacePaintRegion => ({ + id: region.id, + ref: region.finish, + ...(region.u0 !== undefined ? { u0: toMillimetre(region.u0) } : {}), + ...(region.u1 !== undefined ? { u1: toMillimetre(region.u1) } : {}), + ...(region.v0 !== undefined ? { v0: toMillimetre(region.v0) } : {}), + ...(region.v1 !== undefined ? { v1: toMillimetre(region.v1) } : {}), + }), + ) + return { stretches, paintRegions } + } + return { a: read('a'), b: read('b') } +} + // Paint roles a wall resolves to (the paint tool offers `room:`): // `a` / `b` / `aSkirting` … a wall slot // `region:` one paint region on the wall From 34b907aebc38092b711efd541a40298db714d52a Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 17:16:06 +0100 Subject: [PATCH 06/40] Item and door clearance findings name the figures, and stop naming what is designed item_overlap, item_too_close and door_blocked say the metres in their messages (the overlap, the gap and the move that clears it), and read the piece as it is built, not as its box: - a scripted piece is read by the solids its manifest declares (item-solids), so a chair tucked under its table, an oven in its cabinet run or a bedside beside its bed is a designed contact, not a finding; - rugs, runners and mats by their category or name, floor coverings that lie flat, are not obstacles; vehicles in a garage and wall panelling and trim are read for what they are; - a garage door is a door a vehicle drives through: it has no leaf to swing across the floor. Door keep-outs say which side the leaf opens to and how far, with a small margin. The two door checks keep their names: findBlockedDoors of layout-clearance reads shapes, the one of door-clearance reads boxes. Left out: the placement guard on findValidPlacement (a refusal hook for the usage checks), the roof's knee walls in the mid-room check, and the drawn-over-terrain slab elevation. Co-Authored-By: Claude Sonnet 5.5 --- .../agent-operations/door-clearance.test.ts | 49 ++ .../src/agent-operations/door-clearance.ts | 217 ++++++++- .../src/agent-operations/furniture-kind.ts | 118 ++++- packages/core/src/agent-operations/index.ts | 2 + .../core/src/agent-operations/item-solids.ts | 176 +++++++ .../agent-operations/layout-clearance.test.ts | 17 +- .../src/agent-operations/layout-clearance.ts | 452 ++++++++++++++---- .../src/agent-operations/plan-clearance.ts | 62 +++ packages/core/src/lib/door-operation.ts | 7 + 9 files changed, 986 insertions(+), 114 deletions(-) create mode 100644 packages/core/src/agent-operations/item-solids.ts create mode 100644 packages/core/src/agent-operations/plan-clearance.ts diff --git a/packages/core/src/agent-operations/door-clearance.test.ts b/packages/core/src/agent-operations/door-clearance.test.ts index d6b3999af0..da5e205cc7 100644 --- a/packages/core/src/agent-operations/door-clearance.test.ts +++ b/packages/core/src/agent-operations/door-clearance.test.ts @@ -217,3 +217,52 @@ describe('door-clearance', () => { expect(keepoutCoversPlanned(glancing, planned)).toBe(false) }) }) + +describe('a vehicle in its garage', () => { + // A 3 m wall along z = 6, 0.15 m thick, its door 2.3 m wide; the car's tail is 0.425 m from the wall face. + const garageWall = wall('wall_g', [0, 6], [3, 6]) + const garageDoor = (doorType: string) => ({ ...door('door_g', 'wall_g', 1.5, 2.3), doorType }) + const car = (tail: number, category = 'vehicle') => { + const base = item('item_car', [1.5, 0, tail - 2.2], [1.8, 1.4, 4.4], 'Hatchback car') + return { ...base, asset: { ...base.asset, category } } + } + const blockedBy = (nodes: unknown[]) => + findBlockedDoors({ nodes: nodes as AnyNode[] }).map((issue) => issue.itemId) + + test('a car parked clear of the garage door is not blocking it: it drives out through it', () => { + expect(blockedBy([garageWall, garageDoor('garage-sectional'), car(5.5)])).toEqual([]) + expect(blockedBy([garageWall, garageDoor('garage-rollup'), car(5.5)])).toEqual([]) + expect(blockedBy([garageWall, garageDoor('garage-tiltup'), car(5.5)])).toEqual([]) + }) + + test('a car named a car, with no category filed, is a vehicle too', () => { + expect(blockedBy([garageWall, garageDoor('garage-sectional'), car(5.5, '')])).toEqual([]) + }) + + test('a car through the door panel is blocking it: it stands in the opening', () => { + expect(blockedBy([garageWall, garageDoor('garage-sectional'), car(6.0)])).toEqual(['item_car']) + }) + + test('a car in the opening says what it blocks: a garage door, with the opening as the zone', () => { + const [issue] = findBlockedDoors({ + nodes: [garageWall, garageDoor('garage-sectional'), car(6.0)] as unknown as AnyNode[], + }) + expect(issue?.message).toStartWith('Door door_g (garage-sectional, 2.30 m wide) on wall wall_g') + expect(issue?.clearZone.depthM).toEqual({ inward: 0.075, outward: 0.075 }) + }) + + test('anything else in front of a garage door still blocks it', () => { + const shelf = item('item_shelf', [1.5, 0, 5.5], [1, 1.8, 0.4], 'Storage shelf') + expect(blockedBy([garageWall, garageDoor('garage-sectional'), shelf])).toEqual(['item_shelf']) + }) + + test('a car in front of a door with a leaf blocks it: the exemption is the garage door only', () => { + expect(blockedBy([garageWall, garageDoor('hinged'), car(5.5)])).toEqual(['item_car']) + }) + + test('a word that only contains "car" does not make a vehicle', () => { + const base = item('item_scarf', [1.5, 0, 5.2], [1, 1.2, 0.4], 'Scarf rack') + const scarf = { ...base, asset: { ...base.asset, category: '' } } + expect(blockedBy([garageWall, garageDoor('garage-sectional'), scarf])).toEqual(['item_scarf']) + }) +}) diff --git a/packages/core/src/agent-operations/door-clearance.ts b/packages/core/src/agent-operations/door-clearance.ts index 8beb54d3be..793973b553 100644 --- a/packages/core/src/agent-operations/door-clearance.ts +++ b/packages/core/src/agent-operations/door-clearance.ts @@ -7,11 +7,24 @@ * See docs/layout-clearance-error-log.md for pitfalls (levels, gap sign, scale). */ +import { isVehicleDoorType } from '../lib/door-operation' +import { area, intersection } from '../lib/polygon-boolean' import type { Vec3 } from '../procedural-items/recipe' import { boxCorners, rotateVector } from '../procedural-items/spatial' import { type AnyNode, getScaledDimensions } from '../schema' -import { isFloorUnderlay } from './furniture-kind' +import { DEFAULT_WALL_THICKNESS } from '../systems/wall/wall-footprint' +import { isFloorUnderlay, isVehicle } from './furniture-kind' +import type { ItemSolid } from './item-solids' import { itemLevelHeightRange, itemPlanAabbInLevel } from './item-space' +import { + axisOverlap, + type ClearMove, + clearingMoves, + describeMoves, + metres, + roundBox, + roundMm, +} from './plan-clearance' import { type Vec2, wallLength } from './plan-geometry' export type PlanAabb = { @@ -52,6 +65,20 @@ export type DoorKeepout = { localX: number /** The door's height: an item whose bottom is above it does not block the door. */ height: number + doorType?: string + /** Where the door stands on its wall's centre line, and the wall's normal there: 'inward' is the +normal side. */ + centre: Vec2 + normal: Vec2 + /** The zone along the wall: the door's width and a pad either side. */ + alongM: number + /** The zone's depth from the wall's centre line, on each side. */ + depthM: { inward: number; outward: number } + /** + * A vehicle door only: the opening itself, the thickness of its wall. A garage door rolls up and + * leaves no leaf on the floor, and a car parked inside is meant to drive out through it, so a car + * blocks it only by standing in the opening. + */ + vehicleAperture?: DoorKeepout } /** @@ -60,7 +87,7 @@ export type DoorKeepout = { * segments for room edges that do not have a wall node yet, so the id cannot * be the branded `wall_${string}`. */ -export type WallSegmentLike = { id: string; start: Vec2; end: Vec2 } +export type WallSegmentLike = { id: string; start: Vec2; end: Vec2; thickness?: number } /** * Door shape these helpers accept — a real `DoorNode` or a planned opening. @@ -74,6 +101,7 @@ export type DoorOpeningLike = { height?: number /** Which face the leaf swings towards: 'inward' is the wall's +normal side, as the door plan draws it. */ swingDirection?: 'inward' | 'outward' + doorType?: string } /** Plan depth (m) cleared on each side of the wall face through the opening. */ @@ -336,12 +364,31 @@ export function doorKeepoutFromWall( const xs = corners.map((c) => c[0]) const zs = corners.map((c) => c[1]) + const vehicleAperture = isVehicleDoorType(door.doorType) + ? doorKeepoutFromWall( + wall, + { ...door, doorType: undefined }, + { + clearDepth: (wall.thickness ?? DEFAULT_WALL_THICKNESS) / 2, + sidePad, + levelId: options?.levelId, + }, + ) + : null return { + ...(vehicleAperture + ? { vehicleAperture: { ...vehicleAperture, doorType: door.doorType } } + : {}), doorId: door.id, wallId: wall.id, levelId: options?.levelId ?? null, width, localX, + doorType: door.doorType, + centre: [sx + dx * localX, sz + dz * localX], + normal: [nx, nz], + alongM: 2 * half, + depthM: { inward: front, outward: -back }, height: typeof door.height === 'number' && door.height > 0 ? door.height : DEFAULT_DOOR_HEIGHT, aabb: { minX: Math.min(...xs), @@ -378,10 +425,34 @@ export function collectDoorKeepouts( return keepouts } +/** How near a door's keep-out an item may stand before it is read as in it (m): a leaf's play, not a measure of the house. */ +export const DOOR_KEEPOUT_MARGIN = 0.02 + export function itemBlocksDoorKeepout(itemAabb: PlanAabb, keepout: DoorKeepout): boolean { - return aabbsOverlap(itemAabb, keepout.aabb, 0.02) + return aabbsOverlap(itemAabb, keepout.aabb, DOOR_KEEPOUT_MARGIN) +} + +/** The side of its wall an item stands on: 'inward' is the wall's +normal side, as the door plan draws it. */ +export type DoorSide = 'inward' | 'outward' + +export type DoorClearZone = { + /** The box the check reads: the zone's bounding box in plan. */ + box: PlanAabb + alongWallM: number + /** Depth from the wall's centre line, on each side. */ + depthM: { inward: number; outward: number } } +/** How far an item stands in a door's zone: a box by its depth and the ways out of it, a real shape by its area. */ +export type DoorBlockReading = + | { + /** Along the shallower axis; 0 where the box is only within the margin of the zone. */ + overlapM: number + /** The moves of the item that leave it clear of the zone, nearest first. */ + clearBy: ClearMove[] + } + | { overlapAreaM2: number } + export type BlockedDoorIssue = { doorId: string wallId: string @@ -389,6 +460,108 @@ export type BlockedDoorIssue = { levelId?: string | null itemName?: string message: string + footprint: PlanAabb + side: DoorSide + clearZone: DoorClearZone + reading: DoorBlockReading +} + +/** How much of a keep-out an item's real shape must stand in to block it (m²): a touching edge is not. */ +export const DOOR_KEEPOUT_MIN_AREA = 1e-4 + +/** + * The area (m²) of an item's solids that reach below the door's head and stand in the keep-out, + * grown by the same margin the box is read with; 0 when none does. + */ +function solidsKeepoutArea(solids: readonly ItemSolid[], keepout: DoorKeepout): number { + const { minX, maxX, minZ, maxZ } = keepout.aabb + const m = DOOR_KEEPOUT_MARGIN + const zone: [number, number][] = [ + [minX - m, minZ - m], + [maxX + m, minZ - m], + [maxX + m, maxZ + m], + [minX - m, maxZ + m], + ] + return solids.reduce((total, solid) => { + // A pendant over the doorway is above the leaf. + if (solid.y0 >= keepout.height - 0.05) return total + const shared = area(intersection(solid.polygons, zone)) + return shared >= DOOR_KEEPOUT_MIN_AREA ? total + shared : total + }, 0) +} + +function clearZoneOf(keepout: DoorKeepout): DoorClearZone { + return { + box: roundBox(keepout.aabb), + alongWallM: roundMm(keepout.alongM), + depthM: { inward: roundMm(keepout.depthM.inward), outward: roundMm(keepout.depthM.outward) }, + } +} + +function sideOfWall(keepout: DoorKeepout, footprint: PlanAabb): DoorSide { + const across = + ((footprint.minX + footprint.maxX) / 2 - keepout.centre[0]) * keepout.normal[0] + + ((footprint.minZ + footprint.maxZ) / 2 - keepout.centre[1]) * keepout.normal[1] + return across >= 0 ? 'inward' : 'outward' +} + +function blockedDoorMessage( + keepout: DoorKeepout, + item: { name: string; id: string }, + facts: Pick, +): string { + const { side, clearZone, reading } = facts + const standing = + 'overlapAreaM2' in reading + ? `its shape covers ${metres(reading.overlapAreaM2)} m² of the door's clear zone` + : reading.overlapM > 0 + ? `its footprint stands ${metres(reading.overlapM)} m into the door's clear zone` + : `its footprint stands within the ${DOOR_KEEPOUT_MARGIN.toFixed(2)} m the check keeps clear of the door's clear zone` + const { box, alongWallM, depthM } = clearZone + const zone = `Clear zone: x ${metres(box.minX)}…${metres(box.maxX)}, z ${metres(box.minZ)}…${metres(box.maxZ)} (${alongWallM.toFixed(2)} m along the wall, ${depthM.inward.toFixed(2)} m deep inward and ${depthM.outward.toFixed(2)} m outward of the wall's centre line).` + const clear = 'clearBy' in reading ? ` Clear of it: ${describeMoves(reading.clearBy)}.` : '' + const kind = keepout.doorType ? `${keepout.doorType}, ` : '' + return `Door ${keepout.doorId} (${kind}${keepout.width.toFixed(2)} m wide) on wall ${keepout.wallId} is blocked by item ${item.name} (${item.id}): ${standing}, on the ${side} side of the wall. ${zone}${clear}` +} + +function doorBlockReading( + keepout: DoorKeepout, + footprint: PlanAabb, + solidsAreaM2?: number, +): DoorBlockReading { + if (solidsAreaM2 !== undefined) return { overlapAreaM2: roundMm(solidsAreaM2) } + const shared = axisOverlap(footprint, keepout.aabb) + return { + overlapM: Math.max(0, roundMm(Math.min(shared.x, shared.z))), + clearBy: clearingMoves(footprint, keepout.aabb, DOOR_KEEPOUT_MARGIN), + } +} + +/** A blocked door as the agent reads it: the item, how far it stands in the zone, the ways out, the zone. */ +function blockedDoorIssue( + keepout: DoorKeepout, + node: Extract, + footprint: PlanAabb, + levelId: string | null, + solidsAreaM2?: number, +): BlockedDoorIssue { + const name = node.name ?? node.asset?.name ?? node.id + const item = { name: typeof name === 'string' ? name : node.id, id: node.id } + const facts = { + side: sideOfWall(keepout, footprint), + clearZone: clearZoneOf(keepout), + reading: doorBlockReading(keepout, footprint, solidsAreaM2), + } + return { + doorId: keepout.doorId, + wallId: keepout.wallId, + itemId: node.id, + levelId, + itemName: item.name, + footprint: roundBox(footprint), + message: blockedDoorMessage(keepout, item, facts), + ...facts, + } } export function findBlockedDoors(args: { @@ -397,6 +570,13 @@ export function findBlockedDoors(args: { sidePad?: number /** When set, only doors and items on this level are considered. */ levelId?: string + /** + * An item's real shape, where the host chooses to read it (wall panelling): an item that has one + * blocks a door by what it is made of, not by the box round it. Items without it are read by their box. + */ + solidsOf?: (node: Extract) => readonly ItemSolid[] | null + /** An item's bottom and top in its level, where the host can read them better than the pose alone does. */ + heightsOf?: (node: Extract) => { min: number; max: number } | null }): BlockedDoorIssue[] { const nodes = [...args.nodes] const byId = new Map(nodes.map((n) => [n.id, n] as const)) @@ -418,24 +598,25 @@ export function findBlockedDoors(args: { const aabb = itemPlanAabbInLevel(node, byId) if (!aabb) continue - const heights = itemLevelHeightRange(node, byId) + const heights = args.heightsOf?.(node) ?? itemLevelHeightRange(node, byId) + const solids = args.solidsOf?.(node) ?? null - for (const keepout of keepouts) { + const vehicle = isVehicle(node) + for (const full of keepouts) { // Same-level only (multi-story safety). - if (keepout.levelId && itemLevel && keepout.levelId !== itemLevel) continue - if (args.levelId && keepout.levelId && keepout.levelId !== args.levelId) continue + if (full.levelId && itemLevel && full.levelId !== itemLevel) continue + if (args.levelId && full.levelId && full.levelId !== args.levelId) continue + const keepout = (vehicle && full.vehicleAperture) || full if (!itemBlocksDoorKeepout(aabb, keepout)) continue - // A pendant over the doorway is above the leaf. - if (heights && heights.min >= keepout.height - 0.05) continue - const itemName = node.name ?? node.asset?.name ?? node.id - issues.push({ - doorId: keepout.doorId, - wallId: keepout.wallId, - itemId: node.id, - levelId: itemLevel, - itemName: typeof itemName === 'string' ? itemName : undefined, - message: `Door ${keepout.doorId} on wall ${keepout.wallId} is blocked by item ${itemName} (${node.id})`, - }) + let solidsAreaM2: number | undefined + if (solids) { + solidsAreaM2 = solidsKeepoutArea(solids, keepout) + if (solidsAreaM2 === 0) continue + } else if (heights && heights.min >= keepout.height - 0.05) { + // A pendant over the doorway is above the leaf. + continue + } + issues.push(blockedDoorIssue(keepout, node, aabb, itemLevel, solidsAreaM2)) } } return issues diff --git a/packages/core/src/agent-operations/furniture-kind.ts b/packages/core/src/agent-operations/furniture-kind.ts index 7925de85db..c14e76eaf4 100644 --- a/packages/core/src/agent-operations/furniture-kind.ts +++ b/packages/core/src/agent-operations/furniture-kind.ts @@ -1,3 +1,4 @@ +import { foldRoomName } from '../building/room-use' 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. */ @@ -18,14 +19,40 @@ const FREE = /table|rug|carpet|plant|lamp|ottoman|pouf/ const WALL = /fridge|refrigerator|counter|kitchen|stove|oven|cooktop|sink|tv[ -]?(?:stand|unit)|television|dresser|wardrobe|closet|sofa|couch|loveseat|(?:^|[^a-z])bed(?![a-z])|toilet|bath|shower|bookcase|bookshelf|cabinet|washing|washer|dryer|coat/ -/** Only a named, flat floor covering is nonblocking, never an arbitrary short solid or low top surface. */ +/** What the catalogue (or the agent) filed a floor covering under, English or French, folded. */ +const RUG_CATEGORY = /^(?:rugs?|carpets?|tapis|(?:floor|parking)[ -]?mats?)$/ +/** The words that name one when the category says nothing: the asset's id and name, folded. */ +const RUG_WORD = /(?:^|[^a-z])(?:rugs?|carpets?|tapis|(?:floor|parking)[ -]?mats?)(?![a-z])/ + +/** What the catalogue (or the agent) filed a vehicle under, English or French, folded. */ +const VEHICLE_CATEGORY = /^(?:vehicles?|cars?|automobiles?|voitures?)$/ +/** The words that name one when the category says nothing: the asset's id and name, folded. */ +const VEHICLE_WORD = + /(?:^|[^a-z])(?:cars?|hatchbacks?|sedans?|suvs?|utes?|vehicles?|voitures?)(?![a-z])/ + +/** + * A car, a ute: filed as a vehicle, or named as one when nothing is filed. What stands in a garage + * to be driven out of it, so the garage door's opening is its way and not a thing it obstructs. + */ +export function isVehicle(item: ItemNode): boolean { + const category = foldRoomName(item.asset.category ?? '') + if (category) return VEHICLE_CATEGORY.test(category) + return VEHICLE_WORD.test(foldRoomName(read(item.asset))) +} + +/** + * Only a flat floor covering is nonblocking, never an arbitrary short solid or low top surface. It is + * 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 text = read(item.asset) + const category = foldRoomName(item.asset.category ?? '') + const filedAsRug = RUG_CATEGORY.test(category) + const text = foldRoomName(read(item.asset)) if ( - !/(?:^|[^a-z])(?:rug|carpet|(?:floor|parking)[ -]?mat)(?![a-z])/.test(text) || - WALL.test(text) || - CHAIR.test(text) || - /table|desk|ottoman|pouf/.test(text) || + !(filedAsRug || RUG_WORD.test(text)) || + (!filedAsRug && + (WALL.test(text) || CHAIR.test(text) || /table|desk|ottoman|pouf/.test(text))) || item.asset.attachTo ) return false @@ -52,6 +79,85 @@ export function isFloorUnderlay(item: ItemNode): boolean { ) } +/** What the catalogue (or the agent) files wall panelling and trim under, English or French, folded. */ +const WALL_DRESSING_CATEGORY = + /^(?:trim|paneling|panelling|wainscot(?:ing)?|boiseries?|(?:wall ?)?panels?|moulding|molding)$/ + +/** + * Wall panelling and trim are the wall's own surface: an item filed under them is read by its strips + * (its box is the room's) in a collision and in a door's clearance. A piece beside it keeps the gap + * it keeps from anything else. + */ +export function isWallDressing(item: ItemNode): boolean { + return WALL_DRESSING_CATEGORY.test(foldRoomName(item.asset.category ?? '')) +} + +/** The pieces that are designed to stand together, a few centimetres apart (see `designedTogether`). */ +type PairRole = 'bed' | 'bedside' | 'seat' | 'worktop' | 'sofa' | 'sidetable' + +/** What each role is filed under, folded, with hyphens as spaces: the category says it first. */ +const ROLE_CATEGORY: Record = { + bedside: /^(?:night ?stands?|bedside(?: tables?)?|night tables?|chevets?)$/, + bed: /^(?:(?:double|single|twin|king|queen|bunk|kids?) )?(?:beds?|lits?)$/, + seat: /^(?:(?:dining|desk|office|kitchen|bar|counter|outdoor|garden|terrace|work|accent) )?(?:chairs?|stools?)$|^(?:chaises?|tabourets?)$/, + worktop: + /^(?:desks?|bureaux?|(?:dining|kitchen|outdoor|garden|terrace|work|writing|office|meeting|conference|picnic) tables?)$/, + sofa: /^(?:(?:corner|sectional|leather|fabric) )?(?:sofas?|couch(?:es)?|loveseats?|canapes?)$/, + sidetable: /^(?:(?:side|end|accent|occasional|lamp) tables?|side|gueridons?)$/, +} + +/** A category that says nothing about what the piece is (or only "table"): its id and name decide. */ +const GENERIC_CATEGORY = + /^(?:furniture|furnishings?|other|misc\w*|custom|objects?|items?|home|interior|seating|tables?)?$/ + +/** The words that name each role, English or French, folded: only for a piece whose category does not. */ +const ROLE_WORDS: Record = { + bedside: /chevets?|bedside|night ?stands?|night tables?/, + bed: /(?:^|[^a-z])(?:beds?|lits?)(?![a-z])/, + seat: /(?:^|[^a-z])(?:chairs?|stools?|chaises?|tabourets?)(?![a-z])/, + worktop: /(?:^|[^a-z])(?:tables?|desks?|bureaux?)(?![a-z])/, + sofa: /(?:^|[^a-z])(?:sofas?|couch(?:es)?|canapes?|loveseats?)(?![a-z])/, + sidetable: /gueridons?|(?:side|end) tables?|bout de canape|d'appoint/, +} +/** "Bout de lit" is a bench, "coffee table" and "console" are not tables to sit at. */ +const ROLE_NOT: Partial> = { + bed: /(?:\bde|\bdu|\bof|\bfor|\bd') (?:beds?|lits?)\b/, + worktop: /basse|coffee|chevet|bedside|night|console|gueridon|appoint|side table|end table/, +} +const PAIR_ROLES: PairRole[] = ['bedside', 'bed', 'seat', 'sidetable', 'sofa', 'worktop'] + +function pairRole(item: ItemNode): PairRole | null { + const category = foldRoomName(item.asset.category ?? '').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)) + if (ARMCHAIR.test(text)) return null + return ( + PAIR_ROLES.find((role) => ROLE_WORDS[role].test(text) && !ROLE_NOT[role]?.test(text)) ?? null + ) +} + +const DESIGNED_PAIRS: readonly [PairRole, PairRole][] = [ + ['bed', 'bedside'], + ['seat', 'worktop'], + ['sofa', 'sidetable'], +] + +/** + * Whether two items are designed to stand together, a few centimetres apart: a nightstand beside a + * bed, a chair or stool at a desk or table, a sofa beside a side table. Such a pair being close is + * 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 { + const roles = [pairRole(a), pairRole(b)] + return DESIGNED_PAIRS.some( + ([first, second]) => + (roles[0] === first && roles[1] === second) || (roles[0] === second && roles[1] === first), + ) +} + /** * Wall-bound pieces (a fridge, a counter, a bed, a sofa) stand against a wall and never in the * middle of a room; free-standing ones (a dining table, a rug, a plant) may take the middle; a chair diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index d8ddb1039b..ff87e61a8e 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -65,6 +65,8 @@ export * from './furnish-room' export * from './get-node' export * from './hosted-services' export * from './layout-clearance' +// The door check that reads an item's real shape, not the plain one of door-clearance. +export { findBlockedDoors } from './layout-clearance' export * from './level-height-fill' export * from './level-reads' export * from './level-target' diff --git a/packages/core/src/agent-operations/item-solids.ts b/packages/core/src/agent-operations/item-solids.ts new file mode 100644 index 0000000000..9c8cb74b89 --- /dev/null +++ b/packages/core/src/agent-operations/item-solids.ts @@ -0,0 +1,176 @@ +import { + area, + difference, + intersection, + type MultiPolygon, + type Ring, + union, +} from '../lib/polygon-boolean' +import type { GeometryArtifactManifest } from '../schema' +import { distanceToSegment, type Vec2 } from './plan-geometry' + +/** + * The real shape of an item, for the plan checks that read wall panelling: the solids its script says + * it is made of, each a plan polygon between two heights, instead of the one box round its bounds. + * Other items stay their box, since the faces of a script leave out its rails, backs and foliage. A script reports its + * upward faces (`surfaces`, a height and an outline) and its downward faces (`undersides`); every + * upward face is the top of a solid that goes down to the highest downward face below it that + * overlaps it in plan, else to the bottom of the bounds, and a thing with only downward faces (a + * pendant's shade) hangs from the face to the top of its bounds. Legs without a face of their own + * are not modelled, which only ever leaves out matter, and a script with no faces has no solids. + */ + +export type ItemSolid = { polygons: MultiPolygon; y0: number; y1: number } + +/** A manifest point, mapped to the level's frame. */ +export type ToLevel = (point: [number, number, number]) => [number, number, number] + +/** A polygon thinner than this, on average (twice its area over its perimeter), is a sliver, not matter (m). */ +const MIN_MEAN_THICKNESS = 0.003 +/** A solid shorter than this is a face, not matter (m). */ +const MIN_HEIGHT = 1e-6 + +const close = (ring: Ring): Ring => (ring.length >= 3 ? ring : []) + +function ringArea(ring: Ring): number { + let sum = 0 + for (let i = 0; i < ring.length; i++) { + const [x0, z0] = ring[i]! + const [x1, z1] = ring[(i + 1) % ring.length]! + sum += x0 * z1 - x1 * z0 + } + return Math.abs(sum) / 2 +} + +function ringPerimeter(ring: Ring): number { + let sum = 0 + for (let i = 0; i < ring.length; i++) { + const [x0, z0] = ring[i]! + const [x1, z1] = ring[(i + 1) % ring.length]! + sum += Math.hypot(x1 - x0, z1 - z0) + } + return sum +} + +/** Whether a polygon is thick enough, on average, to be a solid and not a sliver of a boolean. */ +function solidEnough(polygon: MultiPolygon[number]): boolean { + const matter = ringArea(polygon.outer) - polygon.holes.reduce((t, ring) => t + ringArea(ring), 0) + const perimeter = + ringPerimeter(polygon.outer) + polygon.holes.reduce((t, r) => t + ringPerimeter(r), 0) + return perimeter > 0 && (2 * matter) / perimeter >= MIN_MEAN_THICKNESS +} + +/** The solids a manifest's faces describe, in the level's frame, or null when it reports none. */ +export function manifestSolids( + manifest: Pick, + toLevel: ToLevel, +): ItemSolid[] | null { + const ups = manifest.surfaces + .filter((face) => face.polygon.length >= 3) + .map((face) => ({ y: face.y, ring: face.polygon as Ring })) + // A downward face carries its plane [0, -1, 0, d]: -y + d = 0, so its height is d. A sloped one is not read. + const downs = manifest.undersides + .filter((face) => face.polygon.length >= 3 && Math.abs(face.plane[1] + 1) < 1e-6) + .map((face) => ({ y: face.plane[3], ring: face.polygon as Ring })) + if (!(ups.length || downs.length)) return null + const bottom = manifest.bounds.min[1] + const raw: { polygons: MultiPolygon; y0: number; y1: number }[] = [] + const solid = (polygons: MultiPolygon, y0: number, y1: number) => { + const kept = polygons.filter(solidEnough) + if (kept.length && y1 - y0 > MIN_HEIGHT) raw.push({ polygons: kept, y0, y1 }) + } + if (!ups.length) { + for (const down of downs) solid(union([close(down.ring)]), down.y, manifest.bounds.max[1]) + } + const byHeight = new Map() + for (const up of ups) { + const key = Math.round(up.y * 1e4) / 1e4 + byHeight.set(key, [...(byHeight.get(key) ?? []), up.ring]) + } + for (const [top, rings] of byHeight) { + let remaining = union(rings.map(close).filter((ring) => ring.length)) + const below = downs.filter((down) => down.y < top - 1e-6).sort((p, q) => q.y - p.y) + for (const down of below) { + if (!remaining.length) break + const piece = intersection(remaining, close(down.ring)) + if (area(piece) > 1e-8) { + solid(piece, down.y, top) + remaining = difference(remaining, close(down.ring)) + } + } + solid(remaining, bottom, top) + } + if (!raw.length) return null + const lift = (y: number) => toLevel([0, y, 0])[1] + return raw.map(({ polygons, y0, y1 }) => ({ + polygons: polygons.map(({ outer, holes }) => ({ + outer: outer.map(([x, z]) => planOf(toLevel([x, 0, z]))), + holes: holes.map((hole) => hole.map(([x, z]) => planOf(toLevel([x, 0, z])))), + })), + y0: lift(y0), + y1: lift(y1), + })) +} + +const planOf = (point: [number, number, number]): [number, number] => [point[0], point[2]] + +/** The least distance between two plan regions' outlines, 0 where they touch or cross. */ +function outlineDistance(a: MultiPolygon, b: MultiPolygon): number { + const rings = (region: MultiPolygon) => region.flatMap(({ outer, holes }) => [outer, ...holes]) + let least = Number.POSITIVE_INFINITY + const against = (from: Ring[], to: Ring[]) => { + for (const ring of from) + for (const point of ring) + for (const other of to) + for (let i = 0; i < other.length; i++) + least = Math.min( + least, + distanceToSegment( + point as Vec2, + other[i] as Vec2, + other[(i + 1) % other.length] as Vec2, + ), + ) + } + against(rings(a), rings(b)) + against(rings(b), rings(a)) + return least +} + +export type SolidsRelation = { + /** How deep the two reach into each other where they share height and plan, 0 when they do not. */ + overlapArea: number + /** The least plan distance between solids that share height; infinity when none do. */ + gap: number +} + +/** + * How two items' solids stand to each other. Two solids share height when they reach into each + * other by more than `stack` (a thing resting on another sinks a little into it): one that only + * rests on the other, or lies clear above or below it, is neither overlapping nor close. Plan + * overlap counts from `minArea` (square metres), which leaves a touching edge or a boolean's + * sliver out. + */ +export function relateSolids( + a: readonly ItemSolid[], + b: readonly ItemSolid[], + options: { stack: number; minArea: number }, +): SolidsRelation { + let overlapArea = 0 + let gap = Number.POSITIVE_INFINITY + for (const sa of a) { + for (const sb of b) { + if (Math.min(sa.y1, sb.y1) - Math.max(sa.y0, sb.y0) <= options.stack + 1e-9) continue + const shared = intersection(sa.polygons, sb.polygons) + const sharedArea = area(shared) + const enough = shared.some(solidEnough) && sharedArea >= options.minArea + if (enough) { + overlapArea += sharedArea + gap = 0 + } else { + gap = Math.min(gap, outlineDistance(sa.polygons, sb.polygons)) + } + } + } + return { overlapArea, gap } +} diff --git a/packages/core/src/agent-operations/layout-clearance.test.ts b/packages/core/src/agent-operations/layout-clearance.test.ts index a46cc60307..e2e4709eac 100644 --- a/packages/core/src/agent-operations/layout-clearance.test.ts +++ b/packages/core/src/agent-operations/layout-clearance.test.ts @@ -11,7 +11,6 @@ import { WindowNode, ZoneNode, } from '../schema' -import { CEILING_DRAW_OFFSET } from '../services' import { authoredItem } from './__fixtures__/add-object-cases' import savedWallScreen from './__fixtures__/wall-screen.json' import { @@ -749,19 +748,23 @@ describe('layout-clearance', () => { expect(findItemItemCollisions({ nodes })).toHaveLength(1) }) - test('following ceiling height and contact remain conservative', () => { + test('a pendant is read at the ceiling it follows: contact is touching, reaching into the furniture beyond what a model sinks is a collision', () => { const { level, ceiling, furniture, pendant } = verticalScene() const nodes = [level, ceiling, furniture, pendant] + // The table is 1 m tall and the pendant, 0.4 m tall, hangs 2 cm under the level's ceiling plane. delete ceiling.height expect(findItemItemCollisions({ nodes })).toEqual([]) - level.height = 1.4 - expect(findItemItemCollisions({ nodes })).toHaveLength(1) - ceiling.height = 1.4 + CEILING_DRAW_OFFSET + level.height = 1.3 expect(findItemItemCollisions({ nodes })).toHaveLength(1) - ceiling.height += 0.5e-6 + level.height = 1.38 expect(findItemItemCollisions({ nodes })).toHaveLength(1) - ceiling.height += 1e-4 + // The pendant's bottom at the table top, then within the 2 cm a model sinks: touching. + level.height = 1.42 expect(findItemItemCollisions({ nodes })).toEqual([]) + level.height = 1.4 + expect(findItemItemCollisions({ nodes })).toEqual([]) + ceiling.height = 1.38 + expect(findItemItemCollisions({ nodes })).toHaveLength(1) }) test('two catalogue recessed lights without raw bounds retain floor and ceiling warnings', () => { diff --git a/packages/core/src/agent-operations/layout-clearance.ts b/packages/core/src/agent-operations/layout-clearance.ts index ab6488be12..d7ad9b8121 100644 --- a/packages/core/src/agent-operations/layout-clearance.ts +++ b/packages/core/src/agent-operations/layout-clearance.ts @@ -25,20 +25,34 @@ import { resolveCeilingHeight } from '../services/level-height' import { CEILING_DRAW_OFFSET } from '../services/storey' import { aabbsOverlap, - findBlockedDoors, + type BlockedDoorIssue, + type DoorBlockReading, + type DoorClearZone, + type DoorSide, + findBlockedDoors as findBlockedDoorsByBox, itemNodePlanAabb, + itemNodePlanCorners, itemPlanAabb, type PlanAabb, resolveNodeLevelId, } from './door-clearance' -import { furnitureKind, isFloorUnderlay } from './furniture-kind' -import { itemHosts, itemLevelHeightRange, itemPlanAabbInLevel } from './item-space' -import { pointInPolygon, type Vec2 } from './plan-geometry' +import { designedTogether, furnitureKind, isFloorUnderlay, isWallDressing } from './furniture-kind' +import { type ItemSolid, manifestSolids, relateSolids, type ToLevel } from './item-solids' +import { itemLevelHeightRange, itemLevelPose, itemPlanAabbInLevel } from './item-space' +import { + axisOverlap, + type ClearMove, + clearingMoves, + describeMoves, + metres, + roundBox, + roundMm, +} from './plan-clearance' +import { distanceToSegment, pointInPolygon, type Vec2 } from './plan-geometry' export { aabbsOverlap, collectDoorKeepouts, - findBlockedDoors, itemNodePlanAabb, itemPlanAabb, type PlanAabb, @@ -57,6 +71,17 @@ export type OccupiedFootprint = { aabb: PlanAabb } +/** + * How far two items stand in or from each other. Boxes: the depth along the shallower axis and + * along each, or the gap, with the moves of `a` that leave the clearance. Real shapes (wall + * panelling): the area they share, or the plan gap between them, and no moves. + */ +export type ItemPairReading = + | { overlapM: number; overlapAlongM: { x: number; z: number }; clearBy: ClearMove[] } + | { gapM: number; clearBy: ClearMove[] } + | { overlapAreaM2: number } + | { gapM: number } + export type ItemCollision = { aId: string bId: string @@ -66,9 +91,51 @@ export type ItemCollision = { kind: 'item-aabb' violation: 'overlap' | 'clearance' minimumClearanceMeters: number + /** Of a and of b: the boxes the check reads. */ + footprints: [PlanAabb, PlanAabb] + reading: ItemPairReading message: string } +function boxReading(a: PlanAabb, b: PlanAabb, gap: number): ItemPairReading { + const shared = axisOverlap(a, b) + const depth = Math.min(shared.x, shared.z) + const clearBy = clearingMoves(a, b, gap) + return depth > 0 + ? { + overlapM: roundMm(depth), + overlapAlongM: { x: roundMm(shared.x), z: roundMm(shared.z) }, + clearBy, + } + : { gapM: roundMm(-depth), clearBy } +} + +function collisionMessage( + violation: ItemCollision['violation'], + gap: number, + [a, b]: [{ id: string; name?: string }, { id: string; name?: string }], + reading: ItemPairReading, +): string { + const [first, second] = [a.name ?? a.id, b.name ?? b.id] + const pair = `${first} (${a.id}) and ${second} (${b.id})` + const how = + 'overlapAreaM2' in reading + ? `share ${metres(reading.overlapAreaM2)} m²` + : 'overlapAlongM' in reading + ? `by ${metres(reading.overlapAlongM.x)} m along x and ${metres(reading.overlapAlongM.z)} m along z` + : `are ${metres(reading.gapM)} m apart` + const lead = + violation === 'overlap' + ? `Items overlap: ${pair} ${how}` + : `Items are closer than ${gap} m: ${pair} ${how}` + const shapes = 'clearBy' in reading ? 'footprint boxes' : 'real shapes' + const moves = + 'clearBy' in reading + ? ` ${first} is ${gap} m clear of ${second}, the gap the check keeps, after ${describeMoves(reading.clearBy)}.` + : '' + return `${lead} (${shapes}).${moves}` +} + export function nodeItemAabb(node: AnyNode): PlanAabb | null { return itemNodePlanAabb(node) } @@ -237,6 +304,42 @@ export function scriptItemBoundsInLevel( } } +/** + * Where a script item's own model space stands in its level: maps a point of its manifest (its + * bounds, parts, surfaces) to the level's frame, through the corrective asset pose and the item's + * node pose the renderer applies. Undefined where the bounds cannot be resolved. + */ +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)) + return (point) => + corrected(point).map((value, axis) => value + shift[axis]!) as [number, number, number] +} + function itemVerticalInterval( node: AnyNode | undefined, nodes: Record, @@ -257,6 +360,136 @@ function itemVerticalInterval( } } +/** + * 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 { + const manifest = node.source?.manifest + if ( + !manifest || + manifest.animations?.length || + !planarRotation(node.rotation) || + !planarRotation(node.asset.rotation) + ) + return null + const direct = scriptItemToLevel(node, nodes) + const toLevel = direct ?? hostedToLevel(node, nodes) + if (!toLevel) return null + try { + const solids = manifestSolids(manifest, toLevel) + return solids?.every((solid) => Number.isFinite(solid.y0) && Number.isFinite(solid.y1)) + ? solids + : null + } catch { + // A malformed outline is not evidence of separation: the box reads instead. + return null + } +} + +/** 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], + ] + } +} + +/** + * Doors blocked by furniture. An item is its box, as tall as its heights say (a pendant over the door + * is above its leaf); wall panelling alone is its real strips (see `findItemItemCollisions`). + */ +export function findBlockedDoors( + args: Parameters[0], +): BlockedDoorIssue[] { + const list = [...args.nodes] + const nodes = Object.fromEntries(list.map((node) => [node.id, node])) + const byId = new Map(list.map((node) => [node.id, node])) + const finite = list.every((node) => node.type === 'item' || finiteNumbers(node)) + return findBlockedDoorsByBox({ + ...args, + nodes: list, + solidsOf: (node) => (finite && isWallDressing(node) ? itemSolidsInLevel(node, nodes) : null), + heightsOf: (node) => itemHeightsInLevel(node, nodes, byId, finite) ?? null, + }) +} + +/** Plan overlap, in square metres, from which two real shapes are overlapping: a touching edge or a boolean's sliver is not. */ +export const MIN_OVERLAP_AREA = 0.001 + +/** + * An item's bottom and top in the level's frame, as the renderer stands it: the model's own bounds + * through the floor construction under it (measured) or, where it has none, its pose and its height + * 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. + */ +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 + 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 } + : 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 + export function findItemItemCollisions(args: { nodes: Iterable levelId?: string @@ -269,54 +502,77 @@ export function findItemItemCollisions(args: { // Drawing fallbacks on invalid support heights cannot prove collision separation. const finiteContext = list.every((node) => node.type === 'item' || finiteNumbers(node)) const byId = new Map(list.map((node) => [node.id, node])) - // The measured interval when the model's bounds allow it, else the node's own height above its - // floor. A measured contact stays a collision (roundoff); a lamp standing on a table top by its - // own height is stacked. - const intervals = new Map( - footprints.map(({ id }) => { - const node = nodes[id] as ItemNode - const measured = finiteContext ? itemVerticalInterval(node, nodes) : undefined - if (measured) return [id, { ...measured, measured: true }] - const range = itemLevelHeightRange(node, byId) - return [ - id, - range - ? { - levelId: resolveNodeLevelId(id, byId) ?? '', - min: range.min, - max: range.max, - measured: false, - } - : undefined, - ] - }), - ) - const hosts = new Map(footprints.map(({ id }) => [id, itemHosts(nodes[id]!, byId)])) + const heights = new Map() + for (const { id } of footprints) + heights.set(id, itemHeightsInLevel(nodes[id] as ItemNode, nodes, byId, finiteContext)) + // 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) + return solids.get(id) ?? null + } + 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, + }, + ] + } const collisions: ItemCollision[] = [] for (let i = 0; i < footprints.length; i++) { 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 - // A thing resting on top of its host is stacked by design: its bottom at the host's top. A - // child sunk into its host, or one whose height is unknown, is still a collision. - const [child, host] = hosts.get(a.id)?.has(b.id) - ? [a, b] - : hosts.get(b.id)?.has(a.id) - ? [b, a] - : [] - if (child && host) { - const cY = intervals.get(child.id) - const hY = intervals.get(host.id) - if (cY && hY && cY.min >= hY.max - 0.02) continue - } if (!aabbsOverlap(a.aabb, b.aabb, gap)) continue - const aY = intervals.get(a.id) - const bY = intervals.get(b.id) - // Contact and sub-micrometre separation remain conservative against roundoff. - if (aY && bY && aY.levelId === bY.levelId) { - const touch = aY.measured && bY.measured ? 1e-6 : -1e-6 - if (bY.min - aY.max > touch || aY.min - bY.max > touch) 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) + ) + continue + violation = aabbsOverlap(a.aabb, b.aabb, 0) ? 'overlap' : 'clearance' + reading = boxReading(a.aabb, b.aabb, gap) } collisions.push({ aId: a.id, @@ -325,11 +581,11 @@ export function findItemItemCollisions(args: { bName: b.name, levelId: a.levelId ?? b.levelId, kind: 'item-aabb', - violation: aabbsOverlap(a.aabb, b.aabb, 0) ? 'overlap' : 'clearance', + violation, minimumClearanceMeters: gap, - message: aabbsOverlap(a.aabb, b.aabb, 0) - ? `Items overlap: ${a.name ?? a.id} (${a.id}) and ${b.name ?? b.id} (${b.id})` - : `Items are closer than ${gap} m: ${a.name ?? a.id} (${a.id}) and ${b.name ?? b.id} (${b.id})`, + footprints: [roundBox(a.aabb), roundBox(b.aabb)], + reading, + message: collisionMessage(violation, gap, [a, b], reading), }) } } @@ -530,17 +786,6 @@ const DEFAULT_WALL_THICKNESS_M = 0.1 const cross = (o: Vec2, p: Vec2, q: Vec2) => (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]) -function distanceToSegment(point: Vec2, a: Vec2, b: Vec2) { - const dx = b[0] - a[0] - const dz = b[1] - a[1] - const length2 = dx * dx + dz * dz - const t = - length2 === 0 - ? 0 - : Math.max(0, Math.min(1, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dz) / length2)) - return Math.hypot(point[0] - (a[0] + t * dx), point[1] - (a[1] + t * dz)) -} - /** The shortest distance from a footprint box to a wall's centre line (0 when the line passes through it). */ function boxToSegment(box: PlanAabb, a: Vec2, b: Vec2) { const corners: Vec2[] = [ @@ -568,7 +813,9 @@ function boxToSegment(box: PlanAabb, a: Vec2, b: Vec2) { /** A wall as the mid-room check reads it: its centre line and half its thickness. */ export type WallFace = { a: Vec2; b: Vec2; halfThickness: number } -/** The walls of a level (resolved through `byId`), as the mid-room check reads them. */ +/** + * The walls of a level (resolved through `byId`), as the mid-room check reads them: its wall nodes. + */ export function wallFacesOn( nodes: Iterable, levelId: string | undefined, @@ -576,12 +823,13 @@ export function wallFacesOn( ): WallFace[] { const walls: WallFace[] = [] for (const node of nodes) { - if (node.type !== 'wall' || resolveNodeLevelId(node.id, byId) !== levelId) continue - walls.push({ - a: [node.start[0], node.start[1]], - b: [node.end[0], node.end[1]], - halfThickness: (node.thickness ?? DEFAULT_WALL_THICKNESS_M) / 2, - }) + if (resolveNodeLevelId(node.id, byId) !== levelId) continue + if (node.type === 'wall') + walls.push({ + a: [node.start[0], node.start[1]], + b: [node.end[0], node.end[1]], + halfThickness: (node.thickness ?? DEFAULT_WALL_THICKNESS_M) / 2, + }) } return walls } @@ -596,8 +844,10 @@ export function gapToWalls(box: PlanAabb, walls: readonly WallFace[]): number { /** * Wall-bound pieces (a fridge, a counter, a bed, a sofa) that stand in a room but away from every - * wall: further than {@link MID_ROOM_DISTANCE_M} from the face of each wall of their level. Pieces - * outside every room, free-standing kinds, and levels with no walls are not judged. + * wall: further than {@link MID_ROOM_DISTANCE_M} from the face of each wall of their level. A roof + * on the level stands walls of its own (knee walls, gable ends) where no wall node does, so a loft + * bounded by its roof is measured to them. Pieces outside every room, free-standing kinds, and + * levels with neither walls nor a roof shell are not judged. */ export function findItemsMidRoom(args: { nodes: Iterable; levelId?: string }): { id: string @@ -633,13 +883,28 @@ export function findItemsMidRoom(args: { nodes: Iterable; levelId?: str return found } +type LayoutFinding = { message: string; nodeIds: string[] } + +export type LayoutIssue = + | (LayoutFinding & + DoorBlockReading & { + type: 'door_blocked' + obstacle: { nodeId: string; name?: string; footprint: PlanAabb; side: DoorSide } + clearZone: DoorClearZone + }) + | (LayoutFinding & + ItemPairReading & { + type: 'item_overlap' | 'item_too_close' + footprints: [PlanAabb, PlanAabb] + minimumClearanceMeters: number + }) + | (LayoutFinding & { type: 'item_mid_room' }) + /** - * Collect layout issues, scoped per level so stacked floors do not false-positive. + * Collect layout issues, scoped per level so stacked floors do not false-positive. A blocked door and + * a pair of items carry the numbers of the finding: what stands where, how deep, and the way clear. */ -export function layoutIssuesFromScene(nodes: Iterable): { - type: 'door_blocked' | 'item_overlap' | 'item_too_close' | 'item_mid_room' - message: string -}[] { +export function layoutIssuesFromScene(nodes: Iterable): LayoutIssue[] { const list = [...nodes] const byId = new Map(list.map((n) => [n.id, n] as const)) const levelIds = new Set() @@ -652,24 +917,45 @@ export function layoutIssuesFromScene(nodes: Iterable): { if (lid) levelIds.add(lid) } - const issues = new Map< - string, - 'door_blocked' | 'item_overlap' | 'item_too_close' | 'item_mid_room' - >() + const issues = new Map() const levels = levelIds.size > 0 ? [...levelIds] : [undefined] + const itemById = new Map(list.map((n) => [n.id, n])) for (const levelId of levels) { for (const b of findBlockedDoors({ nodes: list, levelId })) { - issues.set(b.message, 'door_blocked') + issues.set(b.message, { + type: 'door_blocked', + message: b.message, + nodeIds: [b.doorId, b.itemId, b.wallId], + obstacle: { nodeId: b.itemId, name: b.itemName, footprint: b.footprint, side: b.side }, + clearZone: b.clearZone, + ...b.reading, + }) } for (const c of findItemItemCollisions({ nodes: list, levelId })) { - issues.set(c.message, c.violation === 'overlap' ? 'item_overlap' : 'item_too_close') + // Close is the design for a nightstand beside its bed, a chair at its table: not a finding. + const [a, b] = [itemById.get(c.aId), itemById.get(c.bId)] + if ( + c.violation === 'clearance' && + a?.type === 'item' && + b?.type === 'item' && + designedTogether(a, b) + ) + continue + issues.set(c.message, { + type: c.violation === 'overlap' ? 'item_overlap' : 'item_too_close', + message: c.message, + nodeIds: [c.aId, c.bId], + footprints: c.footprints, + minimumClearanceMeters: c.minimumClearanceMeters, + ...c.reading, + }) } for (const m of findItemsMidRoom({ nodes: list, levelId })) { - issues.set(m.message, 'item_mid_room') + issues.set(m.message, { type: 'item_mid_room', message: m.message, nodeIds: [m.id] }) } } // Deduplicate (node may appear under multiple walks) - return [...issues].map(([message, type]) => ({ type, message })) + return [...issues.values()] } diff --git a/packages/core/src/agent-operations/plan-clearance.ts b/packages/core/src/agent-operations/plan-clearance.ts new file mode 100644 index 0000000000..6604ad4dc1 --- /dev/null +++ b/packages/core/src/agent-operations/plan-clearance.ts @@ -0,0 +1,62 @@ +import type { PlanAabb } from './door-clearance' + +/** The direction of a move in the plan, along the scene's x or z axis. */ +export type ClearDirection = '+x' | '-x' | '+z' | '-z' + +export type ClearMove = { direction: ClearDirection; distanceM: number } + +const MM_PER_M = 1000 + +/** A length in metres, to the millimetre. */ +export const roundMm = (value: number) => Math.round(value * MM_PER_M) / MM_PER_M + +/** A length as the findings say it, to the millimetre. */ +export const metres = (value: number) => value.toFixed(3) + +/** Moves as the findings say them: "0.295 m toward -x or 0.620 m toward -z". */ +export const describeMoves = (moves: readonly ClearMove[]) => + moves.map((move) => `${metres(move.distanceM)} m toward ${move.direction}`).join(' or ') + +export const roundBox = (box: PlanAabb): PlanAabb => ({ + minX: roundMm(box.minX), + maxX: roundMm(box.maxX), + minZ: roundMm(box.minZ), + maxZ: roundMm(box.maxZ), +}) + +/** Up to the millimetre, so a move of the stated length clears; the sliver below is float noise. */ +const ceilMm = (value: number) => Math.ceil(value * MM_PER_M - 1e-9) / MM_PER_M + +/** + * How far two boxes share each plan axis: the length of the shared stretch, or minus the gap where + * they are apart along it. + */ +export function axisOverlap(a: PlanAabb, b: PlanAabb): { x: number; z: number } { + return { + x: Math.min(a.maxX, b.maxX) - Math.max(a.minX, b.minX), + z: Math.min(a.maxZ, b.maxZ) - Math.max(a.minZ, b.minZ), + } +} + +/** + * The moves of `a` that leave `margin` between it and `b`: the nearer way out on each axis, away + * from the other box's middle, shortest first. A box already clear by the margin has none. + */ +export function clearingMoves(a: PlanAabb, b: PlanAabb, margin: number): ClearMove[] { + const awayX = a.minX + a.maxX >= b.minX + b.maxX + const awayZ = a.minZ + a.maxZ >= b.minZ + b.maxZ + const moves: ClearMove[] = [ + { + direction: awayX ? '+x' : '-x', + distanceM: awayX ? margin + b.maxX - a.minX : margin + a.maxX - b.minX, + }, + { + direction: awayZ ? '+z' : '-z', + distanceM: awayZ ? margin + b.maxZ - a.minZ : margin + a.maxZ - b.minZ, + }, + ] + return moves + .filter((move) => move.distanceM > 0) + .map((move) => ({ ...move, distanceM: ceilMm(move.distanceM) })) + .sort((first, second) => first.distanceM - second.distanceM) +} diff --git a/packages/core/src/lib/door-operation.ts b/packages/core/src/lib/door-operation.ts index cdfb93da0d..5e6756471e 100644 --- a/packages/core/src/lib/door-operation.ts +++ b/packages/core/src/lib/door-operation.ts @@ -20,6 +20,13 @@ export function isOperationDoorType( ) } +/** A door a vehicle drives through: it has no leaf to swing across the floor. */ +export function isVehicleDoorType(doorType: DoorType | DoorNode['doorType'] | string | undefined) { + return ( + doorType === 'garage-sectional' || doorType === 'garage-rollup' || doorType === 'garage-tiltup' + ) +} + export function getDoorRenderOpenAmount( doorType: DoorType | DoorNode['doorType'], operationState: number | undefined, From 64c82ab9285e0c350b655a2cc5d6cf48ad7626bf Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 17:21:11 +0100 Subject: [PATCH 07/40] verify_scene names a room no walk from outside reaches room_unreachable: a room, zone or open floor that no walk from outside reaches through the doors, openings, open edges, stairs and lifts the scene models. The circulation graph's reachability read (`reachability.ts`) already says it; this registers it as a verify_scene check, a warning with the room's level, and keeps the rest of what that read says out: a room whose route crosses walking geometry the reading cannot measure is not named (its access is unknown, not missing), and the storey and stair facts stay with their own checks. Rule tests: a room behind a partition with no door is named, a door makes it reachable, and verify_scene carries it only when it is not. Co-Authored-By: Claude Sonnet 5.5 --- .../agent-operations/circulation-geometry.ts | 195 ++++++++++++ packages/core/src/agent-operations/index.ts | 1 + .../core/src/agent-operations/reachability.ts | 284 ++++++++++++++++++ .../unreachable-rooms-check.test.ts | 101 +++++++ .../unreachable-rooms-check.ts | 48 +++ .../core/src/agent-operations/verify-scene.ts | 2 + 6 files changed, 631 insertions(+) create mode 100644 packages/core/src/agent-operations/circulation-geometry.ts create mode 100644 packages/core/src/agent-operations/reachability.ts create mode 100644 packages/core/src/agent-operations/unreachable-rooms-check.test.ts create mode 100644 packages/core/src/agent-operations/unreachable-rooms-check.ts diff --git a/packages/core/src/agent-operations/circulation-geometry.ts b/packages/core/src/agent-operations/circulation-geometry.ts new file mode 100644 index 0000000000..cd606c9261 --- /dev/null +++ b/packages/core/src/agent-operations/circulation-geometry.ts @@ -0,0 +1,195 @@ +import { resolveLevelId } from '../lib/node-ancestry' +import { area, containsPoint, intersection } from '../lib/polygon-boolean' +import { buildCirculationGraph, type CirculationGraph } from './circulation-graph' +import { spaceRegion } from './circulation-spaces' +import type { SceneNodes } from './types' + +export type CirculationGeometryReason = { + code: string + message: string + nodeIds: string[] +} + +type AddReason = (code: string, ...ids: string[]) => void + +function floorReasons(scene: SceneNodes, graph: CirculationGraph, add: AddReason) { + for (const floor of graph.floors) { + for (const slab of floor.slabs) { + const source = scene[slab.id] + if (source?.type !== 'slab') continue + // An open-supported floor outside the enclosed footprint on the ground is outdoor ground. + if (source.support === 'open') { + if (!slab.outdoor) add('open_supported_floors', slab.id) + } else if ( + !slab.outdoor && + Math.abs(slab.elevation - floor.elevation) > 1e-6 && + (!floor.interior.length || + area(intersection({ outer: slab.polygon, holes: slab.holes }, floor.interior)) > 1e-6) + ) + add('split_interior_floors', slab.id) + } + for (const zone of floor.zones) { + const source = scene[zone.id] + if (source?.type !== 'zone') continue + if (zone.outdoor) { + const regions = floor.pockets.flatMap((pocket) => + intersection({ outer: zone.polygon, holes: zone.holes }, pocket.polygon), + ) + if (regions.length > 1) add('divided_outdoor_spaces', zone.id) + } + if (source.floor?.support === 'open' && !zone.outdoor) add('open_supported_floors', zone.id) + else if (zone.outdoor) continue + else if (source.hasFloor === false) + add(floor.ground ? 'floorless_interior_spaces' : 'floorless_upper_spaces', zone.id) + else if ( + source.floor?.elevation !== undefined && + Math.abs(floor.groundElevation + source.floor.elevation - floor.elevation) > 1e-6 + ) + add('split_interior_floors', zone.id) + } + } +} + +function geometryGroups(scene: SceneNodes, graph: CirculationGraph) { + const groups = new Map>() + const add = (code: string, ...ids: string[]) => { + const group = groups.get(code) ?? new Set() + for (const id of ids) group.add(id) + groups.set(code, group) + } + const buildings = Object.values(scene).filter((node) => node.type === 'building') + if (buildings.length > 1) add('multiple_buildings', ...buildings.map((node) => node.id)) + for (const node of buildings) + if (Math.abs(node.rotation[0]) > 1e-8 || Math.abs(node.rotation[2]) > 1e-8) + add('tilted_buildings', node.id) + floorReasons(scene, graph, add) + if (!graph.floors.some((floor) => floor.slabs.length)) { + const inhabited = graph.floors.filter((floor) => floor.zones.length || floor.pockets.length) + if (inhabited.length) add('floor_missing', ...inhabited.map((floor) => floor.id)) + } + for (const node of Object.values(scene)) { + if (node.type !== 'stair') continue + const host = scene[node.supportSlabId ?? ''] + const floor = graph.floors.find( + (candidate) => candidate.id === (node.fromLevelId ?? resolveLevelId(node, scene)), + ) + const surface = floor?.slabs.find((slab) => slab.id === host?.id) + const raisedHost = + host?.type === 'slab' && + (host.support === 'open' || + (surface && + !surface.outdoor && + Math.abs(surface.elevation - (floor?.elevation ?? 0)) > 1e-6)) + const measuredEntrySteps = + graph.entranceFlights.has(node.id) || + (floor?.ground && + !node.toLevelId && + graph.edges.some((edge) => edge.kind === 'stair' && edge.sourceId === node.id)) + if (!measuredEntrySteps && (node.deckSlabId || Math.abs(node.position[1]) > 1e-6 || raisedHost)) + add('deck_stairs', node.id) + } + for (const id of graph.unsupportedIds) { + const node = scene[id] + add( + node?.type === 'stair' + ? 'incomplete_stairs' + : node?.type === 'door' + ? 'unhosted_doors' + : 'disconnected_surfaces', + id, + ) + } + return groups +} + +const REASONS: Record string> = { + multiple_buildings: (n) => `${n} buildings have separate circulation frames`, + tilted_buildings: (n) => + `${n} tilted building${n === 1 ? ' has' : 's have'} non-horizontal walking planes`, + split_interior_floors: (n) => + `${n} interior floor element${n === 1 ? ' has a different walking height' : 's have different walking heights'} on the same level`, + open_supported_floors: (n) => + `${n} open-supported floor element${n === 1 ? ' forms' : 's form'} stacked walking planes`, + floorless_upper_spaces: (n) => + `${n} upper-level space${n === 1 ? ' has' : 's have'} no walking floor`, + floorless_interior_spaces: (n) => + `${n} interior space${n === 1 ? ' has' : 's have'} no walking floor`, + deck_stairs: (n) => + `${n} stair or deck connection${n === 1 ? '' : 's'} cannot be measured between their walking surfaces`, + incomplete_stairs: (n) => + `${n} stair${n === 1 ? ' has' : 's have'} an incomplete walking path or a missing destination floor`, + unhosted_doors: (n) => `${n} door${n === 1 ? ' has' : 's have'} no wall host`, + disconnected_surfaces: (n) => + `${n} floor surface${n === 1 ? ' is' : 's are'} split into disconnected walking regions`, + floor_missing: (n) => `${n} inhabited level${n === 1 ? ' has' : 's have'} no floor slabs`, + divided_outdoor_spaces: (n) => + `${n} outdoor space${n === 1 ? ' spans' : 's span'} disconnected or wall-separated walking regions`, +} + +/** The same named measurement limits for the Flow note and agent diagnostics. */ +export function circulationGeometryReasons( + scene: SceneNodes, + graph: CirculationGraph = buildCirculationGraph(scene), +): CirculationGeometryReason[] { + return [...geometryGroups(scene, graph)].map(([code, ids]) => { + const nodeIds = [...ids] + return { + code, + nodeIds, + message: `${REASONS[code]?.(nodeIds.length) ?? `${nodeIds.length} unsupported elements`}: ${nodeIds + .map((id) => scene[id]?.name ?? `Unnamed ${scene[id]?.type ?? 'element'}`) + .join(', ')}.`, + } + }) +} + +/** Losing a route while excluding geometry is missing coverage, not proof of disconnection. */ +export function unmeasuredRouteIds( + rawReachable: Iterable, + measuredReachable: Iterable, +): Set { + const measured = new Set(measuredReachable) + return new Set([...rawReachable].filter((id) => !measured.has(id))) +} + +/** Exclude uncertain spaces and connectors, not unrelated measured routes. */ +export function measuredCirculationGraph( + scene: SceneNodes, + graph: CirculationGraph, + reasons: CirculationGeometryReason[], +): CirculationGraph { + const unsupported = new Set(reasons.flatMap((reason) => reason.nodeIds)) + const surfaces = [...unsupported].flatMap((id) => { + const node = scene[id] + return node?.type === 'slab' || node?.type === 'zone' ? [node] : [] + }) + const nodes = new Map( + [...graph.nodes].filter(([, node]) => { + if (node.sourceId && unsupported.has(node.sourceId)) return false + return !surfaces.some((surface) => { + if (resolveLevelId(surface, scene) !== node.levelId) return false + const region = spaceRegion(scene, graph, node) + if (region) + return ( + area(intersection(region, { outer: surface.polygon, holes: surface.holes ?? [] })) > + 1e-6 + ) + return containsPoint( + [{ outer: surface.polygon, holes: surface.holes ?? [] }], + [node.position[0], node.position[2]], + ) + }) + }), + ) + const edges = graph.edges.filter( + (edge) => + nodes.has(edge.from) && + nodes.has(edge.to) && + (!edge.sourceId || !unsupported.has(edge.sourceId)), + ) + return { + ...graph, + nodes, + edges, + } +} diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index ff87e61a8e..281f8ac921 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -37,6 +37,7 @@ import { createUnit, listUnits, setUnitMembers } from './units' import { verifyScene } from './verify-scene' import { setWallType } from './wall-type' import './room-checks' +import './unreachable-rooms-check' import './usage-checks' export * from './achieved' diff --git a/packages/core/src/agent-operations/reachability.ts b/packages/core/src/agent-operations/reachability.ts new file mode 100644 index 0000000000..022bfd0b98 --- /dev/null +++ b/packages/core/src/agent-operations/reachability.ts @@ -0,0 +1,284 @@ +import { resolveBuildingForLevel, resolveLevelId } from '../lib/node-ancestry' +import type { AnyNode, AnyNodeId, UnitNode } from '../schema' +import { getLevelAbove } from '../services/storey' +import { + type CirculationGeometryReason, + circulationGeometryReasons, + measuredCirculationGraph, + unmeasuredRouteIds, +} from './circulation-geometry' +import { + buildCirculationGraph, + type CirculationGraph, + type CirculationIssue, + type CirculationNode, + circulationLinks, + exteriorEntranceEdges, + nodeName, + reachedFrom, +} from './circulation-graph' +import { queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +export { floorSpaceReader, type Space, wallSidesReader } from './circulation-spaces' + +const listed = (names: string[]) => + names.length > 8 + ? `${names.slice(0, 8).join(', ')} and ${names.length - 8} more` + : names.join(', ') + +function apartmentIssues( + nodes: SceneNodes, + graph: CirculationGraph, + entrance: boolean, + rawGraph: CirculationGraph, + cutOff: ReadonlySet, +): CirculationIssue[] { + const links = circulationLinks(graph) + const groundIds = new Set( + graph.floors.filter((floor) => floor.ground).map((floor) => floor.id), + ) + const starts = entrance + ? ['outside'] + : [...graph.nodes.values()] + .filter((node) => node.levelId && groundIds.has(node.levelId) && !node.apartment) + .map((node) => node.id) + const everywhere = reachedFrom(links, starts) + const shared = reachedFrom(links, starts, (id) => !graph.nodes.get(id)?.apartment) + const rawLinks = circulationLinks(rawGraph) + const unmeasured = unmeasuredRouteIds(reachedFrom(rawLinks, starts), everywhere) + const unmeasuredShared = unmeasuredRouteIds( + reachedFrom(rawLinks, starts, (id) => !rawGraph.nodes.get(id)?.apartment), + shared, + ) + const unreachable: string[] = [], + through: string[] = [] + for (const unit of queryNodes(nodes, { type: 'unit' })) { + if ((unit.kind ?? 'apartment') !== 'apartment') continue + const keys = [...graph.nodes.values()] + .filter((node) => node.apartment === unit.id) + .map((node) => node.id) + if (!keys.length) continue + if (!keys.some((id) => everywhere.has(id))) { + const onCutOffLevels = keys.every((id) => cutOff.has(graph.nodes.get(id)?.levelId ?? '')) + if (!(onCutOffLevels || keys.some((id) => unmeasured.has(id)))) unreachable.push(unit.id) + } else if (!keys.some((id) => shared.has(id) || unmeasuredShared.has(id))) through.push(unit.id) + } + const issues: CirculationIssue[] = [] + if (unreachable.length) + issues.push({ + type: 'apartment_unreachable', + message: `${unreachable.length} apartment${unreachable.length === 1 ? '' : 's'} cannot be reached from ${entrance ? 'the entrance' : "the ground floor's corridors"}: ${listed(unreachable.map((id) => nodeName(nodes, id)))}.`, + nodeIds: unreachable, + }) + if (through.length) + issues.push({ + type: 'reached_through_apartment', + message: `${through.length} apartment${through.length === 1 ? ' is' : 's are'} reached only by crossing another apartment: ${listed(through.map((id) => nodeName(nodes, id)))}.`, + nodeIds: through, + }) + return issues +} + +/** Why a level is or is not reached from an entrance; null when it is. */ +export type CirculationLevelReason = 'no_connection' | 'no_landing' | 'no_entrance' | 'not_measured' + +/** Whether a level can be reached from an entrance: true, false, or null where it cannot be measured. */ +export type CirculationLevel = { + levelId: string + name: string + buildingId: string | null + reachable: boolean | null + reason: CirculationLevelReason | null + spaces: number + reachedSpaces: number +} + +export type CirculationReach = { + /** The graph the reading measures: raw, or without the geometry that cannot be measured. */ + graph: CirculationGraph + geometry: CirculationGeometryReason[] + /** A multiple-building, tilted or floorless scene has no frame to measure a route in. */ + frameLimited: boolean + entrance: boolean + reached: Set + /** Graph nodes whose route is not measurable: neither reached nor proven cut off. */ + unmeasured: Set + /** Per level that holds a space to reach. */ + levels: CirculationLevel[] + /** Level ids where a flight or lift serves the level but arrives at no floor. */ + landingTrouble: Set + /** Spaces behind a door whose approach from outside cannot be measured. */ + behindUnmeasuredEntrance: Set +} + +const FRAME_REASONS = ['multiple_buildings', 'tilted_buildings', 'floor_missing'] + +function stairLevelIds(nodes: SceneNodes, id: string): string[] { + const stair = nodes[id] + if (stair?.type !== 'stair') return [] + const foot = stair.fromLevelId ?? resolveLevelId(stair, nodes) + const head = stair.toLevelId ?? (foot ? getLevelAbove(foot, nodes)?.id : undefined) + return [foot, head].filter((levelId): levelId is string => typeof levelId === 'string') +} + +/** + * The one reading of reach that describe_circulation and verify_scene share: what is reached from + * any entrance, what is unmeasured, and, per level, whether an entrance reaches it at all. + */ +export function circulationReach( + nodes: SceneNodes, + rawGraph: CirculationGraph, + geometry: CirculationGeometryReason[] = circulationGeometryReasons(nodes, rawGraph), +): CirculationReach { + const frameLimited = geometry.some((reason) => FRAME_REASONS.includes(reason.code)) + const graph = frameLimited ? rawGraph : measuredCirculationGraph(nodes, rawGraph, geometry) + const entrance = exteriorEntranceEdges(graph).length > 0 + const reached = reachedFrom(circulationLinks(graph), entrance ? ['outside'] : []) + const rawLinks = circulationLinks(rawGraph) + const noRoute = !entrance && geometry.length > 0 + const behindUnmeasuredEntrance = reachedFrom( + rawLinks, + rawGraph.unmeasuredEntrances + .map((unmeasured) => unmeasured.spaceId) + .filter((id) => rawGraph.nodes.has(id)), + (id) => id !== 'outside', + ) + const unmeasured = new Set([ + ...unmeasuredRouteIds(reachedFrom(rawLinks, ['outside']), reached), + ...[...behindUnmeasuredEntrance].filter((id) => !reached.has(id)), + ...(noRoute ? [...rawGraph.nodes.keys()].filter((id) => !reached.has(id)) : []), + ]) + const landingTrouble = new Set() + for (const issue of rawGraph.issues) { + if (issue.type !== 'stair_has_no_landing' && issue.type !== 'lift_door_blocked') continue + for (const id of issue.levelIds ?? []) landingTrouble.add(id) + for (const nodeId of issue.nodeIds) + for (const id of stairLevelIds(nodes, nodeId)) landingTrouble.add(id) + } + const levels = rawGraph.floors.flatMap((floor): CirculationLevel[] => { + const spaces = [...rawGraph.nodes.values()].filter( + (node) => + node.levelId === floor.id && + (node.kind === 'room' || node.kind === 'zone' || node.kind === 'floor') && + !rawGraph.nonSpaces.has(node.id), + ) + if (!spaces.length) return [] + const reachedSpaces = spaces.filter((node) => reached.has(node.id)).length + const lost = (node: CirculationNode) => unmeasured.has(node.id) || !graph.nodes.has(node.id) + const [reachable, reason]: [boolean | null, CirculationLevelReason | null] = frameLimited + ? [null, 'not_measured'] + : !entrance + ? [null, 'no_entrance'] + : reachedSpaces + ? [true, null] + : spaces.some(lost) + ? [null, 'not_measured'] + : [false, landingTrouble.has(floor.id) ? 'no_landing' : 'no_connection'] + return [ + { + levelId: floor.id, + name: floor.name, + buildingId: resolveBuildingForLevel(floor.id, nodes as Record) ?? null, + reachable, + reason, + spaces: spaces.length, + reachedSpaces, + }, + ] + }) + return { + graph, + geometry, + frameLimited, + entrance, + reached, + unmeasured, + levels, + landingTrouble, + behindUnmeasuredEntrance, + } +} + +const levelFact = (name: string, building: string) => + `${name} of ${building} has no walkable stair or lift to it from an entrance` + +export function circulationGraphIssues( + nodes: SceneNodes, + rawGraph: CirculationGraph, + reach: CirculationReach = circulationReach(nodes, rawGraph), +): CirculationIssue[] { + const issues = [...rawGraph.issues] + const { geometry } = reach + issues.push( + ...geometry.map( + (reason): CirculationIssue => ({ + type: 'circulation_not_measured', + message: reason.message, + nodeIds: reason.nodeIds, + reasonCode: reason.code, + }), + ), + ) + if (reach.frameLimited) return issues + const { graph, entrance, reached, unmeasured } = reach + if (!entrance && geometry.length) return issues + const ground = graph.floors.find((floor) => floor.ground) + const spaces = [...graph.nodes.values()].filter( + (node) => + (node.kind === 'room' || node.kind === 'zone' || node.kind === 'floor') && + !graph.nonSpaces.has(node.id), + ) + if (!entrance && ground && spaces.length) + issues.push({ + type: 'no_exterior_door', + message: `No door, open edge or entrance steps connect outside to an interior space on ${ground.name}: the building cannot be entered.`, + nodeIds: [ground.id], + levelIds: [ground.id], + }) + // A level no entrance reaches is one fact about the level; its rooms are not raised one by one. + const cutOff = new Set( + reach.levels.filter((level) => level.reachable === false).map((level) => level.levelId), + ) + for (const level of reach.levels) { + if (level.reachable !== false) continue + const building = (level.buildingId && nodes[level.buildingId]?.name) || 'the building' + issues.push({ + type: 'missing_stair', + message: `${levelFact(level.name, building)}.`, + nodeIds: [level.levelId], + levelIds: [level.levelId], + ...(level.reason ? { reasonCode: level.reason } : {}), + }) + } + const rooms = spaces.filter( + (node) => + !reached.has(node.id) && + (!node.apartment || unmeasured.has(node.id)) && + !(cutOff.has(node.levelId ?? '') && !unmeasured.has(node.id)), + ) + for (const room of rooms) { + const limited = unmeasured.has(room.id) + const entryUnmeasured = limited && reach.behindUnmeasuredEntrance.has(room.id) + issues.push({ + type: limited ? 'circulation_not_measured' : 'room_unreachable', + message: entryUnmeasured + ? `${room.name} access is not measured because the door that enters it opens high above the modeled ground.` + : limited + ? `${room.name} access is not measured because its route crosses unmeasured walking geometry.` + : `${room.name} cannot be reached from outside through modeled doors, openings, open edges, stairs or lifts.`, + ...(limited + ? { reasonCode: entryUnmeasured ? 'entrance_not_measured' : 'route_not_measured' } + : {}), + nodeIds: [room.sourceId ?? room.levelId ?? room.id], + levelIds: room.levelId ? [room.levelId] : [], + spaceId: room.id, + }) + } + issues.push(...apartmentIssues(nodes, graph, entrance, rawGraph, cutOff)) + return issues +} + +export function circulationDiagnostics(nodes: SceneNodes): CirculationIssue[] { + return circulationGraphIssues(nodes, buildCirculationGraph(nodes)) +} diff --git a/packages/core/src/agent-operations/unreachable-rooms-check.test.ts b/packages/core/src/agent-operations/unreachable-rooms-check.test.ts new file mode 100644 index 0000000000..5138165847 --- /dev/null +++ b/packages/core/src/agent-operations/unreachable-rooms-check.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + DoorNode, + LevelNode, + SlabNode, + WallNode, + ZoneNode, +} from '../schema' +import './index' +import type { SceneNodes } from './types' +import { unreachableRoomIssues } from './unreachable-rooms-check' +import { verifyScene } from './verify-scene' + +type Pt = [number, number] + +const wall = (id: string, start: Pt, end: Pt, children: string[] = []) => + WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.1, children }) + +const door = (id: string, wallId: string, x: number) => + DoorNode.parse({ + id, + parentId: wallId, + wallId, + position: [x, 1.05, 0], + width: 0.9, + height: 2.1, + frameDepth: 0.07, + }) + +const room = (id: string, name: string, x0: number, x1: number) => + ZoneNode.parse({ + id, + parentId: 'level_1', + name, + polygon: [ + [x0, 0], + [x1, 0], + [x1, 4], + [x0, 4], + ], + }) + +// A 6 x 4 m shell with the street door in the west room; a partition at x = 3, with or without a +// door, makes the east room reachable or not. +function house({ partitionDoor }: { partitionDoor: boolean }): SceneNodes { + const nodes: AnyNode[] = [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), + SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [0, 0], + [6, 0], + [6, 4], + [0, 4], + ], + }), + wall('wall_s', [0, 0], [6, 0], ['door_front']), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + wall('wall_p', [3, 0], [3, 4], partitionDoor ? ['door_inner'] : []), + door('door_front', 'wall_s', 1.5), + ...(partitionDoor ? [door('door_inner', 'wall_p', 2)] : []), + room('zone_west', 'West room', 0, 3), + room('zone_east', 'East room', 3, 6), + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes +} + +describe('a room no walk from outside reaches', () => { + test('a room behind a partition with no door is named, with its level', () => { + const issues = unreachableRoomIssues(house({ partitionDoor: false })) + expect(issues).toHaveLength(1) + expect(issues[0]).toMatchObject({ + type: 'room_unreachable', + severity: 'warning', + levelIds: ['level_1'], + }) + expect(issues[0]?.message).toContain('East room') + expect(issues[0]?.message).toContain('cannot be reached from outside') + }) + + test('a door in the partition makes it reachable: nothing is named', () => { + expect(unreachableRoomIssues(house({ partitionDoor: true }))).toEqual([]) + }) + + test('verify_scene carries it as a warning, and not when the room is reachable', () => { + const issuesOf = (nodes: SceneNodes) => + ( + verifyScene(nodes, {} as never, { activeLevelId: 'level_1' }).result as { + issues: { type: string }[] + } + ).issues.filter((issue) => issue.type === 'room_unreachable') + expect(issuesOf(house({ partitionDoor: false }))).toHaveLength(1) + expect(issuesOf(house({ partitionDoor: true }))).toHaveLength(0) + }) +}) diff --git a/packages/core/src/agent-operations/unreachable-rooms-check.ts b/packages/core/src/agent-operations/unreachable-rooms-check.ts new file mode 100644 index 0000000000..442662f3c3 --- /dev/null +++ b/packages/core/src/agent-operations/unreachable-rooms-check.ts @@ -0,0 +1,48 @@ +import { circulationDiagnostics } from './reachability' +import type { SceneNodes } from './types' +import { registerSceneCheck } from './verify-scene' + +export type RoomUnreachableIssue = { + type: 'room_unreachable' + message: string + severity: 'warning' + nodeIds: string[] + levelIds: string[] + spaceId?: string +} + +/** + * A room no walk from outside reaches through the doors, openings, open edges, stairs and lifts the + * scene models. A level no entrance reaches is one fact about the level, said by the storey checks; + * a room whose route crosses geometry the reading cannot measure is not named (its access is unknown, + * not missing). + */ +export function unreachableRoomIssues(nodes: SceneNodes): RoomUnreachableIssue[] { + return circulationDiagnostics(nodes).flatMap((reading): RoomUnreachableIssue[] => + reading.type === 'room_unreachable' + ? [ + { + type: 'room_unreachable', + message: reading.message, + severity: 'warning', + nodeIds: reading.nodeIds, + levelIds: reading.levelIds ?? [], + ...(reading.spaceId ? { spaceId: reading.spaceId } : {}), + }, + ] + : [], + ) +} + +registerSceneCheck({ + name: 'unreachable rooms', + order: 80, + run: (nodes) => { + try { + return unreachableRoomIssues(nodes) + } catch { + // A scene the circulation graph cannot walk is the schema check's to report. + return [] + } + }, +}) diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 7992fa848b..880e069b9d 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -54,6 +54,7 @@ import { } from './scene-queries' import { reviewSince } from './scene-review' import type { AgentContext, AgentOperation, SceneNodes } from './types' +import type { RoomUnreachableIssue } from './unreachable-rooms-check' import { type WallEndShortIssue, type WallNearlyAlignedIssue, @@ -107,6 +108,7 @@ export type SceneIssue = | WallNearlyAlignedIssue | UsageIssue | RoomCheckIssue + | RoomUnreachableIssue /** What verify_scene was asked: its contract's input, which other modules may extend. */ export type VerifySceneInput = Readonly> From 2426e86c4160bee84147c760d3fc9c376a0c66a5 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 17:26:41 +0100 Subject: [PATCH 08/40] verify_scene groups what it finds, and the model reads the usage findings folded The operation returns the findings grouped by type (issueGroups, with their order: what blocks a way through first, informational last) and, when asked for a room, the room's scope. The model's reading of the result (the MCP's text; the chat reads it the same way) keeps every warning and error whole, gives a repeated informational finding as one entry with its count, its elements and a few examples, and folds the usage findings: a narrow passage is one entry for its place with the rooms it leads to, a room's turning circle and pocket are one entry for the room, the others come one by one without the structure their sentence repeats. verify_scene({ type }) returns every finding of a type whole; verify_scene({ room }) returns a room's findings with every finding naming its items, doors or windows. The structured result keeps the whole report. Tests: the fold of usage findings (passages, rooms, blockers first), and the two reads of a narrow place by room and by type that came with the usage base. Co-Authored-By: Claude Sonnet 5.5 --- .../agent-operations/scene-issue-groups.ts | 89 +++++ .../core/src/agent-operations/verify-scene.ts | 6 + .../agent-tools/verify-scene-usage.test.ts | 344 ++++++++++++++++++ .../src/agent-tools/verify-scene-usage.ts | 194 ++++++++++ packages/core/src/agent-tools/verify-scene.ts | 238 +++++++++++- .../src/spatial/usage-field/findings.test.ts | 48 +++ packages/mcp/src/tools/shared-tools.ts | 28 +- 7 files changed, 942 insertions(+), 5 deletions(-) create mode 100644 packages/core/src/agent-operations/scene-issue-groups.ts create mode 100644 packages/core/src/agent-tools/verify-scene-usage.test.ts create mode 100644 packages/core/src/agent-tools/verify-scene-usage.ts diff --git a/packages/core/src/agent-operations/scene-issue-groups.ts b/packages/core/src/agent-operations/scene-issue-groups.ts new file mode 100644 index 0000000000..5517c40f84 --- /dev/null +++ b/packages/core/src/agent-operations/scene-issue-groups.ts @@ -0,0 +1,89 @@ +import { DOOR_STOPPED_BLOCKING_DEG } from '../spatial/usage-field/swings' +import type { SceneNodes } from './types' +import type { SceneIssue } from './verify-scene' + +export type SceneIssueGroup = { + type: string + message: string + severity?: 'info' | 'warning' + count: number + nodeIds: string[] + nodes: { id: string; name: string; count: number }[] + issueIndexes: number[] +} + +const BLOCKERS = new Set(['room_unreachable', 'door_blocked']) +const REPEATS = new Set(['item_overlap', 'item_too_close']) + +/** A door whose leaf stops short of `DOOR_STOPPED_BLOCKING_DEG` is no way through, whatever it meets. */ +const isStoppedDoor = (issue: SceneIssue) => + issue.type === 'usage_door_swing' && + 'valueDeg' in issue && + typeof issue.valueDeg === 'number' && + issue.valueDeg < DOOR_STOPPED_BLOCKING_DEG + +const severityOf = (issue: SceneIssue | undefined) => + issue && 'severity' in issue ? issue.severity : undefined + +function priority(issue: SceneIssue): number { + if (BLOCKERS.has(issue.type) || isStoppedDoor(issue)) return 0 + if (severityOf(issue) === 'info') return 3 + return REPEATS.has(issue.type) ? 2 : 1 +} + +function namedIds(issue: SceneIssue, nodes: SceneNodes): string[] { + return [ + ...new Set( + Object.entries(issue).flatMap(([key, value]) => { + if (key.endsWith('Ids') && Array.isArray(value)) + return value.filter((id): id is string => typeof id === 'string' && !!nodes[id]) + if (key.endsWith('Id') && typeof value === 'string' && nodes[value]) return [value] + return [] + }), + ), + ] +} + +function groupMessage(type: string, count: number, nodeCount: number): string { + const kind = type.replaceAll('_', ' ') + return `${count} ${kind} findings${nodeCount ? ` involving ${nodeCount} elements` : ''}.` +} + +export function sceneIssueGroups(issues: SceneIssue[], nodes: SceneNodes): SceneIssueGroup[] { + issues.sort((first, second) => priority(first) - priority(second)) + const groups = new Map() + for (const [index, issue] of issues.entries()) { + let group = groups.get(issue.type) + if (!group) { + group = { + type: issue.type, + message: issue.message, + count: 0, + nodeIds: [], + nodes: [], + issueIndexes: [], + } + groups.set(issue.type, group) + } + group.count++ + group.issueIndexes.push(index) + for (const id of namedIds(issue, nodes)) { + const involved = group.nodes.find((node) => node.id === id) + if (involved) involved.count++ + else group.nodes.push({ id, name: nodes[id]?.name ?? id, count: 1 }) + } + } + for (const group of groups.values()) { + group.nodes.sort((first, second) => first.id.localeCompare(second.id)) + group.nodeIds = group.nodes.map(({ id }) => id) + if (group.count > 1) { + const summary = groupMessage(group.type, group.count, group.nodeIds.length) + group.message = group.nodeIds.length ? summary : `${summary} First: ${group.message}` + } + if (group.issueIndexes.every((index) => severityOf(issues[index]) === 'info')) + group.severity = 'info' + else if (group.issueIndexes.some((index) => severityOf(issues[index]) === 'warning')) + group.severity = 'warning' + } + return [...groups.values()] +} diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 880e069b9d..d51c6b7ecb 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -41,7 +41,9 @@ import { wallResolvedHeight } from './level-reads' import { pointInPolygon, polygonContainsPolygon, type Vec2 } from './plan-geometry' import type { RoomCheckIssue } from './room-checks' import { type RoomFinding, roomFindings } from './room-findings' +import { roomIssueScope } from './room-readings' import { EMPTY_SESSION } from './scene-checkpoint' +import { sceneIssueGroups } from './scene-issue-groups' import { changesSince, type SceneCheckpoint } from './scene-measure' import { type ContentCounts, @@ -795,6 +797,7 @@ export const verifyScene: AgentOperation = ( if (check.order >= CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {}, context)) const occupiedStoryCount = levels.filter((level) => level.isOccupiedStory).length + const issueGroups = sceneIssueGroups(issues, nodes) return { result: { ok: true, @@ -807,6 +810,9 @@ export const verifyScene: AgentOperation = ( levels, emptyLevelIds: empty.map((level) => level.levelId), issues, + ...(typeof input?.room === 'string' && { roomScope: roomIssueScope(nodes, input.room) }), + issueGroups, + issueCount: issues.length, hasIssues: issues.some((issue) => !('severity' in issue && issue.severity === 'info')), ...authoredObjects(nodes), ...Object.assign({}, ...reports.map((report) => report.run(nodes))), diff --git a/packages/core/src/agent-tools/verify-scene-usage.test.ts b/packages/core/src/agent-tools/verify-scene-usage.test.ts new file mode 100644 index 0000000000..cd5321803f --- /dev/null +++ b/packages/core/src/agent-tools/verify-scene-usage.test.ts @@ -0,0 +1,344 @@ +import { describe, expect, test } from 'bun:test' +import { sceneIssueGroups } from '../agent-operations/scene-issue-groups' +import type { SceneNodes } from '../agent-operations/types' +import { BED_ACCESS_M } from '../spatial/usage-field/beds' +import { WINDOW_ABOVE_SILL_M, WINDOW_BLOCK_M } from '../spatial/usage-field/blocked' +import { CLASH_WARNING_M } from '../spatial/usage-field/clash' +import { DOOR_M, PASSAGE_M, TURNING_M } from '../spatial/usage-field/findings' +import { OPENS_FULLY_DEG } from '../spatial/usage-field/swings' +import { verifySceneModelResult } from './index' + +// The usage findings a model reads: a room's turning circle and pocket as one entry for the room; a +// narrow place as one entry naming the rooms it leads to; every other finding one by one, without +// the structure its message and node ids repeat; the words every entry would say once; and the whole +// findings back by room or by kind. The report keeps each finding as measured. + +type Found = Record & { type: string } + +const place = (room: string, roomId: string, at: [number, number] = [1.234, 5.678]) => ({ + room, + roomId, + at, +}) +const obstacle = (nodeId: string, name: string) => ({ + nodeId, + name, + kind: 'item', + shape: 'exact', + movable: false, +}) + +/** A narrow place as `usageIssues` makes it: one finding for the rooms the way through it leads to. */ +const passage = (rooms: [room: string, roomId: string][], over: Partial = {}): Found => { + const sentence = `${rooms.map(([room]) => `“${room}”`).join(' and ')}: 0.62 m clear between the jambs of “Door 4”, a 0.72 m door` + const tail = ' (below 0.80 m, a doorway).' + return { + type: 'usage_passage_narrow', + message: `Narrow passage to ${sentence}, measured from “Front door”${tail}`, + brief: `Passage to ${sentence}${tail}`, + fromDoor: 'Front door', + severity: 'warning', + nodeIds: [...rooms.map(([, roomId]) => roomId), 'door_4'], + valueM: 0.62, + thresholdM: 0.8, + doorWidthM: 0.72, + place: place(rooms[0]![0], rooms[0]![1]), + obstacles: [obstacle('door_4', 'Door 4')], + serves: rooms.map(([room, roomId]) => ({ room, roomId })), + approximate: false, + ...over, + } +} +const turning = (room: string, roomId: string, over: Partial = {}): Found => ({ + type: 'usage_turning_narrow', + message: `No 1.50 m turning circle in “${room}”: largest 1.20 m.`, + brief: 'no 1.50 m turning circle, largest 1.20 m', + severity: 'warning', + nodeIds: [roomId], + valueM: 1.2, + thresholdM: 1.5, + place: place(room, roomId), + obstacles: [], + approximate: false, + ...over, +}) +const pocket = (room: string, roomId: string, over: Partial = {}): Found => ({ + type: 'usage_pocket', + message: `“${room}”: 0.57 m² of floor with no 0.60 m way out, beside “Tub”.`, + brief: '0.57 m² of floor with no 0.60 m way out, beside “Tub”', + severity: 'warning', + nodeIds: [roomId, 'item_tub'], + valueM2: 0.57, + place: place(room, roomId), + obstacles: [obstacle('item_tub', 'Tub')], + approximate: false, + ...over, +}) +const clash = (index: number, severity: 'warning' | 'info'): Found => ({ + type: 'usage_clash', + message: `“Piece ${index}” stands 5 cm into the sill of “Window 2” in “Bath”.`, + severity, + nodeIds: ['zone_bath', `item_${index}`, 'window_2'], + valueM: 0.048, + thresholdM: 0.08, + place: place('Bath', 'zone_bath', [-4.7712, -2.1234]), + obstacles: [obstacle(`item_${index}`, `Piece ${index}`)], + approximate: severity === 'info', + code: { profile: 'irc-2021', cite: 'x', source: 'code text', byDefault: true }, +}) + +/** A report as `verify_scene` returns it: the findings, and the groups the operation gathers them into. */ +function reportOf(found: Found[]) { + const issues = [...found] + const issueGroups = sceneIssueGroups(issues as never, {} as SceneNodes) + return { ok: true, issues, issueGroups, issueCount: issues.length, coherence: { open: 0 } } +} + +const shownOf = (found: Found[], input: unknown = {}) => + verifySceneModelResult(reportOf(found), input) as { + issues: Found[] + usageNote?: string + issueCount: number + } + +describe('a room’s turning circle and pocket are one entry', () => { + test('together; the worst severity, every node, how many', () => { + const { issues } = shownOf([turning('Bath', 'zone_bath'), pocket('Bath', 'zone_bath')]) + expect(issues).toHaveLength(1) + expect(issues[0]).toEqual({ + type: 'usage_room', + severity: 'warning', + message: + 'Bath: no 1.50 m turning circle, largest 1.20 m; 0.57 m² of floor with no 0.60 m way out, beside “Tub”.', + nodeIds: ['zone_bath', 'item_tub'], + count: 2, + }) + }) + + test('one entry for each room that has any, warnings first, where the first of them stood', () => { + const blocker = { + type: 'room_unreachable', + message: 'A room no walk reaches', + nodeIds: ['level_1'], + } + const { issues } = shownOf([ + turning('Closet', 'zone_closet', { severity: 'info' }), + pocket('Bath', 'zone_bath'), + blocker as Found, + turning('Bath', 'zone_bath'), + ]) + expect(issues.map((issue) => issue.type)).toEqual([ + 'room_unreachable', + 'usage_room', + 'usage_room', + ]) + expect(issues.slice(1).map((issue) => [issue.severity, issue.count])).toEqual([ + ['warning', 2], + ['info', 1], + ]) + }) + + test('a whole floor with no way out, in a room a narrow place leads to, is the passage’s news', () => { + const whole = pocket('Alfresco', 'zone_alfresco', { + wholeRoom: true, + brief: 'no 0.60 m way out from the entrance (10.27 m²)', + }) + const { issues } = shownOf([passage([['Alfresco', 'zone_alfresco']]), whole]) + // the place says it; the room has nothing else to say, so it has no entry of its own + expect(issues.map((issue) => issue.type)).toEqual(['usage_passage_narrow']) + // the finding is counted, and its record is there for the asking + expect(shownOf([passage([['Alfresco', 'zone_alfresco']]), whole]).issueCount).toBe(2) + const alone = shownOf([whole]).issues + expect(alone[0]!.message).toBe('Alfresco: no 0.60 m way out from the entrance (10.27 m²).') + // with something else to say, the room keeps its entry and still leaves the pocket to the place + const more = shownOf([ + passage([['Alfresco', 'zone_alfresco']]), + whole, + turning('Alfresco', 'zone_alfresco'), + ]).issues + expect(more.find((issue) => issue.type === 'usage_room')!.message).toBe( + 'Alfresco: no 1.50 m turning circle, largest 1.20 m.', + ) + }) +}) + +describe('a narrow place is one entry for the rooms it leads to', () => { + test('naming every room, with the door as drawn and the clear width, and no structure its message repeats', () => { + const { issues } = shownOf([ + passage([ + ['Bath', 'zone_bath'], + ['Hall', 'zone_hall'], + ]), + ]) + expect(issues).toEqual([ + { + type: 'usage_passage_narrow', + severity: 'warning', + message: + 'Passage to “Bath” and “Hall”: 0.62 m clear between the jambs of “Door 4”, a 0.72 m door (below 0.80 m, a doorway).', + nodeIds: ['door_4'], + }, + ]) + }) + + test('the entrance the passages were measured from is said once; with several, each says which', () => { + const one = shownOf([passage([['Bath', 'zone_bath']]), passage([['Hall', 'zone_hall']])]) + expect(one.issues.every((issue) => !String(issue.message).includes('Front door'))).toBe(true) + expect(one.usageNote).toContain('Ground-floor passages are measured from “Front door”.') + const two = shownOf([ + passage([['Bath', 'zone_bath']]), + passage([['Hall', 'zone_hall']], { + fromDoor: 'Back door', + message: 'Narrow passage to “Hall”: 0.62 m, measured from “Back door” (below 0.80 m).', + }), + ]) + expect(two.issues.map((issue) => issue.message)).toEqual([ + 'Narrow passage to “Bath”: 0.62 m clear between the jambs of “Door 4”, a 0.72 m door, measured from “Front door” (below 0.80 m, a doorway).', + 'Narrow passage to “Hall”: 0.62 m, measured from “Back door” (below 0.80 m).', + ]) + expect(two.usageNote).not.toContain('measured from') + }) +}) + +describe('every other usage finding arrives one by one', () => { + test('promoted warnings keep their approximation evidence in singles, passages and room entries', () => { + const { issues } = shownOf( + [ + clash(1, 'warning'), + passage([['Hall', 'zone_hall']], { approximate: true }), + turning('Bath', 'zone_bath', { approximate: true }), + ].map((found) => ({ ...found, approximate: true })), + ) + expect(issues).toHaveLength(3) + for (const issue of issues) { + expect(issue.severity).toBe('warning') + expect(issue.approximate).toBe(true) + } + }) + + test('warning or info, never as a group of examples, without the structure its message repeats', () => { + const { issues, issueCount } = shownOf([ + ...Array.from({ length: 6 }, (_, index) => clash(index, 'info')), + clash(9, 'warning'), + ]) + expect(issueCount).toBe(7) + expect(issues).toHaveLength(7) + expect(issues[0]).toEqual({ + type: 'usage_clash', + severity: 'warning', + message: '“Piece 9” stands 5 cm into the sill of “Window 2” in “Bath”.', + nodeIds: ['zone_bath', 'item_9', 'window_2'], + valueM: 0.048, + at: [-4.77, -2.12], + }) + for (const issue of issues) { + expect(Object.keys(issue)).not.toContain('obstacles') + expect(Object.keys(issue)).not.toContain('place') + expect(Object.keys(issue)).not.toContain('code') + expect(Object.keys(issue)).not.toContain('examples') + } + }) +}) + +describe('the whole findings, by room or by kind', () => { + const found = [ + passage([ + ['Bath', 'zone_bath'], + ['Hall', 'zone_hall'], + ]), + turning('Bath', 'zone_bath'), + turning('Closet', 'zone_closet'), + clash(1, 'warning'), + ] + + test('a room, by id or by name, gives every usage finding of it as measured, the places that lead to it too', () => { + for (const room of ['zone_bath', 'bath', ' Bath ']) { + const answer = verifySceneModelResult(reportOf(found), { room }) as { + room: string + issueCount: number + issues: Found[] + coherence?: unknown + } + expect(answer.issueCount).toBe(3) + expect(answer.issues.map((issue) => issue.type).sort()).toEqual([ + 'usage_clash', + 'usage_passage_narrow', + 'usage_turning_narrow', + ]) + // whole: the obstacles, the places and the rooms it leads to stay + expect(answer.issues.find((issue) => issue.type === 'usage_passage_narrow')).toEqual( + passage([ + ['Bath', 'zone_bath'], + ['Hall', 'zone_hall'], + ]), + ) + expect(answer.coherence).toBeUndefined() + } + // a room the place leads to has it, though the finding's own place names another + const hall = verifySceneModelResult(reportOf(found), { room: 'Hall' }) as { issues: Found[] } + expect(hall.issues.map((issue) => issue.type)).toEqual(['usage_passage_narrow']) + }) + + test('a room nothing was found in names the rooms there are', () => { + const answer = verifySceneModelResult(reportOf(found), { room: 'Attic' }) as Record< + string, + unknown + > + expect(answer).toMatchObject({ room: 'Attic', issueCount: 0, issues: [] }) + expect(answer.rooms).toEqual(['Bath', 'Hall', 'Closet']) + }) + + test('the type of a room’s entry gives the findings the entries hold; a kind gives its own, in a room if asked', () => { + const entries = verifySceneModelResult(reportOf(found), { type: 'usage_room' }) as { + issues: Found[] + } + expect(entries.issues.map((issue) => issue.type).sort()).toEqual([ + 'usage_turning_narrow', + 'usage_turning_narrow', + ]) + const turnings = verifySceneModelResult(reportOf(found), { + type: 'usage_turning_narrow', + room: 'Closet', + }) as { issues: Found[]; room: string } + expect(turnings.room).toBe('Closet') + expect(turnings.issues).toEqual([turning('Closet', 'zone_closet')]) + const places = verifySceneModelResult(reportOf(found), { + type: 'usage_passage_narrow', + room: 'Hall', + }) as { issues: Found[] } + expect(places.issues).toHaveLength(1) + }) +}) + +describe('the words every entry would repeat', () => { + test('are said once, with the usage entries; an answer without any has none', () => { + const { usageNote } = shownOf([passage([['Bath', 'zone_bath']]), clash(1, 'warning')]) + expect(usageNote).toBeString() + expect(usageNote!.match(/indicators/g)).toHaveLength(1) + const none = verifySceneModelResult( + reportOf([{ type: 'door_blocked', message: 'Door 9 is blocked', nodeIds: ['door_9'] }]), + {}, + ) as Record + expect('usageNote' in none).toBe(false) + }) + + test('state the thresholds the checks apply', () => { + const { usageNote } = shownOf([passage([['Bath', 'zone_bath']])]) + const metres = (value: number) => `${value.toFixed(2)} m` + for (const text of [ + `under ${metres(PASSAGE_M)}`, + `(${metres(DOOR_M)} through a doorway)`, + `under ${metres(TURNING_M)}`, + `8 cm a warning`, + `within ${Math.round(WINDOW_BLOCK_M * 100)} cm of the glass`, + `over ${Math.round(WINDOW_ABOVE_SILL_M * 100)} cm above its sill`, + `before ${OPENS_FULLY_DEG}°`, + `wants ${metres(BED_ACCESS_M)} at a side`, + // a doorway is judged on its clear width, and a place on no way to a room has no passage line + 'the limit applies to that clear width, not the door as drawn', + 'a slot or cupboard on no way to a room has none', + ]) + expect(usageNote).toContain(text) + expect(CLASH_WARNING_M).toBe(0.08) + }) +}) diff --git a/packages/core/src/agent-tools/verify-scene-usage.ts b/packages/core/src/agent-tools/verify-scene-usage.ts new file mode 100644 index 0000000000..d0ca093bf5 --- /dev/null +++ b/packages/core/src/agent-tools/verify-scene-usage.ts @@ -0,0 +1,194 @@ +import { USAGE_INDICATORS } from '../building/code-profile' + +/** + * How `verify_scene` shows the usage findings to a model: a room's missing turning circle and + * pocket as one entry for the room, a narrow place as one entry for the rooms it leads to, every + * other finding whole but without the structure its message and node ids already carry, and the + * words every entry would repeat once. The report keeps each finding as measured (`usageIssues`); + * `type` and `room` give them back. + */ + +/** The findings a room's one entry holds. */ +export const ROOM_FOLDED_TYPES = ['usage_turning_narrow', 'usage_pocket'] as const + +/** The type of a narrow passage's finding: one for each place, naming the rooms it leads to. */ +export const PASSAGE_TYPE = 'usage_passage_narrow' + +/** The type of a room's one entry; asking for it returns the findings it holds. */ +export const ROOM_ENTRY_TYPE = 'usage_room' + +export const isUsageType = (type: unknown): type is string => + typeof type === 'string' && type.startsWith('usage_') + +export const isRoomFolded = (type: unknown): boolean => + (ROOM_FOLDED_TYPES as readonly unknown[]).includes(type) + +type Found = Record + +const isRecord = (value: unknown): value is Found => + !!value && typeof value === 'object' && !Array.isArray(value) + +const placeOf = (found: Found) => (isRecord(found.place) ? found.place : {}) + +const roomIdOf = (found: Found) => String(placeOf(found).roomId ?? '') + +const stringsOf = (value: unknown): string[] => + Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [] + +const round2 = (value: number) => Math.round(value * 100) / 100 + +/** A finding's place on the plan to the centimetre, or nothing. */ +function atOf(found: Found): [number, number] | undefined { + const at = placeOf(found).at + return Array.isArray(at) && typeof at[0] === 'number' && typeof at[1] === 'number' + ? [round2(at[0]), round2(at[1])] + : undefined +} + +/** The rooms a narrow passage leads to: its `serves`. */ +function servedBy(found: Found): { room: string; roomId: string }[] { + return Array.isArray(found.serves) + ? found.serves.filter(isRecord).map((room) => ({ + room: String(room.room ?? ''), + roomId: String(room.roomId ?? ''), + })) + : [] +} + +/** The ids of the rooms a narrow passage leads to. */ +export const servedRoomIds = (passages: Found[]) => + new Set(passages.flatMap((found) => servedBy(found).map((room) => room.roomId))) + +/** The entrances the passages were measured from: said once in the note when there is one, by each entry when there are several. */ +export const passageEntrances = (passages: Found[]): string[] => [ + ...new Set( + passages.flatMap((found) => (typeof found.fromDoor === 'string' ? [found.fromDoor] : [])), + ), +] + +/** + * One entry per room for its turning circle and pocket findings, in the order the rooms first + * appear. A pocket that is the room's whole free floor, in a room a narrow passage leads to, says + * what the passage says (a path under a 0.60 m unit leads nowhere a unit can leave), so the entry + * does not say it twice and a room with nothing else has none; `count` is every finding it holds. + */ +export function foldUsageRooms(members: Found[], served: ReadonlySet): Found[] { + const rooms = new Map() + for (const found of members) { + const key = roomIdOf(found) + rooms.set(key, [...(rooms.get(key) ?? []), found]) + } + return [...rooms.entries()].flatMap(([roomId, held]) => { + const clauses = held + .filter( + (found) => + !(found.type === 'usage_pocket' && found.wholeRoom === true && served.has(roomId)), + ) + .map((found) => String(found.brief ?? found.message)) + if (!clauses.length) return [] + const warning = held.some((found) => found.severity !== 'info') + const first = held[0]! + return [ + { + type: ROOM_ENTRY_TYPE, + severity: warning ? 'warning' : 'info', + message: `${String(placeOf(first).room ?? '')}: ${clauses.join('; ')}.`, + nodeIds: [...new Set(held.flatMap((found) => stringsOf(found.nodeIds)))], + count: held.length, + ...(held.some((found) => found.approximate === true) ? { approximate: true } : {}), + }, + ] + }) +} + +/** What an entry for one finding keeps: its sentence, its nodes, its measured values and where. */ +const KEPT = ['type', 'severity', 'message', 'nodeIds', 'valueM', 'valueM2', 'valueDeg'] as const + +/** + * A usage finding without what its message and node ids already say (obstacles, thresholds, code + * table row). A narrow place keeps its sentence and the things that bound it: the figure and the + * rooms are in the sentence, and a room's own findings are asked for by its name. + */ +export function slimUsageFinding(found: Found, entrances: readonly string[] = []): Found { + if (found.type === PASSAGE_TYPE) { + const rooms = new Set(servedBy(found).map((room) => room.roomId)) + return { + type: found.type, + severity: found.severity, + message: + entrances.length < 2 && typeof found.brief === 'string' ? found.brief : found.message, + nodeIds: stringsOf(found.nodeIds).filter((id) => !rooms.has(id)), + ...(found.approximate === true ? { approximate: true } : {}), + } + } + const slim: Found = {} + for (const key of KEPT) if (found[key] !== undefined) slim[key] = found[key] + if (found.approximate === true) slim.approximate = true + const at = atOf(found) + if (at) slim.at = at + return slim +} + +/** The rooms a usage finding is about: its own, and the rooms a narrow passage leads to. */ +function roomsOf(found: Found): { room: string; roomId: string }[] { + return [...servedBy(found), { room: String(placeOf(found).room ?? ''), roomId: roomIdOf(found) }] +} + +/** Findings placed in, serving or naming a room or one of its contents, returned whole. */ +export function findingsOfRoom(issues: unknown[], room: string, scope: unknown): Found[] { + const wanted = room.trim().toLowerCase() + const rooms = Array.isArray(scope) + ? scope.filter( + (entry) => + isRecord(entry) && + [entry.roomId, entry.room].some( + (name) => typeof name === 'string' && name.trim().toLowerCase() === wanted, + ), + ) + : [] + const nodeIds = new Set(rooms.flatMap((entry) => stringsOf(entry.nodeIds))) + return issues.filter( + (issue): issue is Found => + isRecord(issue) && + (roomsOf(issue).some( + (found) => + found.roomId.toLowerCase() === wanted || found.room.trim().toLowerCase() === wanted, + ) || + Object.entries(issue).some(([key, value]) => + key.endsWith('Ids') + ? stringsOf(value).some((id) => nodeIds.has(id)) + : key.endsWith('Id') && typeof value === 'string' && nodeIds.has(value), + )), + ) +} + +/** The rooms that have usage findings, for the answer to a room nothing was found for. */ +export function roomsWithUsageFindings(issues: unknown[]): string[] { + return [ + ...new Set( + issues.flatMap((issue) => + isRecord(issue) && isUsageType(issue.type) ? roomsOf(issue).map((room) => room.room) : [], + ), + ), + ].filter(Boolean) +} + +const metres = (value: number) => value.toFixed(2) + +/** + * The words every usage entry would repeat, said once: what a finding is, the thresholds it reads + * against (the numbers the checks apply; a test holds them to those), and what the entries are. + */ +export function usageNote(measuredFrom: readonly string[] = []): string { + const { passage, doorClear, turning } = USAGE_INDICATORS + return [ + 'Usage findings are indicators read from the drawn scene, not code checks; a figure from a code names it.', + `A passage is narrow under ${metres(passage.value)} m (${metres(doorClear.value)} m through a doorway), a turning circle under ${metres(turning.value)} m; a pocket is floor a 0.60 m unit fits on and cannot leave.`, + 'A piece 2 cm into another is a contact, 8 cm a warning; a window is blocked by a piece within 15 cm of the glass and over 30 cm above its sill; a door stopping before 80° is a finding; a bed wants 0.60 m at a side and at the foot. Use defects warn even on approximate shapes.', + ...(measuredFrom.length + ? [`Ground-floor passages are measured from “${measuredFrom[0]}”.`] + : []), + 'A doorway is read between its jambs, and the limit applies to that clear width, not the door as drawn.', + 'A narrow passage is one entry for the place, naming the rooms it leads to; a slot or cupboard on no way to a room has none, a pocket speaks for dead floor. One usage_room entry per room holds its turning circle and pocket.', + ].join(' ') +} diff --git a/packages/core/src/agent-tools/verify-scene.ts b/packages/core/src/agent-tools/verify-scene.ts index 35a1a9e203..24306f1991 100644 --- a/packages/core/src/agent-tools/verify-scene.ts +++ b/packages/core/src/agent-tools/verify-scene.ts @@ -1,4 +1,17 @@ -import type { z } from 'zod' +import { z } from 'zod' +import { + findingsOfRoom, + foldUsageRooms, + isRoomFolded, + isUsageType, + PASSAGE_TYPE, + passageEntrances, + ROOM_ENTRY_TYPE, + roomsWithUsageFindings, + servedRoomIds, + slimUsageFinding, + usageNote, +} from './verify-scene-usage' /** * `verify_scene`'s contract. Other modules extend it with an input and a sentence for the check @@ -22,9 +35,228 @@ export const verifySceneTool = { name: 'verify_scene', title: 'Verify scene', get description() { - return [DESCRIPTION, ...extensions.map((extension) => extension.description)].join(' ') + return [ + DESCRIPTION, + 'Every warning and every error arrives whole, its own measurements with it; a repeated informational finding (severity info) arrives once, with its count, its elements and a few examples.', + "Usage findings arrive trimmed, a narrow passage as one entry for the place with the rooms it leads to, each room's turning circle and pocket as one usage_room entry; `room` (a room's id or name) returns its whole findings plus every finding naming its items, doors or windows, even when placed in a neighbouring room; `type` returns the whole findings of that kind.", + ...extensions.map((extension) => extension.description), + ].join(' ') }, get input(): Record { - return Object.assign({}, ...extensions.map((extension) => extension.input)) + return Object.assign( + { + type: z + .string() + .min(1) + .optional() + .describe( + 'One finding type (for example "usage_passage_narrow"): the answer then lists every original finding of that type, whole, and none of the other blocks of the report.', + ), + room: z + .string() + .min(1) + .optional() + .describe( + "A room's id or name: the answer lists its findings whole, including passages serving it and every finding naming its items, doors or windows.", + ), + }, + ...extensions.map((extension) => extension.input), + ) }, } + +const groupedReport = z.object({ + issues: z.array(z.unknown()), + issueGroups: z.array( + z.looseObject({ + type: z.string(), + message: z.string(), + count: z.number().int().positive(), + issueIndexes: z.array(z.number().int().nonnegative()).min(1), + // Read for the presentation alone: a group's other fields (its moves) ride along untouched. + severity: z.enum(['info', 'warning']).optional(), + nodes: z.unknown().optional(), + }), + ), +}) + +/** A type's findings, as `sceneIssueGroups` gathered them. */ +type SceneIssueGroup = z.infer['issueGroups'][number] + +/** Complete examples of one repeated informational finding that ride with its group. */ +const GROUP_EXAMPLES = 3 + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) +} + +/** `verify_scene`'s arguments, read for the presentation; the operation itself receives them all. */ +function requestedType(input: unknown): string | null { + const type = isRecord(input) ? input.type : null + return typeof type === 'string' && type.length > 0 ? type : null +} + +function requestedRoom(input: unknown): string | null { + const room = isRecord(input) ? input.room : null + return typeof room === 'string' && room.trim().length > 0 ? room : null +} + +/** + * What the model reads for `verify_scene`: the same facts, grouped. Every warning and error is + * whole — its message, its node ids and its measurements — a repeated informational finding is one + * entry per type with a few examples and the call that returns them all, The usage findings are the exception that + * keeps every finding: a narrow passage is one entry for its place, a room's turning circle and + * pocket are one entry for the room, the others arrive one by one without the structure their sentence repeats (`verify-scene-usage.ts`). + * A `type` or `room` question and a refusal answer as they came; no other argument widens the + * answer. The editor, the structured MCP result and the benchmarks keep the report `verify_scene` + * returned. + */ +export function verifySceneModelResult(output: unknown, input: unknown): unknown { + const parsed = groupedReport.safeParse(output) + if (!parsed.success) return output + const { issues, issueGroups } = parsed.data + if (issueGroups.some((group) => group.issueIndexes.some((index) => index >= issues.length))) + return output + const report = output as Record + const type = requestedType(input) + const room = requestedRoom(input) + if (type) return oneTypeReport(report, issues, issueGroups, type, room) + if (room) return oneRoomReport(report, issues, room) + return compactReport(report, issues, issueGroups) +} + +/** + * `type: "…"`: every original finding of that one type, and none of the report's other blocks. + * `usage_room`, the type of a room's entry, gives the findings the entries hold; with a `room`, only that room's. + */ +function oneTypeReport( + report: Record, + issues: unknown[], + issueGroups: SceneIssueGroup[], + type: string, + room: string | null, +): unknown { + const ofType = issues.filter( + (issue) => + isRecord(issue) && + (type === ROOM_ENTRY_TYPE ? isRoomFolded(issue.type) : issue.type === type), + ) + const findings = room ? findingsOfRoom(ofType, room, report.roomScope) : ofType + const named = { ok: report.ok, type, ...(room ? { room } : {}) } + if (findings.length > 0) return { ...named, issueCount: findings.length, issues: findings } + return { + ...named, + issueCount: 0, + issues: [], + types: Object.fromEntries(issueGroups.map((group) => [group.type, group.count])), + } +} + +/** `room: "…"`: the room's findings and those naming its contents, whole. */ +function oneRoomReport(report: Record, issues: unknown[], room: string): unknown { + const findings = findingsOfRoom(issues, room, report.roomScope) + if (findings.length > 0) + return { ok: report.ok, room, issueCount: findings.length, issues: findings } + return { + ok: report.ok, + room, + issueCount: 0, + issues: [], + rooms: roomsWithUsageFindings(issues), + } +} + +function compactReport( + report: Record, + issues: unknown[], + issueGroups: SceneIssueGroup[], +): unknown { + const { issueGroups: _groups, ...rest } = report + const { shown, measuredFrom } = shownIssues(issues, issueGroups) + return { + ...rest, + issueCount: issues.length, + issues: shown, + ...(shown.some((issue) => isRecord(issue) && isUsageType(issue.type)) + ? { usageNote: usageNote(measuredFrom) } + : {}), + } +} + +/** Every warning and error whole; one entry for each repeated informational finding; the usage findings as the room entries and the singles they are. */ +function shownIssues( + issues: unknown[], + issueGroups: SceneIssueGroup[], +): { shown: unknown[]; measuredFrom: string[] } { + const shown: unknown[] = [] + const grouped = new Set() + const roomFindings: Record[] = [] + let roomsAt = -1 + const passages = issues.filter(isRecord).filter((issue) => issue.type === PASSAGE_TYPE) + const entrances = passageEntrances(passages) + for (const group of issueGroups) { + const members = group.issueIndexes.map((index) => { + grouped.add(index) + return issues[index] + }) + // A room's turning circle and pocket are one entry for the room, where the first of them stood. + if (isRoomFolded(group.type)) { + if (roomsAt < 0) roomsAt = shown.length + roomFindings.push(...members.filter(isRecord)) + continue + } + // The other usage findings arrive one by one, info or not, without the structure their message repeats. + if (isUsageType(group.type)) { + shown.push( + ...members.map((member) => + isRecord(member) ? slimUsageFinding(member, entrances) : member, + ), + ) + continue + } + // A lone finding of a type is its own complete example, informational or not. + if (group.severity === 'info' && members.length > 1) { + shown.push(infoGroup(group, members)) + continue + } + shown.push(...members) + } + if (roomsAt >= 0) { + const entries = foldUsageRooms(roomFindings, servedRoomIds(passages)) + shown.splice( + roomsAt, + 0, + ...entries.filter((entry) => entry.severity !== 'info'), + ...entries.filter((entry) => entry.severity === 'info'), + ) + } + // A finding no group gathered still arrives whole: the presentation hides none. + issues.forEach((issue, index) => { + if (!grouped.has(index)) shown.push(issue) + }) + return { shown, measuredFrom: entrances.length === 1 ? entrances : [] } +} + +/** A repeated informational finding: how many, where, a few examples, and how to read them all. */ +function infoGroup(group: SceneIssueGroup, members: unknown[]) { + const { issueIndexes: _indexes, nodes: _nodes, ...summary } = group + return { + ...summary, + examples: distinctExamples(members), + detail: `verify_scene({ "type": "${group.type}" }) returns all ${members.length} findings`, + } +} + +/** The first few findings that differ, so a group of identical records costs one of them. */ +function distinctExamples(members: unknown[]): unknown[] { + const examples: unknown[] = [] + const seen = new Set() + for (const member of members) { + const key = JSON.stringify(member) + if (seen.has(key)) continue + seen.add(key) + examples.push(member) + if (examples.length === GROUP_EXAMPLES) break + } + return examples +} diff --git a/packages/core/src/spatial/usage-field/findings.test.ts b/packages/core/src/spatial/usage-field/findings.test.ts index 416472b281..30f320febc 100644 --- a/packages/core/src/spatial/usage-field/findings.test.ts +++ b/packages/core/src/spatial/usage-field/findings.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, test } from 'bun:test' import { verifyScene } from '../../agent-operations' +import { verifySceneModelResult } from '../../agent-tools/verify-scene' import { distanceToBoundary } from '../../lib/polygon-boolean' import { type AnyNode, @@ -335,6 +336,21 @@ describe('a narrow place is one finding for the rooms it leads to', () => { ]) }) + test('the room filter gives the place for each room it leads to, and nothing for another room', () => { + setSdfChecks(true) + const report = verifyScene(both(), {}, { activeLevelId: null }).result + try { + for (const room of ['East room', 'East annex', 'zone_annex']) { + const answer = verifySceneModelResult(report, { room }) as { issues: { type: string }[] } + expect(answer.issues.map((i) => i.type)).toContain('usage_passage_narrow') + } + const west = verifySceneModelResult(report, { room: 'West room' }) as { issueCount: number } + expect(west.issueCount).toBe(0) + } finally { + setSdfChecks(false) + } + }) + test('a slot on no way to a room has no passage finding', () => { // two stubs from the north wall leave a 0.30 m slot, 1.5 m deep, open to the hall at one end const nodes = house([ @@ -478,4 +494,36 @@ describe('the flag', () => { expect(JSON.stringify(verifyScene(nodes, {}, context).result)).toBe(off) expect(off).not.toContain('usage_') }) + + test('a model reads a narrow place as one entry, and the report and the asking give the findings whole', () => { + setSdfChecks(true) + const report = verifyScene(twoRooms(0.7), {}, { activeLevelId: null }).result as { + issues: { type: string; place?: { room: string } }[] + } + // the report keeps each finding as measured + const east = report.issues.filter((i) => i.place?.room === 'East room') + expect(east.map((i) => i.type)).toEqual(['usage_passage_narrow']) + + const model = verifySceneModelResult(report, {}) as { + issues: { type: string; message: string; nodeIds: string[]; count?: number }[] + usageNote: string + } + // a narrow place is its own entry, the limit that applied with it and the entrance said once in the note; nothing else in the room, so no room entry + const place = model.issues.find((i) => i.type === 'usage_passage_narrow') + expect(place?.message).toBe( + 'Passage to “East room”: 0.60 m clear between the jambs of “Inner door”, a 0.70 m door (below 0.80 m, a doorway).', + ) + expect(place?.nodeIds).toEqual(['door_inner']) + expect(model.issues.some((i) => i.type === 'usage_room')).toBe(false) + expect(model.usageNote).toContain('Ground-floor passages are measured from “Front door”.') + + const asked = verifySceneModelResult(report, { room: 'East room' }) as { + issues: { type: string }[] + } + expect(asked.issues).toEqual(east) + const byKind = verifySceneModelResult(report, { type: 'usage_passage_narrow' }) as { + issues: unknown[] + } + expect(byKind.issues).toEqual(report.issues.filter((i) => i.type === 'usage_passage_narrow')) + }) }) diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index d35dc926fd..68619432eb 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -65,6 +65,7 @@ import { setUnitMembersTool, setWallTypeTool, validateDesignTool, + verifySceneModelResult, verifySceneTool, viewAssetsTool, } from '@pascal-app/core/agent-tools' @@ -663,6 +664,18 @@ function writesScene(changes: SceneChanges | undefined): boolean { ) } +/** + * What the model reads of a tool's result: for verify_scene, the findings grouped and trimmed + * (`verifySceneModelResult`); every other result as it is. The structured result keeps the report whole. + */ +function modelResult( + name: string, + output: Record, + input: Record, +) { + return name === verifySceneTool.name ? verifySceneModelResult(output, input) : output +} + export function registerSharedTools( server: McpServer, bridge: SceneOperations, @@ -795,11 +808,22 @@ export function registerOperationTool( }) if (pictures.length) return { - content: [{ type: 'text' as const, text: JSON.stringify(shown) }, ...pictures], + content: [ + { + type: 'text' as const, + text: JSON.stringify(modelResult(tool.contract.name, shown, input)), + }, + ...pictures, + ], structuredContent: shown, } return { - content: [{ type: 'text' as const, text: JSON.stringify(payload) }], + content: [ + { + type: 'text' as const, + text: JSON.stringify(modelResult(tool.contract.name, payload, input)), + }, + ], structuredContent: payload, } }, From 61be6d11c24e3ebf4c216586a8070e869aa71f0c Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 18:00:37 +0100 Subject: [PATCH 09/40] verify_scene's description names the room checks The description named the problem types of main and the wall and floor checks; it did not name the ones that read a room's surfaces. One sentence now lists them with their types: a wet room whose walls are not tiled where its fixtures stand, skirting in no room or on part of the wall faces of a room, floors and wall faces left at the default finish, an outside finish that also shows on the inside face of a wall, and an item hung on the face that looks into a different room than the one it names. Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/agent-tools/verify-scene.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/agent-tools/verify-scene.ts b/packages/core/src/agent-tools/verify-scene.ts index 24306f1991..b7e7d27a47 100644 --- a/packages/core/src/agent-tools/verify-scene.ts +++ b/packages/core/src/agent-tools/verify-scene.ts @@ -29,7 +29,7 @@ export function extendVerifyScene(extension: { } const DESCRIPTION = - 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), two rooms on the same clear floor (zones_overlap) and floor inside a covered space that no zone or stair claims (floor_unclaimed), both warnings with their area, width and place and quiet under 0.1 m² (overlap), 0.3 m² (unclaimed) or 15 cm wide, wall bodies not counting as floor, an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' + 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), two rooms on the same clear floor (zones_overlap) and floor inside a covered space that no zone or stair claims (floor_unclaimed), both warnings with their area, width and place and quiet under 0.1 m² (overlap), 0.3 m² (unclaimed) or 15 cm wide, wall bodies not counting as floor, an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). What the surfaces of a room say, each one an observation to keep when it is intended: a wet room whose walls are not tiled where its fixtures stand (room_wet_untiled), skirting in no room or on part of the wall faces of a room (rooms_no_skirting, rooms_skirting_partial), floors and wall faces left at the default finish (rooms_floors_default, wall_faces_default), an outside finish that also shows on the inside face of a wall (walls_outside_finish_inside), and an item hung on the face that looks into a different room than the one it names (room_wall_item_wrong_face). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' export const verifySceneTool = { name: 'verify_scene', From 915ee0c5c6317b8829bf6fd9def4958c50f7718c Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 18:14:51 +0100 Subject: [PATCH 10/40] run_batch checks each call under the batch's own refusal policy A batch used to be refused whole, before any call ran, when one call named an unknown tool or had an invalid input (unless the tool was independent), or when the design brief's gate refused a call. The same refusal from a call that ran was handled by onRefusal. The batch now checks each call as it comes: an unknown tool, an invalid input and a brief refusal are that call's refusal, and `stop` (the default) applies nothing while `skip` reports it and applies the other calls. An object a batch builds is checked against the gate before its module is compiled, and a catalog placement the gate refuses does not make the host read the library. create_unit joins the tools a batch runs; create_room, add_door and add_window say they are not available in a batch. Tests: the case table's two rewritten rows and two new ones (stop names the refused call and applies nothing; skip runs the calls around an unsupported tool and an invalid input), the core brief tests, the MCP brief test (stop and skip, then a brief opens the made pieces) and two batch tests (a refusal leaves the authored objects in one undo step; a missing brief refuses an object before compilation). Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/design-brief-cases.ts | 54 ++++++++++-- .../core/src/agent-operations/add-object.ts | 5 +- packages/core/src/agent-operations/batch.ts | 87 +++++++------------ .../src/agent-operations/design-brief.test.ts | 31 ++++--- .../core/src/agent-operations/design-brief.ts | 17 +--- packages/core/src/agent-tools/batch.ts | 3 +- packages/core/src/agent-tools/create-room.ts | 2 +- .../core/src/agent-tools/wall-openings.ts | 4 +- .../mcp/src/tools/add-object-batch.test.ts | 49 +++++++++++ packages/mcp/src/tools/design-brief.test.ts | 66 +++++++++++--- packages/mcp/src/tools/shared-tools.ts | 5 +- skills/pascal-3d/SKILL.md | 2 +- wiki/architecture/agent-surfaces.md | 4 +- 13 files changed, 219 insertions(+), 110 deletions(-) diff --git a/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts index 87164bf8e0..bc6b8e44c8 100644 --- a/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts @@ -634,7 +634,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ expect: { result: {} }, }, { - name: 'a batch holding one furnishing call before a brief is refused whole, whatever onRefusal says', + name: 'skip reports a missing brief per call while the batch reads still run', tool: 'run_batch', scene: storeysScene, input: { @@ -646,8 +646,9 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ }, context: { designBrief: null }, expect: { - refusal: 'design_brief_required', - mentions: ["The batch's call 2 (place_design) is refused", 'Nothing in the batch was applied'], + result: { applied: 1, refused: 1 }, + contains: { calls: [{ index: 1, tool: 'place_design', status: 'refused', code: 'design_brief_required' }] }, + mentions: BEFORE, }, }, { @@ -718,7 +719,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ expect: { result: { status: 'applied', applied: 1, refused: 0 } }, }, { - name: 'a batch under an open brief refuses a catalog placement whole', + name: 'skip under an open brief makes its piece and reports the refused catalog call', tool: 'run_batch', scene: storeysScene, input: { @@ -730,8 +731,49 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ }, context: { ...library, designBrief: OPEN }, expect: { - refusal: 'brief_source_open', - mentions: ["The batch's call 2 (place_in_room) is refused", OPEN_SOURCE('double-bed')], + result: { applied: 1, refused: 1 }, + contains: { calls: [{ index: 1, tool: 'place_in_room', status: 'refused', code: 'brief_source_open' }] }, + mentions: [OPEN_SOURCE('double-bed')], + }, + }, + { + name: 'stop names the refused catalog call and applies nothing', + tool: 'run_batch', + scene: storeysScene, + input: { + calls: [ + { tool: 'place_design', input: sofa }, + { tool: 'place_in_room', input: { assetId: 'double-bed', polygon: [[0, 0], [4, 0], [4, 5], [0, 5]], ...ground } }, + ], + }, + context: { ...library, designBrief: OPEN }, + expect: { + refusal: 'batch_call_refused', + mentions: ['call 2', 'place_in_room', 'brief_source_open', OPEN_SOURCE('double-bed')], + }, + }, + { + name: 'skip runs the calls around an unsupported tool and an invalid input', + tool: 'run_batch', + scene: storeysScene, + input: { + calls: [ + { tool: 'list_levels' }, + { tool: 'run_batch', input: { calls: [] } }, + { tool: 'delete_node', input: {} }, + { tool: 'list_levels' }, + ], + onRefusal: 'skip', + }, + expect: { + result: { applied: 2, refused: 2 }, + contains: { + calls: [ + { index: 1, tool: 'run_batch', status: 'refused', code: 'unknown_tool' }, + { index: 2, tool: 'delete_node', status: 'refused', code: 'invalid_input' }, + { index: 3, tool: 'list_levels', status: 'ok' }, + ], + }, }, }, ] diff --git a/packages/core/src/agent-operations/add-object.ts b/packages/core/src/agent-operations/add-object.ts index ece03f470e..a5277726d3 100644 --- a/packages/core/src/agent-operations/add-object.ts +++ b/packages/core/src/agent-operations/add-object.ts @@ -29,11 +29,12 @@ import { type WallFace, } from '../schema' import { achievedChanges } from './achieved' +import { requireFurnishing } from './design-brief' import { targetLevel } from './level-target' import { roofLevelRefusal } from './roof-writes' import { exactColorMaterial, exactScriptSlots } from './scene-materials' import { queryNodes } from './scene-queries' -import type { AgentOperation, BatchedObject, SceneNodes } from './types' +import type { AgentContext, AgentOperation, BatchedObject, SceneNodes } from './types' type Vec3 = [number, number, number] @@ -478,6 +479,7 @@ const BATCH_COMPILES_AT_ONCE = 3 export async function buildBatchObjects( calls: readonly { tool?: unknown; input?: unknown }[], build: (input: Omit) => Promise, + designBrief?: AgentContext['designBrief'], ): Promise> { const parse = z.object(addObjectTool.input) const built: Record = {} @@ -505,6 +507,7 @@ export async function buildBatchObjects( const worker = async () => { for (let job = jobs[next++]; job; job = jobs[next++]) { try { + requireFurnishing('add_object', job.input, designBrief) requireAddObjectReason(job.input) built[job.index] = { compiled: await build(job.input) } } catch (error) { diff --git a/packages/core/src/agent-operations/batch.ts b/packages/core/src/agent-operations/batch.ts index 74d7ee62f1..52d28eb88b 100644 --- a/packages/core/src/agent-operations/batch.ts +++ b/packages/core/src/agent-operations/batch.ts @@ -17,73 +17,52 @@ type CallReport = | { index: number; tool: string; status: 'ok'; result: Record } | { index: number; tool: string; status: 'refused'; code: string; error: string } -type PreparedCall = - | { index: number; tool: string; invalid: string } - | { - index: number - tool: string - invalid?: undefined - operation: AgentOperation - input: unknown - } +function prepareCall( + call: BatchInput['calls'][number], + index: number, + operations: Readonly>>, + contracts: readonly Contract[], +) { + const operation = Object.hasOwn(operations, call.tool) ? operations[call.tool] : undefined + const contract = contracts.find((candidate) => candidate.name === call.tool) + if (!(operation && contract)) + refuse( + 'unknown_tool', + `The batch's call ${index + 1} names ${call.tool}, which a batch cannot run: call it on its own. A batch runs: ${Object.keys(operations).join(', ')}.`, + ) + const parsed = z.object(contract.input).safeParse(call.input ?? {}) + if (!parsed.success) + refuse( + 'invalid_input', + `The batch's call ${index + 1} (${call.tool}) has an invalid input: ${parsed.error.issues + .map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`) + .join('; ')}.`, + ) + return { operation, input: parsed.data } +} /** * `run_batch`: shared tools in order, each on the scene the calls before it left, their changes * merged into one set — one undo step, one write on either surface. The user: the model spent a * round trip per step on what could be serialised (deleting balcony walls one by one, the same - * build on every floor). Inputs are checked before anything runs. + * build on every floor). Pre-check and operation refusals follow the same per-call policy. */ export function createBatchOperation( operations: Readonly>>, contracts: readonly Contract[], ): AgentOperation { - const names = Object.keys(operations).join(', ') return (nodes, { calls, onRefusal = 'stop' }, context) => { - const prepared = calls.map((call, index): PreparedCall => { - const operation = operations[call.tool] - const contract = contracts.find((candidate) => candidate.name === call.tool) - if (!(operation && contract)) - refuse( - 'unknown_tool', - `The batch's call ${index + 1} names ${call.tool}, which a batch cannot run: call it on its own. A batch runs: ${names}.`, - { index, tool: call.tool }, - ) - const parsed = z.object(contract.input).safeParse(call.input ?? {}) - if (!parsed.success) { - const message = `The batch's call ${index + 1} (${call.tool}) has an invalid input: ${parsed.error.issues - .map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`) - .join('; ')}.` - // An independent call's bad input is its own report; the others still run. - if (INDEPENDENT_BATCH_TOOLS.includes(call.tool)) - return { index, tool: call.tool, invalid: message } - refuse('invalid_input', `${message} Nothing ran.`, { index, tool: call.tool }) - } - return { index, tool: call.tool, operation, input: parsed.data } - }) - - // The gate is a fact of the tool, not of the scene: a call it refuses cannot succeed under - // either onRefusal, so the batch is refused whole before anything runs. - requireFurnishing('run_batch', { calls }, context.designBrief) - let working = nodes let workingContext = context const sets: SceneChanges[] = [] const reports: CallReport[] = [] - for (const call of prepared) { - if (call.invalid !== undefined) { - reports.push({ - index: call.index, - tool: call.tool, - status: 'refused', - code: 'invalid_input', - error: call.invalid, - }) - continue - } + for (const [index, call] of calls.entries()) { try { - const { result, changes } = call.operation(working, call.input as never, { + requireFurnishing(call.tool, call.input, context.designBrief) + const { operation, input } = prepareCall(call, index, operations, contracts) + const { result, changes } = operation(working, input as never, { ...workingContext, - batchCall: call.index, + batchCall: index, }) if (changes) { sets.push(changes) @@ -97,17 +76,17 @@ export function createBatchOperation( }, } } - reports.push({ index: call.index, tool: call.tool, status: 'ok', result }) + reports.push({ index, tool: call.tool, status: 'ok', result }) } catch (error) { if (!isAgentRefusal(error)) throw error if (onRefusal === 'stop' && !INDEPENDENT_BATCH_TOOLS.includes(call.tool)) refuse( 'batch_call_refused', - `The batch stopped at call ${call.index + 1} (${call.tool}), refused with ${error.code}: ${error.message} Nothing in the batch was applied.`, - { index: call.index, tool: call.tool, refusal: error.code, ...error.details }, + `The batch stopped at call ${index + 1} (${call.tool}), refused with ${error.code}: ${error.message} Nothing in the batch was applied.`, + { ...error.details, index, tool: call.tool, refusal: error.code }, ) reports.push({ - index: call.index, + index, tool: call.tool, status: 'refused', code: error.code, diff --git a/packages/core/src/agent-operations/design-brief.test.ts b/packages/core/src/agent-operations/design-brief.test.ts index e510656395..a1e097ae51 100644 --- a/packages/core/src/agent-operations/design-brief.test.ts +++ b/packages/core/src/agent-operations/design-brief.test.ts @@ -174,24 +174,20 @@ describe('a brief that names the catalog, a brand or existing pieces', () => { describe('run_batch', () => { const call = (tool: string, input: unknown) => ({ tool, input }) - test('one refused call refuses the batch whole, naming the call, whatever onRefusal says', () => { + test('hosts leave per-call batch refusals to the batch operation', () => { const calls = [call('paint', {}), call('place_design', { design: {} })] for (const onRefusal of ['stop', 'skip'] as const) { const refusal = furnishingRefusal('run_batch', { calls, onRefusal }, null) - expect(refusal?.code).toBe('design_brief_required') - expect(refusal?.message).toStartWith( - "The batch's call 2 (place_design) is refused: Furnishing follows", - ) - expect(refusal?.message).toEndWith('Nothing in the batch was applied.') - expect(refusal?.details).toMatchObject({ index: 1, tool: 'place_design' }) + expect(refusal).toBeNull() } }) - test('under an open brief, creation passes and a catalog placement does not', () => { + test('an open batch gate does not replace the catalog placement gate', () => { expect(code('run_batch', { calls: [call('add_object', { code: 'x' })] }, open())).toBeNull() - expect(code('run_batch', { calls: [call('place_in_room', { assetId: 'sofa' })] }, open())).toBe( - 'brief_source_open', - ) + expect( + code('run_batch', { calls: [call('place_in_room', { assetId: 'sofa' })] }, open()), + ).toBeNull() + expect(code('place_in_room', { assetId: 'sofa' }, open())).toBe('brief_source_open') }) test('a batch with no furnishing call is not gated', () => { @@ -200,14 +196,21 @@ describe('run_batch', () => { ).toBeNull() }) - test('the operation refuses before any call runs', () => { + test('the default policy rolls back a brief refusal as it does a runtime refusal', () => { const run = () => AGENT_OPERATIONS.run_batch( {}, - { calls: [{ tool: 'list_levels' }, { tool: 'place_design', input: { design: {} } }] }, + { + calls: [ + { tool: 'list_levels' }, + { tool: 'place_in_room', input: { assetId: 'sofa', zoneId: 'zone_x' } }, + ], + }, { activeLevelId: null, designBrief: null }, ) - expect(run).toThrow(/The batch's call 2 \(place_design\)/) + expect(run).toThrow( + /The batch stopped at call 2 \(place_in_room\), refused with design_brief_required/, + ) }) }) diff --git a/packages/core/src/agent-operations/design-brief.ts b/packages/core/src/agent-operations/design-brief.ts index 7873796653..a31aabcd7d 100644 --- a/packages/core/src/agent-operations/design-brief.ts +++ b/packages/core/src/agent-operations/design-brief.ts @@ -236,28 +236,13 @@ function placedAssets(tool: string, input: Record): string[] { /** * Why a furnishing call may not run under this brief, or null. `brief` null is no brief yet. An * `add_object` that names a `nodeId` edits an object that stands: it places and makes nothing. - * A batch holding a refused call is refused whole: the gate says nothing about its other calls. + * A batch checks each call in its operation, under the same policy as runtime refusals. */ export function furnishingRefusal( tool: string, input: unknown, brief: DesignBrief | null, ): AgentRefusal | null { - if (tool === 'run_batch') { - const calls = asRecord(input).calls - for (const [index, call] of (Array.isArray(calls) ? calls : []).entries()) { - const { tool: name, input: callInput } = asRecord(call) - if (typeof name !== 'string') continue - const refusal = furnishingRefusal(name, callInput, brief) - if (refusal) - return new AgentRefusal( - refusal.code, - `The batch's call ${index + 1} (${name}) is refused: ${refusal.message} Nothing in the batch was applied.`, - { ...refusal.details, index, tool: name }, - ) - } - return null - } if (!(isCatalogPlacement(tool) || isCreation(tool))) return null const args = asRecord(input) if (tool === 'add_object' && typeof args.nodeId === 'string') return null diff --git a/packages/core/src/agent-tools/batch.ts b/packages/core/src/agent-tools/batch.ts index fd54f2fa3a..8140472cb3 100644 --- a/packages/core/src/agent-tools/batch.ts +++ b/packages/core/src/agent-tools/batch.ts @@ -20,6 +20,7 @@ export const BATCHABLE_TOOLS = [ 'set_wall_type', 'add_fence', 'add_level', + 'create_unit', 'create_stair', 'add_corner_window', 'merge_windows', @@ -45,7 +46,7 @@ export const INDEPENDENT_BATCH_TOOLS: readonly string[] = ['add_object'] export const runBatchTool = { name: 'run_batch', title: 'Run a batch of scene tools', - description: `Optionally run several scene tools in one call: in order, each on the scene the calls before it left, applied as one undo step, with a report per call. Supports repeated or known-in-advance work; individual calls remain available. A call cannot use an id another call of the same batch creates; created ids are available in the report for subsequent calls. onRefusal stop (default): a refused call stops the batch and nothing is applied; skip: the others are applied and each refusal is reported; add_object calls are independent of each other under both: one that fails is reported with its own error and the others are applied, each with the receipt a single add_object gives. Tools: ${BATCHABLE_TOOLS.join(', ')}.`, + description: `Optionally run several scene tools in one call: in order, each on the scene the calls before it left, applied as one undo step, with a report per call. Supports repeated or known-in-advance work; individual calls remain available. A call cannot use an id another call of the same batch creates; created ids are available in the report for subsequent calls. onRefusal stop (default): a refused call stops the batch and nothing is applied; skip: the others are applied and each refusal is reported. This policy includes unsupported tools, invalid inputs and design-brief refusals, as well as runtime refusals. add_object calls are independent of each other under both: one that fails is reported with its own error and the others are applied, each with the receipt a single add_object gives. Tools: ${BATCHABLE_TOOLS.join(', ')}.`, input: { calls: z .array( diff --git a/packages/core/src/agent-tools/create-room.ts b/packages/core/src/agent-tools/create-room.ts index eac44344b7..18e7665310 100644 --- a/packages/core/src/agent-tools/create-room.ts +++ b/packages/core/src/agent-tools/create-room.ts @@ -25,7 +25,7 @@ export const createRoomTool = { name: 'create_room', title: 'Create room', description: - "Create a room on a level from its polygon: a wall per edge, an edge a wall already runs along reusing that wall (rooms share their boundary with their neighbour), and the room zone that names it. The floor plate and the ceiling are derived from the room — never author a slab or a ceiling for it. Declare the room's doors and windows in the same call by polygon edge (wallIndex) and t along it, no wall ids needed; each is placed with add_door's and add_window's rules, and one that cannot be is skipped and listed in skippedOpenings with its code. Returns zoneId, slabId, ceilingId, wallIds in edge order (null where no wall), doorIds, windowIds. outdoor: true draws a terrace instead: separators where no wall runs, no walls of its own and no ceiling. Where the walls already enclose a room the reconciler numbered, the call names that room instead of adding a second one; where they enclose a room with a name of its own (not a number the editor gave it), it is refused (room_named_by_person) unless rename is true, which you pass only when the person asked for the rename, so a name is never changed silently.", + "Create a room on a level from its polygon: a wall per edge, an edge a wall already runs along reusing that wall (rooms share their boundary with their neighbour), and the room zone that names it. The floor plate and the ceiling are derived from the room — never author a slab or a ceiling for it. Declare the room's doors and windows in the same call by polygon edge (wallIndex) and t along it, no wall ids needed; each is placed with add_door's and add_window's rules, and one that cannot be is skipped and listed in skippedOpenings with its code. Returns zoneId, slabId, ceilingId, wallIds in edge order (null where no wall), doorIds, windowIds. outdoor: true draws a terrace instead: separators where no wall runs, no walls of its own and no ceiling. Where the walls already enclose a room the reconciler numbered, the call names that room instead of adding a second one; where they enclose a room with a name of its own (not a number the editor gave it), it is refused (room_named_by_person) unless rename is true, which you pass only when the person asked for the rename, so a name is never changed silently. Not available in run_batch: the result needs the floor plate and ceiling derived by the host after reconciliation.", input: { ...levelTarget, name: z.string().min(1).describe('Room name, e.g. "Bedroom", "Kitchen".'), diff --git a/packages/core/src/agent-tools/wall-openings.ts b/packages/core/src/agent-tools/wall-openings.ts index 4a64913d96..cd913a6569 100644 --- a/packages/core/src/agent-tools/wall-openings.ts +++ b/packages/core/src/agent-tools/wall-openings.ts @@ -58,7 +58,7 @@ export const addDoorTool = { name: 'add_door', title: 'Add door', description: - 'Add a door to an existing straight wall at t (0..1 along it), or a passage with no leaf (openingKind opening: a cased opening, an arch). The door slides to stay on the wall and reports clamped. On a railing (wallType railing) it is a gap in the guard as tall as the railing, with no leaf, casing or threshold. Refused with a code, as in the editor: curved walls, walls shorter than the door, and overlapping another door, window or wall item unless force is set. Match the reference with the outline (rectangle, rounded, arch), doorType and style; what they cannot express (glass strips, a pattern of lites, carved panels) is written as a script in code, never left as not possible.', + 'Add a door to an existing straight wall at t (0..1 along it), or a passage with no leaf (openingKind opening: a cased opening, an arch). The door slides to stay on the wall and reports clamped. On a railing (wallType railing) it is a gap in the guard as tall as the railing, with no leaf, casing or threshold. Refused with a code, as in the editor: curved walls, walls shorter than the door, and overlapping another door, window or wall item unless force is set. Match the reference with the outline (rectangle, rounded, arch), doorType and style; what they cannot express (glass strips, a pattern of lites, carved panels) is written as a script in code, never left as not possible. Not available in run_batch: the host opening executor prepares scripted creation and rebuilds, which a batch does not prepare.', input: { wallId: NodeId.optional().describe('The wall to add the door to.'), nodeId: NodeId.optional().describe( @@ -106,7 +106,7 @@ export const addWindowTool = { name: 'add_window', title: 'Add window', description: - "Add a window to an existing straight wall at t (0..1 along it), centred vertically on the wall, or on sillHeight above the floor when given. It slides to stay on the wall and under the wall's ceiling, and reports clamped. Refused with a code, as in the editor: curved walls, railings (railing_window: a railing takes a door, a gap in its guard), walls shorter than the window, overlapping another door, window or wall item unless force is set, and a style on a window that is not Fixed (style_needs_fixed_window). Match the reference with the outline (rectangle, rounded, arch), windowType and panes (columns × rows, or a style); what they cannot express (glass strips, leaded lites, a feature frame) is written as a script in code, never left as not possible.", + "Add a window to an existing straight wall at t (0..1 along it), centred vertically on the wall, or on sillHeight above the floor when given. It slides to stay on the wall and under the wall's ceiling, and reports clamped. Refused with a code, as in the editor: curved walls, railings (railing_window: a railing takes a door, a gap in its guard), walls shorter than the window, overlapping another door, window or wall item unless force is set, and a style on a window that is not Fixed (style_needs_fixed_window). Match the reference with the outline (rectangle, rounded, arch), windowType and panes (columns × rows, or a style); what they cannot express (glass strips, leaded lites, a feature frame) is written as a script in code, never left as not possible. Not available in run_batch: the host opening executor prepares scripted creation and rebuilds, which a batch does not prepare.", input: { wallId: NodeId.optional().describe('The wall to add the window to.'), nodeId: NodeId.optional().describe( diff --git a/packages/mcp/src/tools/add-object-batch.test.ts b/packages/mcp/src/tools/add-object-batch.test.ts index 1aeb01631c..bec828cc8c 100644 --- a/packages/mcp/src/tools/add-object-batch.test.ts +++ b/packages/mcp/src/tools/add-object-batch.test.ts @@ -124,6 +124,55 @@ describe('add_object in run_batch over MCP', () => { (node) => node.type === 'item' && names.includes(node.name ?? ''), ) + test('an open-source refusal leaves the authored objects standing in one undo step', async () => { + const brief = bridge.agentSession.read().designBrief + if (!brief) throw new Error('Expected the fixture brief') + bridge.agentSession.keep({ designBrief: { ...brief, source: 'open' } }) + bridge.clearHistory() + const before = structuredClone(bridge.getNodes()) + await connect(host) + const result = (await client.callTool({ + name: 'run_batch', + arguments: { + onRefusal: 'skip', + calls: [ + object('Oak table'), + { tool: 'place_in_room', input: { assetId: 'bench', zoneId: 'zone_x' } }, + object('Side table'), + ], + }, + })) as Result + const text = result.content[0]?.text + if (!text) throw new Error('Expected a batch report') + expect(JSON.parse(text)).toMatchObject({ + applied: 2, + refused: 1, + calls: [{ status: 'ok' }, { status: 'refused', code: 'brief_source_open' }, { status: 'ok' }], + }) + expect(compiles).toHaveLength(2) + expect(itemsNamed('Oak table', 'Side table')).toHaveLength(2) + expect(bridge.getHistory()).toEqual({ pastCount: 1, futureCount: 0 }) + bridge.undo() + expect(bridge.getNodes()).toEqual(before) + }) + + test('a missing brief refuses an independent object before compilation and still runs the other calls', async () => { + bridge.agentSession.replace({ checkpoints: {}, made: [] }) + await connect(host) + const result = (await client.callTool({ + name: 'run_batch', + arguments: { calls: [object('Oak table'), { tool: 'list_levels' }], onRefusal: 'skip' }, + })) as Result + const text = result.content[0]?.text + if (!text) throw new Error('Expected a batch report') + expect(JSON.parse(text)).toMatchObject({ + applied: 1, + refused: 1, + calls: [{ status: 'refused', code: 'design_brief_required' }, { status: 'ok' }], + }) + expect(compiles).toHaveLength(0) + }) + test('three objects, one failing: two are placed, the third reports its own error', async () => { await connect(host) const result = (await client.callTool({ diff --git a/packages/mcp/src/tools/design-brief.test.ts b/packages/mcp/src/tools/design-brief.test.ts index 5ec6d43849..307e6b03d3 100644 --- a/packages/mcp/src/tools/design-brief.test.ts +++ b/packages/mcp/src/tools/design-brief.test.ts @@ -325,29 +325,73 @@ describe('the design brief over MCP', () => { ).toBeFalsy() }) - test('run_batch holding a gated call is refused as a whole, whatever onRefusal says, and nothing is applied', async () => { - const before = Object.keys(bridge.getNodes()).length + test('run_batch keeps the brief gate: stop applies nothing, skip applies the other calls, and furnishing runs only after a brief', async () => { + const before = structuredClone(bridge.getNodes()) + const [firstWall, secondWall] = Object.values(before).filter((node) => node.type === 'wall') + if (!(firstWall && secondWall)) throw new Error('The room needs two walls to delete') + const gatedCall = { tool: 'place_design', input: sofa() } const calls = [ - { tool: 'delete_node', input: { id: 'wall_missing' } }, - { tool: 'place_design', input: sofa() }, + { tool: 'delete_node', input: { id: firstWall.id } }, + gatedCall, + { tool: 'delete_node', input: { id: secondWall.id } }, ] - for (const onRefusal of ['stop', 'skip'] as const) { - const { result, payload } = await call('run_batch', { calls, onRefusal }) + for (const policy of [{}, { onRefusal: 'stop' }]) { + const { result, payload } = await call('run_batch', { calls, ...policy }) expect(result.isError).toBe(true) - expect(payload.code).toBe('design_brief_required') - expect(String(payload.error)).toContain("The batch's call 2 (place_design) is refused") + expect(payload).toMatchObject({ + code: 'batch_call_refused', + index: 1, + tool: 'place_design', + refusal: 'design_brief_required', + }) + expect(bridge.getNodes()).toEqual(before) } - expect(Object.keys(bridge.getNodes()).length).toBe(before) + const skipped = await call('run_batch', { calls, onRefusal: 'skip' }) + expect(skipped.result.isError).toBeFalsy() + expect(skipped.payload).toMatchObject({ + status: 'applied', + applied: 2, + refused: 1, + calls: [ + { index: 0, tool: 'delete_node', status: 'ok' }, + { + index: 1, + tool: 'place_design', + status: 'refused', + code: 'design_brief_required', + error: expect.stringContaining('design_brief records what the request fixes'), + }, + { index: 2, tool: 'delete_node', status: 'ok' }, + ], + }) + expect(bridge.getNodes()[firstWall.id]).toBeUndefined() + expect(bridge.getNodes()[secondWall.id]).toBeUndefined() + expect( + Object.values(bridge.getNodes()).filter((node) => + ['item', 'procedural-item'].includes(node.type), + ), + ).toEqual([]) + expect(compiles).toBe(0) + expect(bridge.agentSession.read().designBrief).toBeUndefined() + await call('design_brief', brief('open')) const batch = await call('run_batch', { - calls: [calls[1]!, { tool: 'add_object', input: object }], + calls: [gatedCall, { tool: 'add_object', input: object }], }) expect(batch.result.isError).toBeFalsy() expect(batch.payload).toMatchObject({ status: 'applied', applied: 2, refused: 0 }) + expect(compiles).toBe(1) + expect(Object.values(bridge.getNodes()).some((node) => node.type === 'procedural-item')).toBe( + true, + ) const refused = await call('run_batch', { calls: [{ tool: 'place_in_room', input: { assetId: 'double-bed', zoneId } }], }) - expect(refused.payload.code).toBe('brief_source_open') + expect(refused.result.isError).toBe(true) + expect(refused.payload).toMatchObject({ + code: 'batch_call_refused', + refusal: 'brief_source_open', + }) }) test('the brief is the session’s: the next brief replaces it, a scene load starts the session anew', async () => { diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index 68619432eb..7f20635e36 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -732,7 +732,9 @@ export function registerOperationTool( typeof call === 'object' && call !== null && 'tool' in call && - call.tool === placeInRoomTool.name, + call.tool === placeInRoomTool.name && + (designBrief === undefined || + !furnishingRefusal(call.tool, 'input' in call ? call.input : {}, designBrief)), ) const batchesObjects = tool.contract.name === runBatchTool.name && @@ -760,6 +762,7 @@ export function registerOperationTool( batchObjects: await buildBatchObjects( input.calls as { tool?: unknown; input?: unknown }[], hosts.buildObject ?? refuseScripts, + designBrief, ), }), } diff --git a/skills/pascal-3d/SKILL.md b/skills/pascal-3d/SKILL.md index dc5e2515da..98e853f095 100644 --- a/skills/pascal-3d/SKILL.md +++ b/skills/pascal-3d/SKILL.md @@ -59,7 +59,7 @@ For construction, prefer tools such as `create_story_shell`, `create_room`, `add A building of several dwellings or tenancies (a condo, an apartment building, a duplex, a hotel, shops under flats) groups its rooms into units, one per dwelling, suite or lot: once the rooms exist, `create_unit` names one as a person would (Apartment 2B, Suite 301, Shop 1; `kind` apartment, hotel-room, commercial or common) with the zone ids of its rooms, on any level (a duplex spans two), `set_unit_members` replaces them, and `list_units` reads them with their areas. A zone is in one unit at most (`zone_in_other_unit` names the unit that holds it; `move: true` moves it), a zone in no unit is common area (corridors, the lobby, the stairs), and a single-family house has no units. -Furnishings follow a design brief. `design_brief` records the request once: what it fixes, what it leaves open, where the objects come from (`source`: `open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open and, with an open source, the catalog pieces placed as they are (`asIs`, each with a reason). Before one, `search_assets` and `view_assets` read the catalog; `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` are refused (`design_brief_required`), inside `run_batch` too, and a batch holding such a call is refused whole. Source `open` opens the made pieces, places a catalog piece only when named in `asIs`, and keeps `furnish_room`, which places a whole stock set, closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. +Furnishings follow a design brief. `design_brief` records the request once: what it fixes, what it leaves open, where the objects come from (`source`: `open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open and, with an open source, the catalog pieces placed as they are (`asIs`, each with a reason). Before one, `search_assets` and `view_assets` read the catalog; `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` are refused (`design_brief_required`), inside `run_batch` too, where each call is checked under the batch's `onRefusal` policy. Source `open` opens the made pieces, places a catalog piece only when named in `asIs`, and keeps `furnish_room`, which places a whole stock set, closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. To give a surface a finish, call `paint` as the editor's Paint does: the targets, a `role` when it is not the default surface (a wall's `exterior` or `interior` face, a slot, a roof's `top`, `edge` or `wall`), and one finish: a library material whose `library:` you found with `search_materials`, a `color` (painted with the nearest library colour, or exactly with `exact: true`), or a native material for an exact finish, kept as a scene material and reused when an equal one exists; a textured one takes its `repeat`, an `offset` that lines its joints up, and normal and bump maps. An unknown target, role or material refuses the whole call and nothing is painted. diff --git a/wiki/architecture/agent-surfaces.md b/wiki/architecture/agent-surfaces.md index 88eabd94d0..15020ca11b 100644 --- a/wiki/architecture/agent-surfaces.md +++ b/wiki/architecture/agent-surfaces.md @@ -115,7 +115,7 @@ Views are planned on the site: a building's position and yaw move and turn the b **Inside a room.** `interior: { zoneId }` stands the eye in a room (a zone) at a person's height (1.6 m above its floor, or `eyeHeight`), a step in from the corner farthest from what it looks at (`from` picks the corner on that side; a `target` is looked at), never inside or within 0.3 m of a floor piece standing through the eye's height (a wardrobe, a fridge, a bookcase: the step goes further in, else another corner is taken; a bed or a counter under the eye does not move it), with a 75° field of view (`fov`), looking level across the room at its far wall. The floor is cut as for `levelId`, and the plan hands the host the level id and the room id (`roomId`), which only the note reads: `sceneViewNote` says the eye stands inside the room when it does. `position`, `elevation`, `from: 'above'` or `projection: 'orthographic'` keep the cut room seen from outside, framed on the room. `interior` takes one of `levelId` and `zoneId` (`interior_one_of`); a zone with no floor or outline is `interior_room_invalid`. The chat, the MCP and the hosted MCP share it through `sceneViewPlan`; `furnish_room` names it in its description and in the result for a room given by `zoneId`. -**Objects in a batch.** `run_batch` runs `add_object` calls. A compile is async and the operations are sync, so the host builds every add_object module first (`buildBatchObjects`, three compiles at a time, with the same compile its lone `add_object` uses) and hands the results to the batch in `AgentContext.batchObjects`; `addObjectInBatch` places each, with the receipt a lone call gives (`achieved` per object). `add_object` is in `INDEPENDENT_BATCH_TOOLS`: a module that fails (`script_failed`), a missing reason, an invalid input or a refused placement is that call's own report, whatever `onRefusal` says, and the other objects are applied. A refusal of another tool in the same batch still stops it and applies nothing. A host that built nothing answers `object_not_built` (the chat builds through `executeRunBatch`, the MCP through `registerOperationTool`'s `buildObject` host). +**Objects in a batch.** `run_batch` runs `add_object` calls. A compile is async and the operations are sync, so the host builds every permitted add_object module first (`buildBatchObjects`, three compiles at a time, with the same compile its lone `add_object` uses) and hands the results to the batch in `AgentContext.batchObjects`; `addObjectInBatch` places each, with the receipt a lone call gives (`achieved` per object). `add_object` is in `INDEPENDENT_BATCH_TOOLS`: a module that fails (`script_failed`), a missing reason, an invalid input or a refused placement is that call's own report, whatever `onRefusal` says, and the other objects are applied. Every other tool's refusal follows `onRefusal`: `stop` (default) applies nothing, `skip` reports the refusal and applies the other calls. Unsupported tools, invalid inputs and brief refusals follow this same policy. A host that built nothing answers `object_not_built` (the chat builds through `executeRunBatch`, the MCP through `registerOperationTool`'s `buildObject` host). **Inside a floor.** `interior: { levelId }` looks into one floor. The plan checks the level (`interior_level_invalid`, also for a level holding only roofs and ceilings; `interior_hidden` for a hidden level or ancestor, a hidden site excepted, since it hides only its ground; `interior_transform_unsupported` for a tipped building) and that a target is on it and in the picture (`interior_target_elsewhere`, also for its roofs and ceilings), frames the floor from 55° above unless a target, an eye or a camera is given, and hands the host only the level id. The editor that renders it works out the rest from its own scene with `sceneViewInterior`: for that one render the other floors and this floor's roofs and ceilings are hidden, everything on the floor (walls, openings, furniture) and its shadows are cut at 0.65 of the storey height, its walls are drawn whole whatever the user's wall mode, and the user's solo and isolation are lifted on it. Everything is put back right after the render, so the live view does not change. @@ -129,7 +129,7 @@ One check for every surface: `verify_scene` (`verifyScene` in core) reports per `design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; over MCP an axis quote is required and not compared, there being no message), the eighth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and, for an open source, `asIs` (technical equipment only: sanitaryware, kitchen and laundry appliances, fixed services; each piece shown by `view_assets` earlier in the turn or session, `SessionRecord.viewed`, each with a reason; furniture is made: `brief_as_is_furniture`, `brief_as_is_not_viewed`). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. -The gate is a fact of the furnishing tools, in core: `furnishingRefusal(tool, input, brief)` refuses `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` before a brief (`design_brief_required`); under an open brief it refuses the catalog's placements except the `asIs` pieces and all of `furnish_room`, which places a whole stock set (`brief_source_open`); a catalog, brand or existing source opens everything. `run_batch` is refused whole when one call is refused, whatever `onRefusal` says, before any call runs. Reading the catalog (`search_assets`, `view_assets`), rooms, walls, openings and finishes are never gated, and neither is an `add_object` that edits a standing object (`nodeId`). The operations of the gated tools refuse when the host lends `AgentContext.designBrief` (`null` while there is none, left out where the host does not gate); a host with an async step in front (the compile of an object) asks `furnishingRefusal` first. +The gate is a fact of the furnishing tools, in core: `furnishingRefusal(tool, input, brief)` refuses `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` before a brief (`design_brief_required`); under an open brief it refuses the catalog's placements except the `asIs` pieces and all of `furnish_room`, which places a whole stock set (`brief_source_open`); a catalog, brand or existing source opens everything. `run_batch` checks the gate per call under its usual refusal policy, not as a whole-batch host pre-check. Refused objects are not compiled and refused catalog placements do not read the library. Reading the catalog (`search_assets`, `view_assets`), rooms, walls, openings and finishes are never gated, and neither is an `add_object` that edits a standing object (`nodeId`). The operations of the gated tools refuse when the host lends `AgentContext.designBrief` (`null` while there is none, left out where the host does not gate); a host with an async step in front (the compile of an object) asks `furnishingRefusal` first. The brief lives where the host keeps the agent's session (`SessionRecord.designBrief`): over MCP, the bridge's session (`briefInForce`), which a scene load or clear starts anew; a bridge that keeps no session gates nothing. The hosted chat keeps it in the thread's session for the turn (the chat clears it when a new user turn starts) and gates only the scene agent's calls. From f83cfd544b22156aea09185903861959bbe6ddfa Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 18:16:08 +0100 Subject: [PATCH 11/40] The room checks name no tool this repository lacks The skirting and wet-room findings told the model to call set_wall_trim and dress_room, which this repository does not have, and two comments named tools it does not carry. The findings now state the fix as a fact: skirting is the skirting field of the wall, and the wet room is tiled to 1.20 m on the walls its fixtures stand against and to the ceiling around its shower. The comments name what is here. Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/agent-operations/reachability.ts | 2 +- packages/core/src/agent-operations/room-checks.test.ts | 6 ++---- packages/core/src/agent-operations/room-checks.ts | 10 ++++------ packages/core/src/building/code-profile.ts | 2 +- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/packages/core/src/agent-operations/reachability.ts b/packages/core/src/agent-operations/reachability.ts index 022bfd0b98..5efb8a8f38 100644 --- a/packages/core/src/agent-operations/reachability.ts +++ b/packages/core/src/agent-operations/reachability.ts @@ -123,7 +123,7 @@ function stairLevelIds(nodes: SceneNodes, id: string): string[] { } /** - * The one reading of reach that describe_circulation and verify_scene share: what is reached from + * The one reading of reach that verify_scene and the circulation findings share: what is reached from * any entrance, what is unmeasured, and, per level, whether an entrance reaches it at all. */ export function circulationReach( diff --git a/packages/core/src/agent-operations/room-checks.test.ts b/packages/core/src/agent-operations/room-checks.test.ts index 22b04ee9ba..4a47f1f1aa 100644 --- a/packages/core/src/agent-operations/room-checks.test.ts +++ b/packages/core/src/agent-operations/room-checks.test.ts @@ -67,9 +67,7 @@ describe('a wet room owes tile on its walls', () => { ], ])('%s does not make a wet room tiled', (_, spec, lead) => { expect(wet(spec)?.message).toContain(lead) - expect(wet(spec)?.message).toContain( - "dress_room ({ zoneIds: ['zone_0'], layers: [{ kind: 'tiles'", - ) + expect(wet(spec)?.message).toContain('tile its walls to 1.20 m') }) test.each([ @@ -94,7 +92,7 @@ describe('a wet room owes tile on its walls', () => { test('a shower whose surround stops at 1.2 m is named, with the call that tiles around it', () => { const issue = wet(room({ regions: [{ v1: 1.2, finish: TILE }], pieces: [SHOWER] })) expect(issue?.message).toContain('not to the ceiling around its shower (Douche)') - expect(issue?.message).toContain("to: 'full', where: { around: ['item_0_0'] }") + expect(issue?.message).toContain('tile the walls around Douche to the ceiling') }) test('the walls read are those the fixtures stand against, else all of them', () => { diff --git a/packages/core/src/agent-operations/room-checks.ts b/packages/core/src/agent-operations/room-checks.ts index 76b73450ff..77151fa967 100644 --- a/packages/core/src/agent-operations/room-checks.ts +++ b/packages/core/src/agent-operations/room-checks.ts @@ -60,8 +60,6 @@ export function wetRoomIssues(rooms: readonly RoomReading[]): RoomCheckIssue[] { const wet = room.wet if (wet?.verdict !== 'no' || !isWetRoomUse(room.use)) return [] const where = wet.byFixtures ? 'the walls its fixtures stand against' : 'its walls' - const dress = (layer: string) => - `dress_room ({ zoneIds: ['${room.id}'], layers: [{ kind: 'tiles', finish: '', ${layer} }] }) lays it` const bareShower = wet.showers.find((shower) => shower.full === 'no') const [lead, fix] = wet.tiled === 'no' @@ -71,11 +69,11 @@ export function wetRoomIssues(rooms: readonly RoomReading[]): RoomCheckIssue[] { : wet.tiledTo && wet.tiledTo > 0.05 ? `has tile up to ${metres(wet.tiledTo)} on ${where}` : `has tile on part of ${where}, along less than most of their length`, - dress(`to: ${WET_TILED_TO_M}`), + `tile ${where} to ${metres(WET_TILED_TO_M)}`, ] : [ `is tiled to ${metres(WET_TILED_TO_M)} but not to the ceiling around its shower (${bareShower?.name})`, - dress(`to: 'full', where: { around: ['${bareShower?.id}'] }`), + `tile the walls around ${bareShower?.name} to the ceiling`, ] return [ { @@ -112,13 +110,13 @@ export function skirtingIssue(rooms: readonly RoomReading[]): RoomCheckIssue | n ? null : { type: 'rooms_no_skirting', - message: `No room of the scene has skirting: ${listed(bare.map((room) => room.name))} (${bare.length}) show bare wall bases. set_wall_trim sets it ({ kind: 'skirting', zoneIds } with these rooms' ids), as does a skirting layer of dress_room, or keep the bare bases if they are intended.`, + message: `No room of the scene has skirting: ${listed(bare.map((room) => room.name))} (${bare.length}) show bare wall bases. Skirting is the skirting field of the wall: set it on the walls of these rooms, or keep the bare bases if they are intended.`, severity: 'warning', nodeIds, } return { type: 'rooms_no_skirting', - message: `${listed(bare.map((room) => room.name))} have no skirting while ${listed(skirted.map((room) => room.name))} do. set_wall_trim sets it ({ kind: 'skirting', zoneIds } with these rooms' ids), as does a skirting layer of dress_room, or keep them bare if that is intended.`, + message: `${listed(bare.map((room) => room.name))} have no skirting while ${listed(skirted.map((room) => room.name))} do. Skirting is the skirting field of the wall: set it on the walls of these rooms, or keep them bare if that is intended.`, severity: 'warning', nodeIds, } diff --git a/packages/core/src/building/code-profile.ts b/packages/core/src/building/code-profile.ts index 0ae89341b6..9062fec496 100644 --- a/packages/core/src/building/code-profile.ts +++ b/packages/core/src/building/code-profile.ts @@ -373,5 +373,5 @@ export function codeProfileOf(nodes: Readonly>): CodePr export const thresholdOf = (profile: CodeProfile, id: ThresholdId): Threshold | undefined => profile.thresholds[id] -/** The IRC value of a threshold, for a checker that is a US checker by design (Architect Pro's `design_check`). */ +/** The IRC value of a threshold, for a checker that is a US checker by design (a host's own design checker). */ export const ircValue = (id: IrcThresholdId): number => IRC_2021[id].value From 2ce38b9e6ef332ef57413bc67437f33db57161ec Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 18:37:38 +0100 Subject: [PATCH 12/40] The design brief reads the request axis by axis, form, facade and rooms included The brief had seven axes; it now has nine plus the source: form and facade join action, size, pieces, openings, style, materials and dressing. An open form states its massing (a plan, a number of volumes, one height or several), an open facade its treatment (cladding, bands, elements, rhythm), and an open form owes its rooms, one entry per room with its use, what sets it apart, its finishes and its pieces. design_brief refuses what is missing or inconsistent (form_massing_missing, form_massing_inconsistent, facade_treatment_missing, rooms_missing, room_distinct_missing, rooms_identical). verify_scene reads the brief back against the scene: form_simpler_than_brief where the volumes the rooms form are plainer than the massing stated, form_revised_simpler, facade_revised_simpler and room_dressing_revised_simpler where a later brief of the turn states less than the first, form_bounded_without_plan and rooms_not_listed where a turn built under a brief that fixes no plan or lists no rooms. The form finding names, per differing axis, what the brief stated against what is built. The session keeps the first massing, treatment and dressing, and how much the thread had made when the brief was written. Under an open source the gate no longer takes a list the model declares (asIs, each piece viewed first): the catalog's function tags and tags decide. Technical equipment (sanitaryware, appliances, fixed services) and plants are placed from the catalog; every other catalog piece is refused, naming the tools that make it and their fields, and furnish_room stays closed. A piece refused once is answered briefly the second time, by any placing tool, through a reading the session keeps; a batch carries the keep of a refused call. A stored brief that still holds asIs reads without it. Not carried, with the lots that own them: the direction axis and its roll, the style catalogue, the findings that read the built facade (facade_simpler_than_brief, facade_bounded_without_treatment), the room dressing and announced-room findings, and rooms_announced_alike. Tests: the case table (core, MCP and chat runners read it) with the form, facade revision, dressing revision and gap rows, the core and MCP brief tests, and the form finding's rows. Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/brief-gaps-cases.ts | 148 +++++ .../agent-operations/__fixtures__/cases.ts | 8 + .../__fixtures__/design-brief-cases.ts | 580 +++++++++++++++--- .../__fixtures__/design-facade-cases.ts | 87 +++ .../__fixtures__/design-form-cases.ts | 422 +++++++++++++ .../__fixtures__/room-dressing-cases.ts | 78 +++ packages/core/src/agent-operations/batch.ts | 23 +- .../src/agent-operations/brief-findings.ts | 118 ++++ .../src/agent-operations/brief-gaps.test.ts | 67 ++ .../core/src/agent-operations/brief-gaps.ts | 50 ++ .../src/agent-operations/design-brief.test.ts | 318 ++++++---- .../core/src/agent-operations/design-brief.ts | 301 ++++++--- .../agent-operations/design-facade.test.ts | 9 + .../src/agent-operations/design-facade.ts | 81 +++ .../src/agent-operations/design-form.test.ts | 80 +++ .../core/src/agent-operations/design-form.ts | 341 ++++++++++ packages/core/src/agent-operations/index.ts | 5 + .../core/src/agent-operations/massing-read.ts | 320 ++++++++++ .../agent-operations/room-dressing.test.ts | 33 + .../src/agent-operations/room-dressing.ts | 64 ++ .../src/agent-operations/room-readings.ts | 1 - .../src/agent-operations/scene-checkpoint.ts | 86 ++- .../core/src/agent-operations/verify-scene.ts | 2 +- packages/core/src/agent-tools/design-brief.ts | 256 +++++++- packages/core/src/agent-tools/refusal.ts | 5 + .../core/src/contracts/reference-inventory.ts | 9 + packages/mcp/src/prompts/scene-guidance.ts | 2 +- packages/mcp/src/resources/agent-guide.ts | 2 +- packages/mcp/src/tools/design-brief.test.ts | 150 +++-- packages/mcp/src/tools/shared-tools.ts | 34 +- 30 files changed, 3331 insertions(+), 349 deletions(-) create mode 100644 packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts create mode 100644 packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts create mode 100644 packages/core/src/agent-operations/__fixtures__/design-form-cases.ts create mode 100644 packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts create mode 100644 packages/core/src/agent-operations/brief-findings.ts create mode 100644 packages/core/src/agent-operations/brief-gaps.test.ts create mode 100644 packages/core/src/agent-operations/brief-gaps.ts create mode 100644 packages/core/src/agent-operations/design-facade.test.ts create mode 100644 packages/core/src/agent-operations/design-facade.ts create mode 100644 packages/core/src/agent-operations/design-form.test.ts create mode 100644 packages/core/src/agent-operations/design-form.ts create mode 100644 packages/core/src/agent-operations/massing-read.ts create mode 100644 packages/core/src/agent-operations/room-dressing.test.ts create mode 100644 packages/core/src/agent-operations/room-dressing.ts diff --git a/packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts b/packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts new file mode 100644 index 0000000000..ad6a164f9d --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts @@ -0,0 +1,148 @@ +import type { DesignBrief } from '../../agent-tools/design-brief' +import type { MadeEntry, SessionRecord } from '../scene-checkpoint' +import type { AgentToolCase } from './cases' +import { HOUSE_ROOMS, OPEN_AXES } from './design-brief-cases' +import { massedScene, rect } from './design-form-cases' + +/** + * What a brief leaves unstated while the turn built: a form bounded by words that fix no plan, and + * a brief that lists no rooms for a building of many. A finding at the + * end of the turn, for a turn that made zones or levels since the brief, never a refusal. + */ + +const house = () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) + +const bounded = (quote: string, reading: string) => ({ + kind: 'bounded' as const, + quote, + reading, +}) + +/** "Construis-moi une grande maison": the form and the facade bounded by words that state no plan and no treatment. */ +const GRANDE_MAISON: DesignBrief = { + axes: { + ...OPEN_AXES, + form: bounded('grande maison', 'a large house'), + facade: bounded('grande maison', 'a large house'), + }, + source: 'open', + vision: 'A large house.', + beyond: 'none: the test reads the brief.', +} + +export const zone = (id: string): MadeEntry => ({ id, type: 'zone', levelId: 'level_0' }) +const lamp: MadeEntry = { id: 'item_lamp', type: 'item', levelId: 'level_0' } + +/** The session of a turn: what the thread made before the brief, the brief, what was made under it. */ +export const underBrief = ( + designBrief: DesignBrief, + before: MadeEntry[], + under: MadeEntry[], +): SessionRecord => ({ + checkpoints: {}, + made: [...before, ...under], + designBrief, + briefMadeAt: before.length, +}) + +const keeping = (session: SessionRecord): AgentToolCase['context'] => ({ + designBrief: session.designBrief, + session: () => session, +}) + +const FORM = { type: 'form_bounded_without_plan', severity: 'warning' } +const ROOMS = { type: 'rooms_not_listed', severity: 'warning' } + +export const BRIEF_GAP_CASES: AgentToolCase[] = [ + { + name: 'a form bounded by "grande maison" while the turn built a rectangle: the finding names the words and what was built', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(underBrief(GRANDE_MAISON, [], [zone('zone_House_0')])), + expect: { + result: { hasIssues: true }, + contains: { + issues: [ + { + ...FORM, + message: + 'The brief bounds the form by "grande maison", words that fix no plan; the scene has 1 volume (rectangle).', + }, + ], + }, + }, + }, + { + name: 'a turn that made no zone or level, a lamp, says nothing of the form: the cheap statement holds', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(underBrief(GRANDE_MAISON, [], [lamp])), + expect: { result: {}, lacks: { issues: [FORM, ROOMS] } }, + }, + { + name: 'what the thread built before the brief is not the turn’s: no finding', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(underBrief(GRANDE_MAISON, [zone('zone_House_0'), zone('zone_Study_0')], [lamp])), + expect: { result: {}, lacks: { issues: [FORM, ROOMS] } }, + }, + { + name: 'a session record with no marker (before it existed) cannot tell the turn: no finding', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping({ + checkpoints: {}, + made: [zone('zone_House_0'), zone('zone_Study_0')], + designBrief: GRANDE_MAISON, + }), + expect: { result: {}, lacks: { issues: [FORM, ROOMS] } }, + }, + { + name: 'three rooms built under a brief that lists none: the finding counts them', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping( + underBrief(GRANDE_MAISON, [], [zone('zone_a'), zone('zone_b'), zone('zone_c')]), + ), + expect: { + result: {}, + contains: { issues: [ROOMS] }, + mentions: ['The brief lists no rooms; the turn built 3 rooms.'], + }, + }, + { + name: 'one room built, or the rooms listed: no rooms finding', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping( + underBrief({ ...GRANDE_MAISON, rooms: HOUSE_ROOMS }, [], [zone('zone_a'), zone('zone_b')]), + ), + expect: { result: {}, lacks: { issues: [ROOMS] } }, + }, + { + name: 'a form that states its plan is compared and not reported as unstated', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping( + underBrief( + { + ...GRANDE_MAISON, + axes: { + ...GRANDE_MAISON.axes, + form: { ...bounded('grande maison', 'a large house'), massing: { plan: 'rectangle' } }, + }, + }, + [], + [zone('zone_House_0')], + ), + ), + expect: { result: {}, lacks: { issues: [FORM] } }, + }, +] diff --git a/packages/core/src/agent-operations/__fixtures__/cases.ts b/packages/core/src/agent-operations/__fixtures__/cases.ts index 2539db18e6..a524beae46 100644 --- a/packages/core/src/agent-operations/__fixtures__/cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/cases.ts @@ -31,7 +31,11 @@ import { OUTDOOR_ROOM_READ_CASES, ROOM_CASES } from './room-cases' import { CHECK_ROOMS_CASES, VALIDATE_SCENE_CASES } from './scene-check-cases' import { SEARCH_ASSETS_CASES } from './search-assets-cases' import { VIEW_ASSETS_CASES } from './view-assets-cases' +import { BRIEF_GAP_CASES } from './brief-gaps-cases' import { DESIGN_BRIEF_CASES } from './design-brief-cases' +import { DESIGN_FACADE_CASES } from './design-facade-cases' +import { DESIGN_FORM_CASES } from './design-form-cases' +import { DESIGN_DRESSING_CASES } from './room-dressing-cases' import { CORNER_WINDOW_CASES } from './corner-window-cases' import { MERGE_WINDOWS_CASES } from './merge-windows-cases' import { DESCRIBE_NODE_CASES, FIND_NODES_CASES } from './node-read-cases' @@ -974,6 +978,10 @@ export const AGENT_TOOL_CASES: readonly AgentToolCase[] = [ ...SEARCH_ASSETS_CASES, ...VIEW_ASSETS_CASES, ...DESIGN_BRIEF_CASES, + ...DESIGN_FORM_CASES, + ...DESIGN_FACADE_CASES, + ...DESIGN_DRESSING_CASES, + ...BRIEF_GAP_CASES, ...ADD_WALL_CASES, ...WALL_TYPE_CASES, ...FRAMING_POST_CASES, diff --git a/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts index bc6b8e44c8..5947d75173 100644 --- a/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts @@ -1,6 +1,14 @@ import { DESIGN_EXAMPLE } from '../../procedural-items' import type { AssetInput } from '../../schema' -import type { Beyond, BriefAxes, DesignBrief } from '../../agent-tools/design-brief' +import type { + Beyond, + BriefAxes, + BriefRoom, + DesignBrief, + Massing, + Treatment, +} from '../../agent-tools/design-brief' +import type { SessionRecord } from '../scene-checkpoint' import type { AgentToolCase } from './cases' import { storeysScene } from './structure-cases' @@ -26,7 +34,10 @@ const CATALOG = [ piece('double-bed', 'Double bed', 'double-beds'), piece('bedside-table', 'Bedside table', 'coffee-tables'), piece('closet', 'Closet', 'wardrobes'), + piece('sofa', 'Sofa', 'sofas'), piece('toilet', 'Toilet', 'toilets'), + piece('fridge', 'Fridge', 'kitchen-appliances'), + { ...piece('palm', 'Palm', 'outdoor'), tags: ['tree', 'plant', 'garden'] }, ] const seen = (...ids: string[]) => () => ({ checkpoints: {}, made: [], viewed: ids }) const library = { activeLevelId: null, catalog: CATALOG } @@ -67,6 +78,44 @@ const bounded = (quote: string, reading: string, extent?: 'minimum' | 'exact') = ...(extent ? { extent } : {}), }) const openAxis = (design: string) => ({ kind: 'open' as const, design }) +/** An open facade states its treatment: what it is clad in or carries, and the rhythm of its openings. */ +export const openFacade = (design: string, treatment: Treatment) => ({ + kind: 'open' as const, + design, + treatment, +}) + +/** The rooms of the house an open brief designs: two of one use, each with its own line. */ +export const HOUSE_ROOMS: BriefRoom[] = [ + { + name: 'Master bedroom', + use: 'bedroom', + distinct: 'the parents’ room, calm and oak, the largest, with its own bathroom', + finishes: { floor: 'oak parquet', walls: 'limewashed white', tiled: false, skirting: true }, + pieces: ['a king bed', 'two nightstands', 'a wardrobe'], + }, + { + name: 'Children’s bedroom', + use: 'bedroom', + distinct: 'the children’s room, bright, with a desk by the window and bunk beds', + finishes: { floor: 'cork', walls: 'pale green', tiled: false, skirting: true }, + pieces: ['bunk beds', 'a desk', 'a toy chest'], + }, + { + name: 'Bathroom', + use: 'bathroom', + distinct: 'the family bathroom, tiled floor to ceiling, a bath under the window', + finishes: { floor: 'terrazzo tiles', walls: 'white zellige tiles', tiled: true, skirting: false }, + pieces: ['a bath', 'a double basin', 'a toilet'], + }, +] + +/** An open form states its massing: the plan, the volumes, whether they stand at one height. */ +export const openForm = (design: string, massing: Massing) => ({ + kind: 'open' as const, + design, + massing, +}) const BEDROOM_REQUEST = 'a 4 by 5 m bedroom with a double bed, two nightstands, a wardrobe, one window, one door' @@ -75,6 +124,8 @@ const BEDROOM_REQUEST = export const BEDROOM_AXES: BriefAxes = { action: bounded('a 4 by 5 m bedroom', 'one bedroom, not a house; inside it, making it is the job'), size: bounded('4 by 5 m', 'the room is 4 by 5 m'), + form: bounded('a 4 by 5 m bedroom', 'one room of 4 by 5 m, a rectangle; no building is designed'), + facade: bounded('a 4 by 5 m bedroom', 'one room: no building exterior is designed'), pieces: bounded( 'a double bed, two nightstands, a wardrobe', 'those pieces must be there; nothing says only, so more may come', @@ -90,6 +141,8 @@ export const BEDROOM_AXES: BriefAxes = { export const LAMP_AXES: BriefAxes = { action: bounded('add a lamp', 'one object added to a room that exists; no redecoration'), size: openAxis('the lamp sized to the sofa it stands beside'), + form: bounded('add a lamp', 'one object in a room that exists; the building stands as it is'), + facade: bounded('add a lamp', 'one object in a room that exists; the exterior stands as it is'), pieces: bounded('a lamp', 'the one lamp the request names', 'exact'), openings: openAxis('no openings are touched by this addition'), style: openAxis('a sculptural paper lamp echoing the oak sofa'), @@ -101,6 +154,8 @@ export const LAMP_AXES: BriefAxes = { const LAMP_AXES_FR: BriefAxes = { action: bounded('Ajoute une lampe', 'un seul objet ajouté à une pièce qui existe; aucune redécoration'), size: openAxis('la lampe dimensionnée selon le canapé près duquel elle se tient'), + form: bounded('Ajoute une lampe', 'un objet dans une pièce qui existe; le bâtiment reste tel qu’il est'), + facade: bounded('Ajoute une lampe', 'un objet dans une pièce qui existe; l’extérieur reste tel qu’il est'), pieces: bounded('une lampe', 'la seule lampe que la demande nomme', 'exact'), openings: openAxis('aucune ouverture n’est touchée par cet ajout'), style: openAxis('une lampe en papier sculpturale qui répond au canapé en chêne'), @@ -108,10 +163,19 @@ const LAMP_AXES_FR: BriefAxes = { dressing: bounded('Ajoute une lampe', 'la demande ajoute une lampe; la pièce n’est pas habillée davantage'), } -/** Every axis open, for the briefs whose subject is the source or the gate, not the reading. */ +/** Every axis open, for the briefs whose subject is the source or the gate, not the reading. Its open form owes `rooms`: HOUSE_ROOMS. */ export const OPEN_AXES: BriefAxes = { action: openAxis('the work the request calls for, designed as a whole'), size: openAxis('sizes chosen to fit the rooms they serve'), + form: openForm('a single block composed to fit the rooms it holds', { + plan: 'rectangle', + volumes: 1, + heights: 'one', + }), + facade: openFacade('a plain render facade with a free rhythm of windows', { + cladding: ['render'], + rhythm: 'free', + }), pieces: openAxis('the pieces each room needs, designed one by one'), openings: openAxis('openings placed for light and passage room by room'), style: openAxis('each piece designed in one calm character throughout'), @@ -125,10 +189,6 @@ const OPEN: DesignBrief = { vision: 'A calm room of oak and linen, low furniture, the bed under the window wall.', beyond: DRESSED, } -const OPEN_AS_IS: DesignBrief = { - ...OPEN, - asIs: [{ assetId: 'toilet', reason: 'technical equipment, as drawn in the catalog' }], -} const IKEA: DesignBrief = { axes: { ...OPEN_AXES, @@ -156,11 +216,24 @@ export const CATALOG_BRIEF: DesignBrief = { const ground = { levelId: 'level_ground' } const sofa = { design: DESIGN_EXAMPLE, hostId: 'level_ground', position: [3, 0, 2] } const bed = { items: [{ assetId: 'double-bed', x: 2, z: 2 }], ...ground } -const wc = { items: [{ assetId: 'toilet', x: 2, z: 2 }], ...ground } +const fridge = { items: [{ assetId: 'fridge', x: 2, z: 2 }], ...ground } +const palm = { items: [{ assetId: 'palm', x: 2, z: 2 }], ...ground } +const couch = { items: [{ assetId: 'sofa', x: 2, z: 2 }], ...ground } const BEFORE = ['design_brief records what the request fixes', 'searched and viewed, not placed'] const OPEN_SOURCE = (pieceNamed: string) => - `The brief left the source open: ${pieceNamed} can be made with add_object or place_design (view_assets shows the catalog's for reference), or, for technical equipment, named in the brief's asIs after view_assets, with a reason.` + `The brief left the source open: ${pieceNamed} cannot be placed from the catalog, pieces are made.` +/** The facts the first refusal states about the making tools: which tool, with which input. */ +const MAKING_TOOLS = [ + 'add_object makes a piece (code, or piece for the object in words; parentId and position say where it goes)', + 'place_design places a designed piece (design, hostId, position)', +] +/** What the session holds after a refusal: the pieces already refused, read back by the next call. */ +const refusedBefore = (...pieces: string[]) => (): SessionRecord => ({ + checkpoints: {}, + made: [], + readings: { 'brief.refusedPieces': pieces }, +}) export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ { @@ -172,13 +245,16 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ source: 'open', vision: OPEN.vision, beyond: OPEN.beyond, - asIs: OPEN_AS_IS.asIs, }, - context: { ...library, session: seen('toilet') }, + context: library, readOnly: true, expect: { - result: { status: 'recorded', brief: OPEN_AS_IS }, - mentions: ['add_object, place_design make the pieces', 'furnish_room places a whole stock set'], + result: { status: 'recorded', brief: OPEN }, + mentions: [ + 'add_object, place_design make the pieces', + 'furnish_room places a whole stock set', + 'place_items and place_in_room place technical equipment and plants from the catalog', + ], session: (session) => (session.designBrief?.vision === OPEN.vision ? [] : ['not kept']), }, }, @@ -188,6 +264,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ scene: storeysScene, input: { axes: IKEA.axes, + rooms: HOUSE_ROOMS, source: 'brand', sourceQuote: IKEA.sourceQuote, brand: 'IKEA', @@ -206,6 +283,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ scene: storeysScene, input: { axes: IKEA.axes, + rooms: HOUSE_ROOMS, source: 'brand', sourceQuote: IKEA.sourceQuote, vision: IKEA.vision, @@ -219,6 +297,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ scene: storeysScene, input: { axes: OPEN_AXES, + rooms: HOUSE_ROOMS, source: 'catalog', vision: 'Furnished from the catalog.', beyond: nothing('catalog'), @@ -231,6 +310,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ scene: storeysScene, input: { axes: OPEN_AXES, + rooms: HOUSE_ROOMS, source: 'catalog', sourceQuote: 'Furnished from the catalog', vision: 'Furnished from the catalog.', @@ -249,6 +329,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ scene: storeysScene, input: { axes: IKEA.axes, + rooms: HOUSE_ROOMS, source: 'brand', sourceQuote: 'IKEA furniture only', brand: 'IKEA', @@ -261,7 +342,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ expect: { result: { status: 'recorded', brief: { source: 'brand', sourceQuote: 'IKEA furniture only' } } }, }, { - name: 'view_assets records what it showed, for the brief’s asIs', + name: 'view_assets records what it showed in the session', tool: 'view_assets', scene: storeysScene, input: { ids: ['toilet'] }, @@ -272,47 +353,6 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ session: (session) => (session.viewed?.includes('toilet') ? [] : ['not kept']), }, }, - { - name: 'an open brief naming a double bed, a bedside table and a closet as they are is refused: furniture is made', - tool: 'design_brief', - scene: storeysScene, - input: { - axes: OPEN.axes, - source: 'open', - vision: OPEN.vision, - beyond: OPEN.beyond, - asIs: ['double-bed', 'bedside-table', 'closet'].map((assetId) => ({ - assetId, - reason: 'fits the room', - })), - }, - context: { ...library, session: seen('double-bed', 'bedside-table', 'closet') }, - expect: { - refusal: 'brief_as_is_furniture', - mentions: [ - 'Double bed is furniture: in an open brief furniture is made (add_object, place_design) or the request names a catalog source; asIs keeps technical equipment (sanitaryware, appliances).', - 'Bedside table is furniture', - 'Closet is furniture', - ], - }, - }, - { - name: 'an open brief keeping a toilet not viewed is refused: look first', - tool: 'design_brief', - scene: storeysScene, - input: { - axes: OPEN.axes, - source: 'open', - vision: OPEN.vision, - beyond: OPEN.beyond, - asIs: OPEN_AS_IS.asIs, - }, - context: library, - expect: { - refusal: 'brief_as_is_not_viewed', - mentions: ['toilet was not viewed', 'view_assets'], - }, - }, { name: 'a brief that adds nothing says so and why', tool: 'design_brief', @@ -322,6 +362,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ ...OPEN_AXES, dressing: bounded('catalog only', 'the request limits the pieces to the catalog'), }, + rooms: HOUSE_ROOMS, source: 'catalog', sourceQuote: 'catalog only', vision: 'The catalog as it is.', @@ -381,6 +422,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ style: openAxis('the bed and the lamp designed plainly in oak and paper'), materials: openAxis('oak, paper and plain cotton chosen for the two pieces'), }, + rooms: HOUSE_ROOMS, source: 'open', vision: 'A bed and a lamp in a plain room, both designed.', beyond: nothing('the request says only a bed and a lamp'), @@ -413,6 +455,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ pieces: bounded('only a bed and a lamp', 'a bed and a lamp'), dressing: bounded('only a bed and a lamp', 'the request limits the pieces to those two'), }, + rooms: HOUSE_ROOMS, source: 'open', vision: 'A bed and a lamp in a plain room, both designed.', beyond: nothing('the request says only a bed and a lamp'), @@ -430,6 +473,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ pieces: bounded('un lit, rien d’autre', 'a bed and nothing else', 'exact'), dressing: bounded('rien d’autre', 'the request limits the pieces to the bed'), }, + rooms: HOUSE_ROOMS, source: 'open', vision: 'A bed in a plain room.', beyond: nothing('the request says nothing else'), @@ -562,6 +606,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ action: bounded('a house', 'one house'), dressing: bounded('a house', 'read as the house alone, undressed'), }, + rooms: HOUSE_ROOMS, source: 'open', vision: 'A house, plainly built.', beyond: nothing('read as the house alone'), @@ -667,6 +712,36 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ context: { ...library, designBrief: OPEN }, expect: { refusal: 'brief_source_open', mentions: [OPEN_SOURCE('double-bed')] }, }, + { + name: 'an open brief: the first refusal says which tools make the piece and with which input', + tool: 'place_items', + scene: storeysScene, + input: bed, + context: { ...library, designBrief: OPEN }, + expect: { refusal: 'brief_source_open', mentions: MAKING_TOOLS }, + }, + { + name: 'an open brief: the same piece refused again is answered briefly, by any placing tool', + tool: 'place_in_room', + scene: storeysScene, + input: { assetId: 'double-bed', ...ground }, + context: { ...library, designBrief: OPEN, session: refusedBefore('double-bed') }, + expect: { + refusal: 'brief_source_open', + mentions: ["Already refused, the brief's source is open: double-bed."], + }, + }, + { + name: 'an open brief: a call naming a piece refused before and a new one gives the facts for the new one only', + tool: 'place_items', + scene: storeysScene, + input: { items: [...couch.items, ...bed.items], ...ground }, + context: { ...library, designBrief: OPEN, session: refusedBefore('sofa') }, + expect: { + refusal: 'brief_source_open', + mentions: [OPEN_SOURCE('double-bed'), ' Already refused: sofa.'], + }, + }, { name: 'an open brief: furnish_room, which places a whole stock set, stays closed', tool: 'furnish_room', @@ -679,20 +754,28 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ }, }, { - name: 'an open brief: a catalog piece named in asIs is placed as it is', + name: 'an open brief: a fridge and a palm are placed from the catalog', tool: 'place_items', scene: storeysScene, - input: wc, - context: { ...library, designBrief: OPEN_AS_IS }, + input: { items: [...fridge.items, ...palm.items], ...ground }, + context: { ...library, designBrief: OPEN }, expect: { result: { ok: true, levelId: 'level_ground' } }, }, { - name: 'an open brief: asIs lets that piece through and still refuses the others of the call', + name: 'an open brief: a sofa and a bed in one call are both listed in the refusal', tool: 'place_items', scene: storeysScene, - input: { items: [...wc.items, ...bed.items], ...ground }, - context: { ...library, designBrief: OPEN_AS_IS }, - expect: { refusal: 'brief_source_open', mentions: [OPEN_SOURCE('double-bed')] }, + input: { items: [...couch.items, ...bed.items], ...ground }, + context: { ...library, designBrief: OPEN }, + expect: { refusal: 'brief_source_open', mentions: [OPEN_SOURCE('sofa, double-bed')] }, + }, + { + name: 'a brand brief opens the catalog: the toilet is placed', + tool: 'place_items', + scene: storeysScene, + input: { items: [{ assetId: 'toilet', x: 2, z: 2 }], ...ground }, + context: { ...library, designBrief: IKEA }, + expect: { result: { ok: true, levelId: 'level_ground' } }, }, { name: 'a brand brief opens the catalog: the double bed is placed', @@ -737,43 +820,372 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ }, }, { - name: 'stop names the refused catalog call and applies nothing', - tool: 'run_batch', + name: 'a brief with no form axis is refused, the absent axis named', + tool: 'design_brief', scene: storeysScene, input: { - calls: [ - { tool: 'place_design', input: sofa }, - { tool: 'place_in_room', input: { assetId: 'double-bed', polygon: [[0, 0], [4, 0], [4, 5], [0, 5]], ...ground } }, + axes: { ...BEDROOM_AXES, form: undefined }, + source: 'open', + vision: 'A calm room of oak and linen.', + beyond: DRESSED, + }, + expect: { refusal: 'axis_missing', mentions: ['form is absent'] }, + }, + { + name: 'an open form with no massing is refused, the fields named', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { ...OPEN_AXES, form: openAxis('a house composed of volumes around a forecourt') }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A house around its forecourt.', + beyond: DRESSED, + }, + expect: { + refusal: 'form_massing_missing', + mentions: ['plan, volumes, heights are absent'], + }, + }, + { + name: 'an open form that states only its plan is refused for the fields it leaves out', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + form: openForm('a house composed of volumes around a forecourt', { plan: 'u' }), + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A house around its forecourt.', + beyond: DRESSED, + }, + expect: { refusal: 'form_massing_missing', mentions: ['volumes, heights are absent'] }, + }, + { + name: 'a form of one volume stated as detached is refused', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + form: openForm('a house composed of volumes around a forecourt', { + plan: 'detached', + volumes: 1, + heights: 'one', + }), + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A house around its forecourt.', + beyond: DRESSED, + }, + expect: { refusal: 'form_massing_inconsistent', mentions: ['one volume cannot be detached'] }, + }, + { + name: '"Build a house" with the form open states its massing and is recorded with it', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + form: openForm('a two-storey body with a lower wing at each end, around a forecourt', { + plan: 'u', + volumes: 3, + heights: 'several', + }), + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A house around its forecourt.', + beyond: DRESSED, + }, + expect: { + result: { + status: 'recorded', + brief: { + axes: { + form: { kind: 'open', massing: { plan: 'u', volumes: 3, heights: 'several' } }, + }, + }, + }, + }, + }, + { + name: '"an L-shaped house" bounds the form by the person’s words, the plan they fix stated', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + action: bounded('an L-shaped house', 'a house, L-shaped'), + form: { ...bounded('an L-shaped house', 'the plan is an L'), massing: { plan: 'l' } }, + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'An L-shaped house around a terrace.', + beyond: DRESSED, + }, + context: { requestText: 'Build me an L-shaped house' }, + expect: { + result: { + status: 'recorded', + brief: { axes: { form: { kind: 'bounded', massing: { plan: 'l' } } } }, + }, + }, + }, + { + name: 'a form bounded by words that are not in the person’s message is refused', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { ...OPEN_AXES, form: bounded('a U-shaped house', 'the plan is a U') }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A house around its forecourt.', + beyond: DRESSED, + }, + context: { requestText: 'Build me a house' }, + surfaces: ['core', 'chat'], + expect: { refusal: 'axis_quote_not_in_request' }, + }, + { + name: 'an open form owes its rooms: a house with none is refused', + tool: 'design_brief', + scene: storeysScene, + input: { axes: OPEN_AXES, source: 'open', vision: 'A calm house.', beyond: DRESSED }, + expect: { refusal: 'rooms_missing', mentions: ['rooms lists each room it builds'] }, + }, + { + name: 'an open form with an empty list of rooms is refused too', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: OPEN_AXES, + rooms: [], + source: 'open', + vision: 'A calm house.', + beyond: DRESSED, + }, + expect: { refusal: 'rooms_missing' }, + }, + { + name: 'a room with no distinct line is refused, the room named', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: OPEN_AXES, + rooms: [HOUSE_ROOMS[0], { ...HOUSE_ROOMS[1], distinct: undefined }], + source: 'open', + vision: 'A calm house.', + beyond: DRESSED, + }, + expect: { refusal: 'room_distinct_missing', mentions: ['The room "Children’s bedroom"'] }, + }, + { + name: 'a room whose distinct line is blank is refused like one with none', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: OPEN_AXES, + rooms: [{ ...HOUSE_ROOMS[0], distinct: ' ' }], + source: 'open', + vision: 'A calm house.', + beyond: DRESSED, + }, + expect: { refusal: 'room_distinct_missing' }, + }, + { + name: 'two rooms of one use with the same distinct line and the same pieces, in any order, are refused as copies', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: OPEN_AXES, + rooms: [ + HOUSE_ROOMS[0], + { + ...HOUSE_ROOMS[0], + name: 'Guest bedroom', + distinct: HOUSE_ROOMS[0]!.distinct!.toUpperCase(), + pieces: [...HOUSE_ROOMS[0]!.pieces].reverse(), + }, ], + source: 'open', + vision: 'A calm house.', + beyond: DRESSED, }, - context: { ...library, designBrief: OPEN }, expect: { - refusal: 'batch_call_refused', - mentions: ['call 2', 'place_in_room', 'brief_source_open', OPEN_SOURCE('double-bed')], + refusal: 'rooms_identical', + mentions: ['The rooms "Master bedroom" and "Guest bedroom" are of one use'], }, }, { - name: 'skip runs the calls around an unsupported tool and an invalid input', - tool: 'run_batch', + name: 'two rooms of one use with the same distinct line but their own pieces are recorded: anything subtler is a finding at the end of the turn', + tool: 'design_brief', scene: storeysScene, input: { - calls: [ - { tool: 'list_levels' }, - { tool: 'run_batch', input: { calls: [] } }, - { tool: 'delete_node', input: {} }, - { tool: 'list_levels' }, + axes: OPEN_AXES, + rooms: [ + HOUSE_ROOMS[0], + { ...HOUSE_ROOMS[0], name: 'Guest bedroom', pieces: ['a sofa bed', 'a reading chair'] }, ], - onRefusal: 'skip', + source: 'open', + vision: 'A calm house.', + beyond: DRESSED, + }, + expect: { result: { status: 'recorded', brief: { rooms: [{ name: 'Master bedroom' }, { name: 'Guest bedroom' }] } } }, + }, + { + name: 'a focused refit of two rooms bounds the form by its words and still lists the rooms: they are kept with the brief', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: LAMP_AXES, + rooms: [HOUSE_ROOMS[0], HOUSE_ROOMS[2]], + source: 'open', + vision: 'Two rooms refitted.', + beyond: nothing('the request refits two rooms'), + }, + context: { requestText: 'add a lamp next to the sofa' }, + expect: { + result: { status: 'recorded', brief: { rooms: [{ use: 'bedroom' }, { use: 'bathroom' }] } }, + session: (session) => + session.designBrief?.rooms?.length === 2 ? [] : ['the rooms were not kept with the brief'], + }, + }, + { + name: 'a brief with no facade axis is refused, the absent axis named', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { ...BEDROOM_AXES, facade: undefined }, + source: 'open', + vision: 'A calm room of oak and linen.', + beyond: DRESSED, + }, + expect: { refusal: 'axis_missing', mentions: ['facade is absent'] }, + }, + { + name: 'an open facade with no treatment is refused, the fields named', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { ...OPEN_AXES, facade: openAxis('a stone manor with shuttered windows') }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A manor.', + beyond: DRESSED, + }, + expect: { + refusal: 'facade_treatment_missing', + mentions: ['Absent: cladding or elements, rhythm.'], + }, + }, + { + name: 'an open facade that states cladding but no rhythm is refused for the rhythm', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + facade: openFacade('a stone manor with shuttered windows', { cladding: ['stone'] }), + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A manor.', + beyond: DRESSED, + }, + expect: { refusal: 'facade_treatment_missing', mentions: ['Absent: rhythm.'] }, + }, + { + name: 'an open facade that states a rhythm but carries nothing is refused too', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + facade: openFacade('a stone manor with shuttered windows', { rhythm: 'regular' }), + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A manor.', + beyond: DRESSED, + }, + expect: { refusal: 'facade_treatment_missing', mentions: ['Absent: cladding or elements.'] }, + }, + { + name: '"Build a house" with the facade open states its treatment and is recorded with it', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + facade: openFacade('a stone facade dressed with quoins, its windows shuttered', { + cladding: ['stone'], + bands: ['base', 'cornice'], + elements: ['corners', 'shutters'], + rhythm: 'regular', + }), + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A manor.', + beyond: DRESSED, + }, + expect: { + result: { + status: 'recorded', + brief: { + axes: { + facade: { + kind: 'open', + treatment: { cladding: ['stone'], rhythm: 'regular' }, + }, + }, + }, + }, + }, + }, + { + name: '"une façade en pierre avec volets" bounds the facade by the person’s words, the treatment they fix stated', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: { + ...OPEN_AXES, + facade: { + ...bounded('une façade en pierre avec volets', 'stone and shutters'), + treatment: { cladding: ['stone'], elements: ['shutters'] }, + }, + }, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A stone house.', + beyond: DRESSED, }, + context: { requestText: 'Construis-moi une maison avec une façade en pierre avec volets' }, expect: { - result: { applied: 2, refused: 2 }, - contains: { - calls: [ - { index: 1, tool: 'run_batch', status: 'refused', code: 'unknown_tool' }, - { index: 2, tool: 'delete_node', status: 'refused', code: 'invalid_input' }, - { index: 3, tool: 'list_levels', status: 'ok' }, - ], + result: { + status: 'recorded', + brief: { axes: { facade: { kind: 'bounded', treatment: { cladding: ['stone'] } } } }, }, }, }, + { + name: 'rooms of one use announced apart carry no finding', + tool: 'design_brief', + scene: storeysScene, + input: { + axes: OPEN_AXES, + rooms: HOUSE_ROOMS, + source: 'open', + vision: 'A house.', + beyond: DRESSED, + }, + expect: { + result: { status: 'recorded' }, + check: (result) => ('findings' in result ? ['findings carried'] : []), + }, + }, ] diff --git a/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts new file mode 100644 index 0000000000..7b2b53a92b --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts @@ -0,0 +1,87 @@ +import type { DesignBrief, Treatment } from '../../agent-tools/design-brief' +import type { SessionRecord } from '../scene-checkpoint' +import type { AgentToolCase } from './cases' +import { BEDROOM_AXES, openFacade } from './design-brief-cases' +import { massedScene, rect } from './design-form-cases' + +/** + * The facade a brief states, and a later brief of the turn against the first: a finding where a + * later brief states a plainer treatment (fewer cladding families, bands or elements, a free + * rhythm for a regular one), none where it states the same or more or states no treatment. + */ + +const house = () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) + +const brief = (treatment: Treatment | undefined): DesignBrief => ({ + axes: { + ...BEDROOM_AXES, + facade: treatment + ? openFacade('a stone manor, dressed, its windows shuttered', treatment) + : BEDROOM_AXES.facade, + }, + source: 'open', + vision: 'A manor in stone.', + beyond: 'none: the test reads the facade.', +}) +export const facadeBrief = brief + +export const MANOR: Treatment = { + cladding: ['stone'], + bands: ['base', 'cornice'], + elements: ['corners', 'shutters', 'entrance'], + rhythm: 'regular', +} + +const keeping = (designBrief: DesignBrief, firstTreatment?: Treatment): AgentToolCase['context'] => ({ + designBrief, + session: (): SessionRecord => ({ + checkpoints: {}, + made: [], + designBrief, + ...(firstTreatment ? { firstTreatment } : {}), + }), +}) + +const REVISED = { type: 'facade_revised_simpler', severity: 'warning' } + +export const DESIGN_FACADE_CASES: AgentToolCase[] = [ + { + name: 'a facade revised to a plainer treatment within the turn: a finding says so', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(brief({ cladding: ['stone'], rhythm: 'free' }), MANOR), + expect: { + result: {}, + contains: { issues: [REVISED] }, + mentions: [ + 'The facade was revised during the turn: from stone cladding, base and cornice bands, corner chains, shutters, an entrance unit and a regular rhythm to stone cladding and a free rhythm.', + ], + }, + }, + { + name: 'a facade revised to a richer one, or left as it was: no revision finding', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(brief(MANOR), { cladding: ['stone'], rhythm: 'free' }), + expect: { result: {}, lacks: { issues: [REVISED] } }, + }, +] + +/** A first treatment, the one a later brief of the turn states, and whether the later one is plainer. */ +export const FACADE_REVISION_ROWS: { + name: string + first: Treatment | undefined + latest: Treatment | undefined + plainer: boolean +}[] = [ + { name: 'a manor revised to cladding and a free rhythm', first: MANOR, latest: { cladding: ['stone'], rhythm: 'free' }, plainer: true }, + { name: 'a regular rhythm revised to a free one', first: { cladding: ['stone'], rhythm: 'regular' }, latest: { cladding: ['stone'], rhythm: 'free' }, plainer: true }, + { name: 'a band dropped', first: { cladding: ['stone'], bands: ['base', 'cornice'], rhythm: 'free' }, latest: { cladding: ['stone'], bands: ['cornice'], rhythm: 'free' }, plainer: true }, + { name: 'a stone facade revised to brick: a swap asks as much', first: { cladding: ['stone'], rhythm: 'free' }, latest: { cladding: ['brick'], rhythm: 'free' }, plainer: false }, + { name: 'a facade revised to a richer one', first: { cladding: ['stone'], rhythm: 'free' }, latest: MANOR, plainer: false }, + { name: 'a facade restated as it was', first: MANOR, latest: MANOR, plainer: false }, + { name: 'a later brief that states no treatment has nothing to compare', first: MANOR, latest: undefined, plainer: false }, + { name: 'no first treatment', first: undefined, latest: MANOR, plainer: false }, +] diff --git a/packages/core/src/agent-operations/__fixtures__/design-form-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-form-cases.ts new file mode 100644 index 0000000000..b0a87eb8f7 --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/design-form-cases.ts @@ -0,0 +1,422 @@ +import type { DesignBrief, Massing } from '../../agent-tools/design-brief' +import { BuildingNode, LevelNode, SiteNode, ZoneNode } from '../../schema' +import type { SessionRecord } from '../scene-checkpoint' +import type { AgentToolCase, SceneGraph } from './cases' +import { BEDROOM_AXES, LAMP_AXES, openForm } from './design-brief-cases' + +/** + * The form a brief states, read back against the volumes the scene has: a finding where the scene + * is plainer than the brief, none where it holds up what is stated or the brief states no massing. + * Scenes are rooms tagged with the volume they belong to (or untagged, as create_room leaves them), one + * level per storey, each 3 m tall, on the editor's scaffold: a site and a building. + */ + +type Pt = [number, number] +type Part = { + name: string + polygon: Pt[] + /** Tagged with the volume the room belongs to; left out, the room is untagged and read as inferred. */ + shape?: string + /** Storeys counted from `from`, 1 by default. */ + storeys?: number + /** The first storey it stands on, 0 by default: -1 is a basement. */ + from?: number +} + +export const rect = (minX: number, minZ: number, maxX: number, maxZ: number): Pt[] => [ + [minX, minZ], + [maxX, minZ], + [maxX, maxZ], + [minX, maxZ], +] + +export function massedScene(...parts: Part[]): SceneGraph { + const storeys = parts.flatMap((part) => + Array.from({ length: part.storeys ?? 1 }, (_, s) => (part.from ?? 0) + s), + ) + const levelIds = Array.from(new Set(storeys)).sort((a, b) => a - b) + const levels = levelIds.map((index) => + LevelNode.parse({ + id: `level_${index}`, + parentId: 'building_a', + level: index, + height: 3, + children: [], + }), + ) + const zones = parts.flatMap((part) => + Array.from({ length: part.storeys ?? 1 }, (_, s) => { + const index = (part.from ?? 0) + s + return ZoneNode.parse({ + id: `zone_${part.name}_${index}`, + parentId: `level_${index}`, + name: part.name, + polygon: part.polygon, + ...(part.shape + ? { + metadata: { + volume: { + id: `volume_${part.name}`, + name: part.name, + shape: part.shape, + storeyIndex: s, + partIndex: 0, + }, + }, + } + : {}), + }) + }), + ) + const site = SiteNode.parse({ id: 'site_a', children: ['building_a'] }) + // Storeys below the ground floor push the stack down: the ground floor stands at the site's grade. + const building = BuildingNode.parse({ + id: 'building_a', + parentId: 'site_a', + position: [0, 3 * Math.min(0, ...levelIds), 0], + children: levels.map((level) => level.id), + }) + const nodes = Object.fromEntries( + [site, building, ...levels, ...zones].map((node) => [node.id, node]), + ) + for (const level of levels) + (nodes[level.id] as { children: string[] }).children = zones + .filter((zone) => zone.parentId === level.id) + .map((zone) => zone.id) + return { nodes, rootNodeIds: [building.id] } +} + +/** The brief of "Construis-moi un manoir", its form stated: a U of three volumes at two heights. */ +const brief = (massing: Massing | undefined): DesignBrief => ({ + axes: { + ...BEDROOM_AXES, + form: massing + ? openForm('a central body with two wings stepping forward, the wings lower', massing) + : BEDROOM_AXES.form, + }, + source: 'open', + vision: 'A manor around its forecourt.', + beyond: 'none: the test reads the form.', +}) + +const U_OF_THREE: Massing = { plan: 'u', volumes: 3, heights: 'several' } + +/** The U as the brief states it: a two-storey body across the back, a one-storey wing at each end. */ +export const U_BUILT = massedScene( + { name: 'Body', polygon: rect(0, 0, 12, 4), shape: 'rectangle', storeys: 2 }, + { name: 'West wing', polygon: rect(0, 4, 3, 9), shape: 'rectangle' }, + { name: 'East wing', polygon: rect(9, 4, 12, 9), shape: 'rectangle' }, +) + +/** The same house as two rectangles, an L at one height. */ +export const TWO_RECTANGLES = massedScene( + { name: 'Body', polygon: rect(0, 0, 12, 4), shape: 'rectangle' }, + { name: 'West wing', polygon: rect(0, 4, 3, 9), shape: 'rectangle' }, +) + +/** The brief in force on every surface: the session's, and the one the host passes where it gates. */ +const keeping = (designBrief: DesignBrief, firstMassing?: Massing): AgentToolCase['context'] => ({ + designBrief, + session: (): SessionRecord => ({ + checkpoints: {}, + made: [], + designBrief, + ...(firstMassing ? { firstMassing } : {}), + }), +}) + +const FINDING = { type: 'form_simpler_than_brief', severity: 'warning' } +const REVISED = { type: 'form_revised_simpler', severity: 'warning' } +const RECTANGLE: Massing = { plan: 'rectangle', volumes: 1, heights: 'one' } + +export const DESIGN_FORM_CASES: AgentToolCase[] = [ + { + name: 'two rectangle volumes against a U of three at different heights: one finding naming both sides', + tool: 'verify_scene', + scene: () => TWO_RECTANGLES, + input: {}, + context: keeping(brief(U_OF_THREE)), + expect: { + result: { hasIssues: true }, + contains: { issues: [FINDING] }, + mentions: [ + 'The brief states a form of a U, 3 volumes, at different heights; the scene has 2 volumes (rectangle, rectangle), a plan with 1 re-entrant corner, one height (3.0 m).', + ], + }, + }, + { + name: 'the finding says what is missing, on which building, and which read lists it', + tool: 'verify_scene', + scene: () => TWO_RECTANGLES, + input: {}, + context: keeping(brief(U_OF_THREE)), + expect: { + result: { hasIssues: true }, + mentions: [ + 'Compared on building building_a: volumes: 3 stated, 2 built (Body (rectangle, top 3.0 m), West wing (rectangle, top 3.0 m)), 1 missing; plan: a U needs 2 re-entrant corners or a court, the footprints have 1 re-entrant corner; heights: several stated, every volume tops out at 3.0 m.', + ], + }, + }, + { + name: 'a U of three volumes at two heights, as the brief states it: no finding', + tool: 'verify_scene', + scene: () => U_BUILT, + input: {}, + context: keeping(brief(U_OF_THREE)), + expect: { result: {}, lacks: { issues: [FINDING] } }, + }, + { + name: 'a form stated with no massing (a focused edit bounds it by its words): no finding on any scene', + tool: 'verify_scene', + scene: () => TWO_RECTANGLES, + input: {}, + context: keeping({ + axes: LAMP_AXES, + source: 'open', + vision: 'One lamp.', + beyond: 'none: one lamp.', + }), + expect: { result: {}, lacks: { issues: [FINDING] } }, + }, + { + name: 'a U of three revised to a rectangle within the turn: a finding says so, though the scene matches the later brief', + tool: 'verify_scene', + scene: () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }), + input: {}, + context: keeping(brief(RECTANGLE), U_OF_THREE), + expect: { + result: { hasIssues: true }, + contains: { issues: [REVISED] }, + lacks: { issues: [FINDING] }, + mentions: [ + 'The form was revised during the turn: from a U, 3 volumes, at different heights to a rectangle, 1 volume.', + ], + }, + }, + { + name: 'a form revised to a richer one, or left as it was: no revision finding', + tool: 'verify_scene', + scene: () => U_BUILT, + input: {}, + context: keeping(brief(U_OF_THREE), RECTANGLE), + expect: { result: {}, lacks: { issues: [REVISED] } }, + }, + { + name: 'a form stated once and not revised: no revision finding', + tool: 'verify_scene', + scene: () => U_BUILT, + input: {}, + context: keeping(brief(U_OF_THREE), U_OF_THREE), + expect: { result: {}, lacks: { issues: [REVISED] } }, + }, + { + name: 'a brief stored before the form axis existed: no finding, no throw', + tool: 'verify_scene', + scene: () => TWO_RECTANGLES, + input: {}, + context: keeping({ + axes: { ...BEDROOM_AXES, form: undefined }, + source: 'open', + vision: 'A bedroom.', + beyond: 'none: older brief.', + }), + expect: { result: {}, lacks: { issues: [FINDING] } }, + }, +] + +/** A scene, the massing the brief states, and what differs (none: no finding). */ +export const FORM_ROWS: { + name: string + scene: SceneGraph + massing: Massing | undefined + differs: string[] +}[] = [ + { + name: 'one box against a U of one volume', + scene: massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }), + massing: { plan: 'u', volumes: 1, heights: 'one' }, + differs: ['plan'], + }, + { + name: 'an L built as one letter volume against an L', + scene: massedScene({ + name: 'House', + shape: 'l', + polygon: [ + [0, 0], + [12, 0], + [12, 4], + [3, 4], + [3, 9], + [0, 9], + ], + }), + massing: { plan: 'l', volumes: 1, heights: 'one' }, + differs: [], + }, + { + name: 'an L of untagged rooms against an L: the outline is read, not the tags', + scene: massedScene( + { name: 'Hall', polygon: rect(0, 0, 12, 4) }, + { name: 'Study', polygon: rect(0, 4, 3, 9) }, + ), + massing: { plan: 'l', volumes: 1, heights: 'one' }, + differs: [], + }, + { + name: 'a U built as a U against a courtyard', + scene: U_BUILT, + massing: { plan: 'courtyard', volumes: 3, heights: 'several' }, + differs: ['plan'], + }, + { + name: 'a court closed on four sides against a U: the court holds up what the U leaves open', + scene: massedScene( + { name: 'North', polygon: rect(0, 0, 12, 3), shape: 'courtyard' }, + { name: 'South', polygon: rect(0, 9, 12, 12), shape: 'courtyard' }, + { name: 'West', polygon: rect(0, 3, 3, 9), shape: 'courtyard' }, + { name: 'East', polygon: rect(9, 3, 12, 9), shape: 'courtyard' }, + ), + massing: { plan: 'u', volumes: 4, heights: 'one' }, + differs: [], + }, + { + name: 'volumes that touch against detached volumes', + scene: TWO_RECTANGLES, + massing: { plan: 'detached', volumes: 2, heights: 'one' }, + differs: ['plan'], + }, + { + name: 'volumes that stand apart against detached volumes', + scene: massedScene( + { name: 'House', polygon: rect(0, 0, 10, 6), shape: 'rectangle' }, + { name: 'Pavilion', polygon: rect(14, 0, 18, 6), shape: 'rectangle' }, + ), + massing: { plan: 'detached', volumes: 2, heights: 'one' }, + differs: [], + }, + { + name: 'one height against several', + scene: massedScene( + { name: 'Body', polygon: rect(0, 0, 10, 6), shape: 'rectangle' }, + { name: 'Wing', polygon: rect(10, 0, 14, 6), shape: 'rectangle' }, + ), + massing: { plan: 'rectangle', volumes: 2, heights: 'several' }, + differs: ['heights'], + }, + { + name: 'a taller body and a lower wing against several heights', + scene: massedScene( + { name: 'Body', polygon: rect(0, 0, 10, 6), shape: 'rectangle', storeys: 2 }, + { name: 'Wing', polygon: rect(10, 0, 14, 6), shape: 'rectangle' }, + ), + massing: { plan: 'rectangle', volumes: 2, heights: 'several' }, + differs: [], + }, + { + name: 'more volumes than the brief states are not simpler', + scene: U_BUILT, + massing: { plan: 'rectangle', volumes: 1, heights: 'one' }, + differs: [], + }, + { + name: 'a basement under the whole plan does not fill the notch of a U or count as a volume', + scene: massedScene( + { name: 'Body', polygon: rect(0, 0, 12, 4), shape: 'rectangle' }, + { name: 'West wing', polygon: rect(0, 4, 3, 9), shape: 'rectangle' }, + { name: 'East wing', polygon: rect(9, 4, 12, 9), shape: 'rectangle' }, + { name: 'Cellar', polygon: rect(0, 0, 12, 9), shape: 'rectangle', from: -1 }, + ), + massing: { plan: 'u', volumes: 3, heights: 'one' }, + differs: [], + }, + { + name: 'a scene with no building above grade has nothing to compare', + scene: massedScene({ name: 'Cellar', polygon: rect(0, 0, 12, 9), shape: 'rectangle', from: -1 }), + massing: { plan: 'u', volumes: 3, heights: 'several' }, + differs: [], + }, + { + name: 'a form that states only the plan its words fix, "an L-shaped house", built as a box', + scene: massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }), + massing: { plan: 'l' }, + differs: ['plan'], + }, + { + name: 'no massing stated', + scene: TWO_RECTANGLES, + massing: undefined, + differs: [], + }, +] + +export const formBrief = brief + +/** A form stated first, the one a later brief of the turn states, and what the later one asks less of. */ +export const REVISION_ROWS: { + name: string + first: Massing | undefined + latest: Massing | undefined + differs: string[] +}[] = [ + { + name: 'a U of three at different heights revised to a rectangle of one', + first: U_OF_THREE, + latest: RECTANGLE, + differs: ['volumes', 'plan', 'heights'], + }, + { + name: 'three volumes revised to two', + first: { plan: 'u', volumes: 3, heights: 'one' }, + latest: { plan: 'u', volumes: 2, heights: 'one' }, + differs: ['volumes'], + }, + { + name: 'a letter plan revised to a plainer one', + first: { plan: 'h', volumes: 3, heights: 'one' }, + latest: { plan: 'l', volumes: 3, heights: 'one' }, + differs: ['plan'], + }, + { + name: 'a court revised to a letter', + first: { plan: 'courtyard', volumes: 4, heights: 'one' }, + latest: { plan: 'u', volumes: 4, heights: 'one' }, + differs: ['plan'], + }, + { + name: 'several heights revised to one', + first: U_OF_THREE, + latest: { ...U_OF_THREE, heights: 'one' }, + differs: ['heights'], + }, + { + name: 'a form revised to a richer one', + first: RECTANGLE, + latest: U_OF_THREE, + differs: [], + }, + { + name: 'a form restated as it was', + first: U_OF_THREE, + latest: U_OF_THREE, + differs: [], + }, + { + name: 'a plan of the same rank, a U for a T', + first: { plan: 'u', volumes: 3, heights: 'one' }, + latest: { plan: 't', volumes: 3, heights: 'one' }, + differs: [], + }, + { + name: 'a later brief that states no massing has nothing to compare', + first: U_OF_THREE, + latest: undefined, + differs: [], + }, + { + name: 'no first massing', + first: undefined, + latest: RECTANGLE, + differs: [], + }, +] diff --git a/packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts b/packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts new file mode 100644 index 0000000000..556dd519ab --- /dev/null +++ b/packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts @@ -0,0 +1,78 @@ +import type { BriefRoom, DesignBrief, RoomDressing } from '../../agent-tools/design-brief' +import type { SessionRecord } from '../scene-checkpoint' +import type { AgentToolCase } from './cases' +import { BEDROOM_AXES } from './design-brief-cases' +import { massedScene, rect } from './design-form-cases' + +/** + * The dressing a brief announces for a room, and a later brief of the turn against the first: a + * finding where a later brief announces a kind of wall dressing the first announced for that room + * and no longer does, none where it announces the same or more. + */ + +const house = () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) + +const SALON = (dressing?: RoomDressing[]): BriefRoom => ({ + name: 'Salon', + use: 'living', + distinct: 'The family room, warm and panelled.', + finishes: { + floor: 'oak', + walls: 'white paint', + tiled: false, + skirting: false, + ...(dressing ? { dressing } : {}), + }, + pieces: ['sofa'], +}) + +export const dressingBrief = (...rooms: BriefRoom[]): DesignBrief => ({ + axes: BEDROOM_AXES, + source: 'open', + vision: 'A house.', + beyond: 'none: the test reads the walls.', + rooms, +}) +export const salonBrief = (dressing?: RoomDressing[]) => dressingBrief(SALON(dressing)) + +const keeping = ( + designBrief: DesignBrief, + firstDressing?: SessionRecord['firstDressing'], +): AgentToolCase['context'] => ({ + designBrief, + session: (): SessionRecord => ({ + checkpoints: {}, + made: [], + designBrief, + ...(firstDressing ? { firstDressing } : {}), + }), +}) + +const REVISED = { type: 'room_dressing_revised_simpler', severity: 'warning' } + +export const DESIGN_DRESSING_CASES: AgentToolCase[] = [ + { + name: 'the dressing revised to less within the turn: a finding says what the brief no longer announces', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(salonBrief(['wainscot']), { salon: ['wainscot', 'chairRail', 'crown'] }), + expect: { + result: {}, + contains: { issues: [REVISED] }, + mentions: [ + "The rooms' dressing was revised during the turn; the brief no longer announces Salon: a chair rail and a crown moulding.", + ], + }, + }, + { + name: 'the dressing revised to the same or to more: no revision finding', + tool: 'verify_scene', + scene: house, + input: {}, + context: keeping(salonBrief(['wainscot', 'chairRail', 'crown', 'splashback']), { + salon: ['wainscot', 'chairRail'], + }), + expect: { result: {}, lacks: { issues: [REVISED] } }, + }, +] diff --git a/packages/core/src/agent-operations/batch.ts b/packages/core/src/agent-operations/batch.ts index 52d28eb88b..879772507f 100644 --- a/packages/core/src/agent-operations/batch.ts +++ b/packages/core/src/agent-operations/batch.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import { INDEPENDENT_BATCH_TOOLS } from '../agent-tools/batch' -import { isAgentRefusal, refuse } from '../agent-tools/refusal' +import { AgentRefusal, isAgentRefusal, type RefusalKeep, refuse } from '../agent-tools/refusal' import type { SceneMaterialId } from '../schema/scene-material' import { applySceneChanges, mergeSceneChanges } from './apply-changes' import { requireFurnishing } from './design-brief' @@ -54,11 +54,15 @@ export function createBatchOperation( return (nodes, { calls, onRefusal = 'stop' }, context) => { let working = nodes let workingContext = context + let kept: RefusalKeep['readings'] | undefined const sets: SceneChanges[] = [] const reports: CallReport[] = [] for (const [index, call] of calls.entries()) { try { - requireFurnishing(call.tool, call.input, context.designBrief) + requireFurnishing(call.tool, call.input, context.designBrief, { + session: workingContext.session, + catalog: workingContext.catalog, + }) const { operation, input } = prepareCall(call, index, operations, contracts) const { result, changes } = operation(working, input as never, { ...workingContext, @@ -80,11 +84,23 @@ export function createBatchOperation( } catch (error) { if (!isAgentRefusal(error)) throw error if (onRefusal === 'stop' && !INDEPENDENT_BATCH_TOOLS.includes(call.tool)) - refuse( + throw new AgentRefusal( 'batch_call_refused', `The batch stopped at call ${index + 1} (${call.tool}), refused with ${error.code}: ${error.message} Nothing in the batch was applied.`, { ...error.details, index, tool: call.tool, refusal: error.code }, + error.keep, ) + if (error.keep) { + kept = { ...kept, ...error.keep.readings } + if (workingContext.session) + workingContext = { + ...workingContext, + session: { + ...workingContext.session, + readings: { ...workingContext.session.readings, ...error.keep.readings }, + }, + } + } reports.push({ index, tool: call.tool, @@ -115,6 +131,7 @@ export function createBatchOperation( return { result: { status: 'applied', applied, refused: reports.length - applied, calls: reports }, ...(changed ? { changes: merged } : {}), + ...(kept ? { keep: { readings: kept } } : {}), } } } diff --git a/packages/core/src/agent-operations/brief-findings.ts b/packages/core/src/agent-operations/brief-findings.ts new file mode 100644 index 0000000000..17d5c2a48d --- /dev/null +++ b/packages/core/src/agent-operations/brief-findings.ts @@ -0,0 +1,118 @@ +import { briefGaps } from './brief-gaps' +import { facadeRevision } from './design-facade' +import { formFinding, formRevision } from './design-form' +import { dressingRevision } from './room-dressing' +import type { SessionRecord } from './scene-checkpoint' +import type { SceneNodes } from './types' +import { CHECKPOINT_ORDER, registerSceneCheck } from './verify-scene' + +/** + * What the design brief in force says against the scene, for the one place each surface reads it: + * the form the brief states, read back against the building (a finding where the scene is + * plainer), a later brief of the turn that states the form, the facade or a room's dressing plainer + * than the first (a revision), and what the brief leaves unstated while the turn built. None of + * them refuses a write. + */ + +export type BriefFinding = { + code: string + message: string + /** Absent means warning, as a verify_scene issue's. */ + severity?: 'info' | 'warning' +} + +/** Every code the brief's findings carry: how a reader picks them out of a verify_scene result or a program's diagnostics. */ +export const BRIEF_FINDING_CODES: readonly string[] = [ + 'form_simpler_than_brief', + 'form_revised_simpler', + 'facade_revised_simpler', + 'room_dressing_revised_simpler', + 'form_bounded_without_plan', + 'rooms_not_listed', +] + +/** The scene against the brief: what a program's close reports, the revisions being the turn's and not the scene's. */ +export function briefSceneFindings( + brief: SessionRecord['designBrief'] | null | undefined, + nodes: SceneNodes, +): BriefFinding[] { + const form = formFinding(brief, nodes) + return form ? [form] : [] +} + +/** The phase a program declares: what it is for, which says what of the brief it is too early to ask. */ +export type BriefPhase = 'structure' | 'furnish' | 'finish' | 'edit' + +/** How a reader reads the brief: `phase` is a program's own, which leaves out what the program is too early for (see `briefFindingsForPhase`). */ +export type BriefReadOptions = { phase?: BriefPhase } + +/** What a structure or furnish program can be asked of the brief: the form, a later brief's revision of it and of the facade, and what the brief leaves unstated. */ +const FROM_STRUCTURE: ReadonlySet = new Set([ + 'form_simpler_than_brief', + 'form_revised_simpler', + 'facade_revised_simpler', + 'form_bounded_without_plan', + 'rooms_not_listed', +]) + +/** + * The findings a program's close reports, by the program's own phase: a structure or furnish + * program is asked of the form, the revisions and what the brief leaves unstated, a finish or edit + * program (or one with no phase) of everything, the room dressing included. A program is not + * asked, mid-build, for what it has not finished yet; the end of the turn is asked everything. + */ +export function briefFindingsForPhase( + findings: readonly BriefFinding[], + phase: BriefPhase | undefined, +): BriefFinding[] { + return phase === 'structure' || phase === 'furnish' + ? findings.filter((finding) => FROM_STRUCTURE.has(finding.code)) + : [...findings] +} + +/** Where a later brief of the turn states a plainer form or facade than the first did. */ +export function briefRevisions( + session: Pick, +): BriefFinding[] { + return [ + formRevision(session.firstMassing, session.designBrief), + facadeRevision(session.firstTreatment, session.designBrief), + dressingRevision(session.firstDressing, session.designBrief), + ].filter((finding): finding is NonNullable => finding !== null) +} + +/** Everything the brief in force says of the scene and of the turn. */ +export function briefFindings( + session: Pick< + SessionRecord, + 'designBrief' | 'firstMassing' | 'firstTreatment' | 'firstDressing' | 'made' | 'briefMadeAt' + >, + nodes: SceneNodes, + options: BriefReadOptions = {}, +): BriefFinding[] { + return briefFindingsForPhase( + [ + ...briefSceneFindings(session.designBrief, nodes), + ...briefRevisions(session), + ...briefGaps(session, nodes), + ], + options.phase, + ) +} + +/** + * verify_scene's copy of the brief's findings, as a check it runs after the checkpoint's comparison: + * a warning each unless the finding says it informs. + */ +registerSceneCheck({ + name: 'brief findings', + order: CHECKPOINT_ORDER, + run: (nodes, _input, context) => + context.session + ? briefFindings(context.session, nodes).map((finding) => ({ + type: finding.code, + message: finding.message, + severity: finding.severity ?? 'warning', + })) + : [], +}) diff --git a/packages/core/src/agent-operations/brief-gaps.test.ts b/packages/core/src/agent-operations/brief-gaps.test.ts new file mode 100644 index 0000000000..b26056e22c --- /dev/null +++ b/packages/core/src/agent-operations/brief-gaps.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from 'bun:test' +import { underBrief, zone } from './__fixtures__/brief-gaps-cases' +import { formBrief, massedScene, rect } from './__fixtures__/design-form-cases' +import { briefGaps } from './brief-gaps' +import { EMPTY_SESSION, keepInSession, parseSessionRecord } from './scene-checkpoint' +import type { SceneNodes } from './types' + +describe('the turn’s marker in the session', () => { + const brief = formBrief(undefined) + + test('the first brief marks how much the thread had made; later briefs keep it', () => { + const session = { ...EMPTY_SESSION, made: [zone('zone_a'), zone('zone_b')] } + const first = keepInSession(session, { designBrief: brief }) + expect(first.briefMadeAt).toBe(2) + const grown = keepInSession(first, { made: [zone('zone_c')] }) + const revised = keepInSession(grown, { designBrief: brief }) + expect(revised.briefMadeAt).toBe(2) + expect(revised.made).toHaveLength(3) + }) + + test('it goes with the brief, and the next turn marks anew', () => { + const first = keepInSession( + { ...EMPTY_SESSION, made: [zone('zone_a')] }, + { designBrief: brief }, + ) + const cleared = keepInSession(first, { designBrief: null }) + expect(cleared.briefMadeAt).toBeUndefined() + const next = keepInSession( + { ...cleared, made: [zone('zone_a'), zone('zone_b')] }, + { designBrief: brief }, + ) + expect(next.briefMadeAt).toBe(2) + }) + + test('it is kept with the session record, and a record without it reads', () => { + const kept = keepInSession({ ...EMPTY_SESSION, made: [zone('zone_a')] }, { designBrief: brief }) + expect(parseSessionRecord(JSON.parse(JSON.stringify(kept))).briefMadeAt).toBe(1) + const { briefMadeAt: _marker, ...older } = kept + expect(parseSessionRecord(older).designBrief).toBeDefined() + }) +}) + +describe('what a brief leaves unstated, read for the turn that built', () => { + const nodes = massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) + .nodes as SceneNodes + + test('nothing to read without a brief, or without a marker', () => { + expect(briefGaps({ made: [zone('zone_a')], designBrief: undefined }, nodes)).toEqual([]) + expect( + briefGaps( + { made: [zone('zone_a'), zone('zone_b')], designBrief: formBrief(undefined) }, + nodes, + ), + ).toEqual([]) + }) + + test('two rooms built under a brief that bounds the form by words and lists no rooms: the two are said, in order', () => { + const findings = briefGaps( + underBrief(formBrief(undefined), [], [zone('zone_a'), zone('zone_b')]), + nodes, + ) + expect(findings.map((finding) => finding.code)).toEqual([ + 'form_bounded_without_plan', + 'rooms_not_listed', + ]) + }) +}) diff --git a/packages/core/src/agent-operations/brief-gaps.ts b/packages/core/src/agent-operations/brief-gaps.ts new file mode 100644 index 0000000000..eb2140cafc --- /dev/null +++ b/packages/core/src/agent-operations/brief-gaps.ts @@ -0,0 +1,50 @@ +import type { BriefAxes, DesignBrief } from '../agent-tools/design-brief' +import type { BriefFinding } from './brief-findings' +import { builtForm } from './design-form' +import type { SessionRecord } from './scene-checkpoint' +import type { SceneNodes } from './types' + +/** + * What a brief leaves unstated while the turn built: a form bounded by words that fix no plan is + * compared with nothing, and a brief that lists no rooms owes none to a + * building of many. A finding says so at the end of the turn, never a refusal: the brief is free to + * bound what the person's words bound, and the person sees what was then built without a statement + * to hold it to. Read only for a turn that built (the entries `made` since the brief). + */ + +const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}` + +type Bounded = Extract, { kind: 'bounded' }> + +const boundedWithout = ( + axis: Axis, + states: (axis: Bounded) => boolean, +): Bounded | null => + axis?.kind === 'bounded' && !states(axis as Bounded) ? (axis as Bounded) : null + +export function briefGaps( + session: Pick, + nodes: SceneNodes, +): BriefFinding[] { + const brief: DesignBrief | undefined = session.designBrief + if (!brief || session.briefMadeAt === undefined) return [] + const built = session.made.slice(session.briefMadeAt) + const structure = built.some((entry) => entry.type === 'zone' || entry.type === 'level') + const rooms = built.filter((entry) => entry.type === 'zone').length + const found: BriefFinding[] = [] + if (structure) { + const form = boundedWithout(brief.axes?.form, (axis) => Boolean(axis.massing?.plan)) + const volumes = form ? builtForm(nodes) : null + if (form && volumes) + found.push({ + code: 'form_bounded_without_plan', + message: `The brief bounds the form by "${form.quote}", words that fix no plan; the scene has ${plural(volumes.volumes, 'volume')} (${volumes.shapes.join(', ')}).`, + }) + } + if (rooms >= 2 && !brief.rooms?.length) + found.push({ + code: 'rooms_not_listed', + message: `The brief lists no rooms; the turn built ${rooms} rooms.`, + }) + return found +} diff --git a/packages/core/src/agent-operations/design-brief.test.ts b/packages/core/src/agent-operations/design-brief.test.ts index a1e097ae51..2ffe5e56ad 100644 --- a/packages/core/src/agent-operations/design-brief.test.ts +++ b/packages/core/src/agent-operations/design-brief.test.ts @@ -2,20 +2,23 @@ import { describe, expect, test } from 'bun:test' import { z } from 'zod' import { AGENT_TOOL_CONTRACTS, + addObjectTool, type DesignBrief, type DesignBriefInput, designBriefTool, + placeDesignTool, } from '../agent-tools' import { isAgentRefusal } from '../agent-tools/refusal' import { type AssetInput, BuildingNode, LevelNode, ZoneNode } from '../schema' -import { CATALOG_BRIEF, OPEN_AXES } from './__fixtures__/design-brief-cases' +import { CATALOG_BRIEF, HOUSE_ROOMS, OPEN_AXES } from './__fixtures__/design-brief-cases' +import { storeysScene } from './__fixtures__/structure-cases' import { applyAgentOutcome } from './apply-outcome' import { briefUnlocks, designBrief, furnishingRefusal, gatedByBrief, - isTechnicalEquipment, + REFUSED_PIECES_KEY, requireFurnishing, } from './design-brief' import { AGENT_OPERATIONS } from './index' @@ -39,13 +42,12 @@ const nothing = (why: string) => ), ) as never -const open = (asIs?: DesignBrief['asIs']): DesignBriefInput => ({ +const open = (): DesignBriefInput => ({ fixed: ['a 4 by 5 m bedroom with a double bed'], open: ['form and finish'], source: 'open', vision: 'Oak and linen.', beyond: 'none: the test places what the request names.', - ...(asIs ? { asIs } : {}), }) const tagged = (id: string, name: string, ...functionTags: string[]): AssetInput => ({ @@ -87,9 +89,11 @@ describe('the gate before a brief', () => { 'add_window', 'paint', 'search_materials', + 'generate_material', 'search_assets', 'view_assets', 'verify_scene', + 'add_shelf', 'design_brief', ]) expect(code(tool, {}, null)).toBeNull() @@ -120,40 +124,96 @@ describe('an open brief', () => { open(), ) expect(refusal?.code).toBe('brief_source_open') - expect(refusal?.message).toBe( - "The brief left the source open: double-bed can be made with add_object or place_design (view_assets shows the catalog's for reference), or, for technical equipment, named in the brief's asIs after view_assets, with a reason.", + expect(refusal?.message).toContain( + 'The brief left the source open: double-bed cannot be placed from the catalog, pieces are made.', ) expect(refusal?.details).toMatchObject({ tool: 'place_items', pieces: ['double-bed'] }) }) - test('every piece of the call that is not named is listed, each once', () => { + test('every piece of the call is listed, each once', () => { const refusal = furnishingRefusal( 'place_items', { items: [ { assetId: 'double-bed', x: 0, z: 0 }, - { assetId: 'toilet', x: 1, z: 1 }, + { assetId: 'sofa', x: 1, z: 1 }, { assetId: 'double-bed', x: 2, z: 2 }, { assetId: 'nightstand', x: 3, z: 3 }, ], }, - open([{ assetId: 'toilet', reason: 'technical equipment' }]), + open(), ) - expect(refusal?.details.pieces).toEqual(['double-bed', 'nightstand']) + expect(refusal?.details.pieces).toEqual(['double-bed', 'sofa', 'nightstand']) }) - test('a catalog piece named in asIs is placed as it is, by place_items and place_in_room', () => { - const brief = open([{ assetId: 'toilet', reason: 'technical equipment' }]) - expect(code('place_items', { items: [{ assetId: 'toilet', x: 0, z: 0 }] }, brief)).toBeNull() - expect(code('place_in_room', { assetId: 'toilet' }, brief)).toBeNull() - expect(code('place_in_room', { assetId: 'bathtub' }, brief)).toBe('brief_source_open') + test.each([ + ['place_items', { items: [{ assetId: 'sofa', x: 0, z: 0 }] }], + ['place_in_room', { assetId: 'sofa' }], + ['place_in_room', { assetId: 'double-bed' }], + ])( + 'a catalog piece that is neither equipment nor a plant is refused: %s of %j', + (tool, input) => { + expect(code(tool, input, open())).toBe('brief_source_open') + }, + ) + + test('add_object and place_design make the pieces, a toilet or a fridge as a bed', () => { + expect(code('add_object', { code: 'export default 1', reason: 'a toilet' }, open())).toBeNull() + expect(code('place_design', { design: {} }, open())).toBeNull() }) - test('furnish_room places a whole stock set, so asIs does not open it', () => { - const brief = open([{ assetId: 'toilet', reason: 'technical equipment' }]) + test('furnish_room places a whole stock set, so it stays closed', () => { + const brief = open() const refusal = furnishingRefusal('furnish_room', { roomType: 'bathroom' }, brief) expect(refusal?.code).toBe('brief_source_open') - expect(refusal?.message).toContain("the pieces of furnish_room's stock set can be made") + expect(refusal?.message).toContain( + "the pieces of furnish_room's stock set cannot be placed from the catalog", + ) + }) +}) + +describe('a piece refused under an open source', () => { + const placing = (assetId: string) => ({ items: [{ assetId, x: 0, z: 0 }] }) + const after = (...pieces: string[]) => ({ readings: { [REFUSED_PIECES_KEY]: pieces } }) + + test('the refusal asks the session to remember the piece it refused', () => { + const refusal = furnishingRefusal('place_items', placing('sofa'), open()) + expect(refusal?.keep).toEqual({ readings: { [REFUSED_PIECES_KEY]: ['sofa'] } }) + }) + + test('a piece refused before is answered briefly, the same whichever tool places it', () => { + const short = (tool: string, input: unknown) => + furnishingRefusal(tool, input, open(), { session: after('sofa') }) + const again = short('place_items', placing('sofa')) + expect(again?.message).toBe( + "Already refused, the brief's source is open: sofa. Technical equipment and plants are placed from the catalog; add_object and place_design make the other pieces.", + ) + expect(short('place_in_room', { assetId: 'sofa' })?.message).toBe(again?.message) + expect(short('place_by_relation', placing('sofa'))?.message).toBe(again?.message) + expect(again?.keep).toBeUndefined() + }) + + test('a call with an old piece and a new one gives the facts for the new one, and keeps both', () => { + const refusal = furnishingRefusal( + 'place_items', + { items: [...placing('sofa').items, ...placing('double-bed').items] }, + open(), + { session: after('sofa') }, + ) + expect(refusal?.message).toContain('double-bed cannot be placed from the catalog') + expect(refusal?.message).not.toContain('sofa cannot be placed') + expect(refusal?.message).toContain(' Already refused: sofa.') + expect(refusal?.keep?.readings[REFUSED_PIECES_KEY]).toEqual(['sofa', 'double-bed']) + }) + + test('the tools and fields the first refusal names are in their contracts', () => { + const named = (tool: { input: object }, fields: string[]) => + fields.filter((field) => !(field in tool.input)) + expect(named(addObjectTool, ['code', 'piece', 'parentId', 'position'])).toEqual([]) + expect(named(placeDesignTool, ['design', 'hostId', 'position'])).toEqual([]) + const refusal = furnishingRefusal('place_items', placing('sofa'), open()) + for (const text of ['add_object makes a piece', 'place_design places']) + expect(refusal?.message).toContain(text) }) }) @@ -196,6 +256,40 @@ describe('run_batch', () => { ).toBeNull() }) + const openContext = (): AgentContext => ({ + activeLevelId: null, + designBrief: open(), + session: EMPTY_SESSION, + }) + const sofas = [ + { tool: 'place_in_room', input: { assetId: 'sofa' } }, + { tool: 'place_in_room', input: { assetId: 'sofa' } }, + ] + + test('skip: a piece refused in the batch is short the second time, and the batch keeps it once', () => { + const outcome = AGENT_OPERATIONS.run_batch( + {}, + { calls: sofas, onRefusal: 'skip' }, + openContext(), + ) + const [first, second] = (outcome.result.calls as { error: string }[]).map((c) => c.error) + expect(first).toContain('sofa cannot be placed from the catalog') + expect(second).toStartWith("Already refused, the brief's source is open: sofa.") + expect(outcome.keep?.readings).toEqual({ [REFUSED_PIECES_KEY]: ['sofa'] }) + }) + + test('stop: the refusal that stops the batch carries the keep of the call that refused', () => { + try { + AGENT_OPERATIONS.run_batch({}, { calls: sofas }, openContext()) + throw new Error('the batch did not stop') + } catch (error) { + expect(isAgentRefusal(error) && error.code).toBe('batch_call_refused') + expect(isAgentRefusal(error) && error.keep).toEqual({ + readings: { [REFUSED_PIECES_KEY]: ['sofa'] }, + }) + } + }) + test('the default policy rolls back a brief refusal as it does a runtime refusal', () => { const run = () => AGENT_OPERATIONS.run_batch( @@ -217,16 +311,12 @@ describe('run_batch', () => { describe('design_brief', () => { const input = { axes: OPEN_AXES, + rooms: HOUSE_ROOMS, source: 'open' as const, vision: 'Calm.', beyond: dressed, - asIs: [{ assetId: 'toilet', reason: 'technical equipment' }], - } - const seen: AgentContext = { - activeLevelId: null, - catalog: [tagged('toilet', 'Toilet', 'toilets')], - session: { checkpoints: {}, made: [], viewed: ['toilet'] }, } + const seen: AgentContext = { activeLevelId: null } test('is a shared tool: contract, operation, no scene change', () => { expect(AGENT_TOOL_CONTRACTS.map((contract) => contract.name)).toContain('design_brief') @@ -235,13 +325,12 @@ describe('design_brief', () => { expect(outcome.keep?.designBrief).toEqual(outcome.result.brief as DesignBrief) }) - test('asIs is kept only with an open source, and a brand only with a brand source', () => { + test('a brand is kept only with a brand source', () => { const catalog = designBrief( {}, { ...input, source: 'catalog', brand: 'IKEA', sourceQuote: 'catalog only' }, { activeLevelId: null }, ) - expect(catalog.result.brief).not.toHaveProperty('asIs') expect(catalog.result.brief).not.toHaveProperty('brand') const brand = designBrief( {}, @@ -252,15 +341,14 @@ describe('design_brief', () => { }) test('says what it unlocks and what stays closed', () => { - expect(briefUnlocks(open([{ assetId: 'toilet', reason: 'r' }]))).toEqual({ + expect(briefUnlocks(open() as DesignBrief)).toEqual({ unlocks: [ 'add_object, place_design make the pieces.', - 'place_items and place_in_room place the technical equipment named in asIs: toilet.', + 'place_items and place_in_room place technical equipment and plants from the catalog.', ], closed: [ 'furnish_room places a whole stock set.', - 'Catalog pieces not named in asIs: place_items and place_in_room refuse them; view_assets shows the catalog for reference.', - 'asIs keeps technical equipment (sanitaryware, appliances); furniture is made.', + 'Every other catalog piece is made; view_assets shows the catalog for reference.', ], }) expect(briefUnlocks(CATALOG_BRIEF).closed).toEqual([]) @@ -334,7 +422,7 @@ describe('the brief in a session', () => { test('is read back from where a host stored it, and a stored record that is not a brief is dropped with the record', () => { const stored = keepInSession(EMPTY_SESSION, { - designBrief: open([{ assetId: 'toilet', reason: 'r' }]), + designBrief: open(), }) expect(parseSessionRecord(JSON.parse(JSON.stringify(stored)))).toEqual(stored) expect(parseSessionRecord({ ...stored, designBrief: { source: 'nope' } })).toEqual( @@ -410,15 +498,16 @@ describe('the owner’s bedroom: a 4 by 5 m bedroom with a double bed, two night }) }) -describe('asIs keeps technical equipment, looked at first', () => { +describe('an open source places technical equipment and plants from the catalog', () => { const catalog = [ tagged('double-bed', 'Double bed', 'double-beds'), - tagged('bedside-table', 'Bedside table', 'coffee-tables'), - tagged('closet', 'Closet', 'wardrobes'), + tagged('sofa', 'Sofa', 'sofas'), tagged('toilet', 'Toilet', 'toilets'), tagged('fridge', 'Fridge', 'kitchen-appliances'), + tagged('palm', 'Palm', 'trees'), + { ...tagged('bush', 'Bush', 'outdoor'), tags: ['tree', 'plant', 'garden'] }, ] - const brief = (assetIds: string[], source: 'open' | 'catalog' = 'open') => ({ + const brief = (source: 'open' | 'catalog' = 'open') => ({ axes: source === 'open' ? OPEN_AXES @@ -430,89 +519,104 @@ describe('asIs keeps technical equipment, looked at first', () => { reading: 'the catalog, and nothing beyond it', }, }, + rooms: HOUSE_ROOMS, source, ...(source === 'open' ? {} : { sourceQuote: 'catalog only' }), vision: 'Calm.', beyond: source === 'open' ? dressed : nothing('catalog only'), - asIs: assetIds.map((assetId) => ({ assetId, reason: 'as drawn' })), }) - const run = (assetIds: string[], viewed: string[], source: 'open' | 'catalog' = 'open') => { - try { - return designBrief({}, brief(assetIds, source), { - activeLevelId: null, - catalog, - session: { checkpoints: {}, made: [], viewed }, - }) - } catch (error) { - if (isAgentRefusal(error)) return error - throw error - } - } + const kept = (source: 'open' | 'catalog' = 'open') => + designBrief({}, brief(source), { activeLevelId: null, catalog }).keep!.designBrief! - test('furniture is refused as asIs, viewed or not, with a fact per piece', () => { - const refusal = run( - ['double-bed', 'bedside-table', 'closet'], - ['double-bed', 'bedside-table', 'closet'], - ) - expect(isAgentRefusal(refusal) && refusal.code).toBe('brief_as_is_furniture') - expect((refusal as { message: string }).message).toBe( - ['Double bed', 'Bedside table', 'Closet'] - .map( - (name) => - `${name} is furniture: in an open brief furniture is made (add_object, place_design) or the request names a catalog source; asIs keeps technical equipment (sanitaryware, appliances).`, - ) - .join(' '), + const refusal = (tool: string, input: unknown) => + furnishingRefusal(tool, input, kept(), { catalog }) + const at = (assetId: string) => ({ items: [{ assetId, x: 0, z: 0 }] }) + + test('a fridge is placed from the catalog', () => { + expect(refusal('place_items', at('fridge'))).toBeNull() + const outcome = AGENT_OPERATIONS.place_items( + storeysScene().nodes as SceneNodes, + { ...at('fridge'), levelId: 'level_ground' }, + { activeLevelId: null, catalog, designBrief: kept() }, ) + expect(outcome.result).toMatchObject({ ok: true, levelId: 'level_ground' }) }) - test('a piece not viewed is refused, naming it and view_assets', () => { - const refusal = run(['toilet', 'fridge'], ['fridge']) as { code: string; message: string } - expect(refusal.code).toBe('brief_as_is_not_viewed') - expect(refusal.message).toBe( - 'toilet was not viewed: asIs keeps a catalog piece only after view_assets showed it earlier in the same turn (chat) or session (MCP).', - ) + test('a palm is placed from the catalog, by its plant tags', () => { + expect(refusal('place_items', at('bush'))).toBeNull() + expect(refusal('place_items', at('palm'))).toBeNull() }) - test('a piece never viewed because the host has no session record is refused too', () => { - expect( - (() => { - try { - designBrief({}, brief(['toilet']), { activeLevelId: null, catalog }) - } catch (error) { - return isAgentRefusal(error) && error.code - } - })(), - ).toBe('brief_as_is_not_viewed') - }) - - test('technical equipment viewed is kept, and place_items then passes', () => { - const outcome = run(['toilet', 'fridge'], ['toilet', 'fridge']) as ReturnType< - typeof designBrief - > - const kept = outcome.keep?.designBrief as DesignBrief - expect(kept.asIs?.map((piece) => piece.assetId)).toEqual(['toilet', 'fridge']) - expect(code('place_items', { items: [{ assetId: 'toilet', x: 0, z: 0 }] }, kept)).toBeNull() - expect(code('place_items', { items: [{ assetId: 'double-bed', x: 0, z: 0 }] }, kept)).toBe( - 'brief_source_open', + test('a sofa is still refused under an open source', () => { + const refused = refusal('place_items', at('sofa')) + expect(refused?.code).toBe('brief_source_open') + expect(refused?.details).toMatchObject({ pieces: ['sofa'] }) + expect(refused?.message).toContain( + 'Technical equipment (sanitaryware, appliances) and plants are placed from the catalog under an open source', ) }) - test('a catalog brief opens everything and checks no asIs', () => { - const outcome = run(['double-bed'], [], 'catalog') as ReturnType - expect(outcome.result.brief).not.toHaveProperty('asIs') + test('a call mixing a fridge and a sofa refuses only the sofa', () => { + const mixed = { items: [...at('fridge').items, ...at('sofa').items] } + expect(refusal('place_items', mixed)?.details).toMatchObject({ pieces: ['sofa'] }) + }) + + test('a run_batch places the fridge and refuses the sofa', () => { + const placedBy = (assetId: string) => ({ + tool: 'place_in_room', + input: { + assetId, + polygon: [ + [0, 0], + [4, 0], + [4, 5], + [0, 5], + ], + levelId: 'level_ground', + }, + }) + const outcome = AGENT_OPERATIONS.run_batch( + storeysScene().nodes as SceneNodes, + { calls: [placedBy('fridge'), placedBy('sofa')], onRefusal: 'skip' }, + { activeLevelId: null, catalog, designBrief: kept(), session: EMPTY_SESSION }, + ) + expect(outcome.result).toMatchObject({ applied: 1, refused: 1 }) + expect(outcome.result.calls).toMatchObject([ + { index: 0, status: 'ok' }, + { index: 1, status: 'refused', code: 'brief_source_open' }, + ]) + }) + + test('catalog source: place_items of a toilet is allowed', () => { expect( - code('place_items', { items: [{ assetId: 'double-bed' }] }, outcome.keep!.designBrief!), + code('place_items', { items: [{ assetId: 'toilet', x: 0, z: 0 }] }, kept('catalog')), ).toBeNull() }) - test('technical means plumbing, appliances and services by function tag, else by category', () => { - expect(isTechnicalEquipment(tagged('x', 'X', 'sinks', 'plumbing'))).toBe(true) - expect(isTechnicalEquipment(tagged('x', 'X', 'utilities'))).toBe(true) - expect(isTechnicalEquipment(tagged('x', 'X', 'climate-appliances'))).toBe(true) - expect(isTechnicalEquipment(tagged('x', 'X', 'sofas'))).toBe(false) - expect(isTechnicalEquipment(tagged('x', 'X', 'kitchen-appliances', 'cabinets'))).toBe(false) - expect(isTechnicalEquipment({ category: 'toilets' })).toBe(true) - expect(isTechnicalEquipment({ category: 'furniture' })).toBe(false) + test('a brief stored with asIs, before it was removed, parses without it and gates as open', () => { + const stored = parseSessionRecord({ + checkpoints: {}, + made: [], + designBrief: { + ...brief(), + asIs: [{ assetId: 'double-bed', reason: 'as drawn in the catalog' }], + }, + }) + expect(stored.designBrief).toBeDefined() + expect(stored.designBrief).not.toHaveProperty('asIs') + expect( + code('place_items', { items: [{ assetId: 'double-bed', x: 0, z: 0 }] }, stored.designBrief!), + ).toBe('brief_source_open') + expect(code('add_object', { code: 'export default 1' }, stored.designBrief!)).toBeNull() + }) + + test('an asIs a model still sends is not kept', () => { + const outcome = designBrief( + {}, + { ...brief(), asIs: [{ assetId: 'toilet', reason: 'as drawn' }] } as never, + { activeLevelId: null, catalog }, + ) + expect(outcome.result.brief).not.toHaveProperty('asIs') }) test('view_assets records the ids it showed; the session adds, dedups and forgets them', () => { @@ -532,7 +636,7 @@ describe('asIs keeps technical equipment, looked at first', () => { describe('beyond: the dressing of the rooms, layer by layer', () => { const schema = z.object(designBriefTool.input) - const base = { axes: OPEN_AXES, source: 'open', vision: 'Calm.' } + const base = { axes: OPEN_AXES, rooms: HOUSE_ROOMS, source: 'open', vision: 'Calm.' } const run = ( beyond: unknown, extra: Partial = {}, @@ -746,6 +850,7 @@ describe('beyond: the dressing of the rooms, layer by layer', () => { describe('a source other than open quotes the request', () => { const brief = { axes: OPEN_AXES, + rooms: HOUSE_ROOMS, vision: 'Furnished.', beyond: dressed, } @@ -849,7 +954,10 @@ describe('a source other than open quotes the request', () => { }) test('an older stored brief (no beyond) still reads, with the session’s checkpoints, and still gates', () => { - const { beyond: _beyond, ...older } = open([{ assetId: 'toilet', reason: 'r' }]) + const { beyond: _beyond, ...older } = { + ...open(), + asIs: [{ assetId: 'sofa', reason: 'r' }], + } const stored = JSON.parse( JSON.stringify({ ...EMPTY_SESSION, @@ -864,11 +972,13 @@ describe('a source other than open quotes the request', () => { expect(code('place_items', { items: [{ assetId: 'double-bed' }] }, read.designBrief!)).toBe( 'brief_source_open', ) - expect(code('place_items', { items: [{ assetId: 'toilet' }] }, read.designBrief!)).toBeNull() + expect(code('place_items', { items: [{ assetId: 'sofa' }] }, read.designBrief!)).toBe( + 'brief_source_open', + ) }) test('a brief stored as fixed and open lists with a string beyond, before the axes, still reads, with the session’s checkpoints', () => { - const older = open([{ assetId: 'toilet', reason: 'r' }]) + const older = open() const read = parseSessionRecord( JSON.parse( JSON.stringify({ diff --git a/packages/core/src/agent-operations/design-brief.ts b/packages/core/src/agent-operations/design-brief.ts index a31aabcd7d..ab964f6f6b 100644 --- a/packages/core/src/agent-operations/design-brief.ts +++ b/packages/core/src/agent-operations/design-brief.ts @@ -9,9 +9,11 @@ import { type DesignBriefInput, FURNISHING_CREATION_TOOLS, layerPieces, + MASSING_FIELDS, } from '../agent-tools/design-brief' import { AgentRefusal, refuse } from '../agent-tools/refusal' import type { AssetInput } from '../schema' +import type { SessionRecord } from './scene-checkpoint' import type { AgentContext, AgentOperation } from './types' /** @@ -24,38 +26,35 @@ import type { AgentContext, AgentOperation } from './types' export const NO_BRIEF = "Furnishing follows the turn's design brief: design_brief records what the request fixes, what it leaves open and where objects come from; until then the catalog can be searched and viewed, not placed, and no furnishing is made." -const openSource = (piece: string) => - `The brief left the source open: ${piece} can be made with add_object or place_design (view_assets shows the catalog's for reference), or, for technical equipment, named in the brief's asIs after view_assets, with a reason.` - /** - * The function tags of the catalog's technical equipment: sanitaryware, kitchen, laundry and climate - * appliances, fixed services. A hosted item's `category` is its primary function tag; the built-in - * list carries function tags too. An item whose tags are not all technical is furniture here. + * Which tools make a piece and with what, as facts a refusal states: the field names are the + * contracts' (a test reads them back). Kitchen cabinets are a run of modules, not one object. */ -const TECHNICAL_FUNCTIONS: ReadonlySet = new Set([ - 'plumbing', - 'sinks', - 'toilets', - 'showers', - 'bathtubs', - 'appliances', - 'appliance', - 'kitchen-appliances', - 'laundry-appliances', - 'climate-appliances', - 'utilities', -]) +const MAKING_TOOLS = + 'add_object makes a piece (code, or piece for the object in words; parentId and position say where it goes); place_design places a designed piece (design, hostId, position).' -export function isTechnicalEquipment(item: Pick): boolean { - const tags = item.functionTags?.length ? item.functionTags : [item.category] - return tags.every((tag) => TECHNICAL_FUNCTIONS.has(tag)) -} +const openSource = (pieces: string) => + `The brief left the source open: ${pieces} cannot be placed from the catalog, pieces are made. Technical equipment (sanitaryware, appliances) and plants are placed from the catalog under an open source; every other catalog piece is made. ${MAKING_TOOLS} view_assets shows the catalog's pieces for reference.` -const furnitureFact = (name: string) => - `${name} is furniture: in an open brief furniture is made (add_object, place_design) or the request names a catalog source; asIs keeps technical equipment (sanitaryware, appliances).` +/** What a call answers when every piece it names was refused already: short, the same each time. */ +const alreadyRefused = (pieces: string) => + `Already refused, the brief's source is open: ${pieces}. Technical equipment and plants are placed from the catalog; add_object and place_design make the other pieces.` -const notViewed = (ids: string[]) => - `${ids.join(', ')} ${ids.length === 1 ? 'was' : 'were'} not viewed: asIs keeps a catalog piece only after view_assets showed it earlier in the same turn (chat) or session (MCP).` +/** What `furnish_room` places: no piece is named, a stock set is. */ +const FURNISH_ROOM_PIECES = "the pieces of furnish_room's stock set" + +/** The session reading that holds the pieces refused under an open source (`SessionKeep.readings`). */ +export const REFUSED_PIECES_KEY = 'brief.refusedPieces' +/** The reading keeps the most recent pieces up to here. */ +const MAX_REFUSED_PIECES = 100 + +/** The pieces the session's catalog placements were refused for under an open source. */ +function refusedPieces(session: Pick | undefined): string[] { + const held = session?.readings?.[REFUSED_PIECES_KEY] + return Array.isArray(held) + ? held.filter((piece): piece is string => typeof piece === 'string') + : [] +} const SOURCE_NOT_IN_REQUEST = "A source is set by the request: the brief's sourceQuote must be the person's own words naming it, a brand, the catalog or what is already there; this request names none, so its source is open." @@ -151,9 +150,50 @@ function requireAxes(input: DesignBriefInput, context: AgentContext): BriefAxes } else if (fold(reading.design).split(' ').filter(Boolean).length < AXIS_DESIGN_MIN_WORDS) refuse('axis_open_without_design', `The ${axis} is open: say how it is designed.`, { axis }) } + requireMassing(axes.form!) + requireTreatment(axes.facade!) return axes } +/** An open facade states what it is clad in or carries, and the rhythm of its openings. */ +function requireTreatment(facade: NonNullable): void { + if (facade.kind !== 'open') return + const treatment = facade.treatment ?? {} + const absent = [ + ...(treatment.cladding?.length || treatment.elements?.length ? [] : ['cladding or elements']), + ...(treatment.rhythm ? [] : ['rhythm']), + ] + if (absent.length) + refuse( + 'facade_treatment_missing', + `The facade is open: its treatment states what it is clad in or carries (cladding, bands, elements) and whether its openings follow a regular rhythm or a free one. Absent: ${absent.join(', ')}.`, + { fields: absent }, + ) +} + +/** + * An open form states its massing in full, and a form of one volume is neither detached nor at + * several heights: what the scene is read back against is a commitment it can keep or break. + */ +function requireMassing(form: NonNullable): void { + const massing = form.massing ?? {} + if (form.kind === 'open') { + const absent = MASSING_FIELDS.filter((field) => massing[field] === undefined) + if (absent.length) + refuse( + 'form_massing_missing', + `The form is open: its massing states the plan, the number of volumes and whether they stand at one height or several; ${absent.join(', ')} ${absent.length === 1 ? 'is' : 'are'} absent.`, + { fields: absent }, + ) + } + if (massing.volumes === 1 && (massing.plan === 'detached' || massing.heights === 'several')) + refuse( + 'form_massing_inconsistent', + `A form of one volume cannot be ${massing.plan === 'detached' ? 'detached' : 'at several heights'}: state the number of volumes that stand apart or at different heights.`, + { volumes: 1 }, + ) +} + /** The pieces `beyond` names, flattened: the brief's own list of the dressing. */ export function dressingOf(beyond: DesignBriefInput['beyond']): string[] { return BEYOND_LAYERS.flatMap(([key]) => layerPieces(beyond[key])) @@ -190,33 +230,43 @@ function requireDressing(input: DesignBriefInput, axes: BriefAxes): void { ) } -/** Whether `design_brief` reads the item library: an open brief naming pieces as they are. */ -export function briefReadsCatalog(tool: string, input: unknown): boolean { - const { source, asIs } = asRecord(input) - return tool === 'design_brief' && source === 'open' && Array.isArray(asIs) && asIs.length > 0 -} - /** - * An open brief keeps a catalog piece as it is only if it is technical equipment and view_assets - * showed it to the agent (the session's `viewed`). Furniture is refused first: looking at it would - * change nothing. + * The rooms of a building the brief designs: an open form owes one entry per room, each with its + * own distinct line, and rooms of one use are not copies of one another. Anything subtler than a + * word-for-word copy is a finding at the end of the turn, not a refusal here. */ -function requireAsIs(brief: DesignBrief, context: AgentContext): void { - const named = [...new Set((brief.asIs ?? []).map((piece) => piece.assetId))] - if (brief.source !== 'open' || !named.length) return - const furniture = named.flatMap((id) => { - const item = context.catalog?.find((candidate) => candidate.id === id) - return item && !isTechnicalEquipment(item) ? [{ id, name: item.name }] : [] +function requireRooms(input: DesignBriefInput, axes: BriefAxes): void { + const rooms = input.rooms ?? [] + if (!rooms.length && axes.form?.kind === 'open') + refuse( + 'rooms_missing', + 'The form is open, so the request builds a building: rooms lists each room it builds, with its use, what sets it apart, its finishes and its main pieces.', + ) + for (const room of rooms) + if (!fold(room.distinct ?? '')) + refuse( + 'room_distinct_missing', + `The room "${room.name}" says nothing of what sets it apart: distinct is one line on who it is for and its character, against the other rooms of its use.`, + { room: room.name }, + ) + rooms.forEach((room, index) => { + for (const other of rooms.slice(index + 1)) + if ( + room.use === other.use && + fold(room.distinct ?? '') === fold(other.distinct ?? '') && + pieceKey(room.pieces) === pieceKey(other.pieces) + ) + refuse( + 'rooms_identical', + `The rooms "${room.name}" and "${other.name}" are of one use and state the same distinct line and the same pieces: rooms of one use are distinct rooms, each with its own.`, + { rooms: [room.name, other.name], use: room.use }, + ) }) - if (furniture.length) - refuse('brief_as_is_furniture', furniture.map(({ name }) => furnitureFact(name)).join(' '), { - pieces: furniture.map(({ id }) => id), - }) - const viewed = new Set(context.session?.viewed ?? []) - const unseen = named.filter((id) => !viewed.has(id)) - if (unseen.length) refuse('brief_as_is_not_viewed', notViewed(unseen), { pieces: unseen }) } +/** A room's pieces as a comparison reads them: folded, in no order. */ +const pieceKey = (pieces: string[]) => pieces.map(fold).sort().join('|') + const isCatalogPlacement = (tool: string) => (CATALOG_PLACEMENT_TOOLS as readonly string[]).includes(tool) const isCreation = (tool: string) => (FURNISHING_CREATION_TOOLS as readonly string[]).includes(tool) @@ -224,15 +274,89 @@ const isCreation = (tool: string) => (FURNISHING_CREATION_TOOLS as readonly stri const asRecord = (value: unknown): Record => typeof value === 'object' && value !== null ? (value as Record) : {} +/** + * The function tags of the catalog's technical equipment: sanitaryware, kitchen, laundry and climate + * appliances, fixed services. A hosted item's `category` is its primary function tag; the built-in + * list carries function tags too. An item whose tags are not all technical is furniture here. + */ +const TECHNICAL_FUNCTIONS: ReadonlySet = new Set([ + 'plumbing', + 'sinks', + 'toilets', + 'showers', + 'bathtubs', + 'appliances', + 'appliance', + 'kitchen-appliances', + 'laundry-appliances', + 'climate-appliances', + 'utilities', +]) + +export function isTechnicalEquipment(item: Pick): boolean { + const tags = item.functionTags?.length ? item.functionTags : [item.category] + return tags.every((tag) => TECHNICAL_FUNCTIONS.has(tag)) +} + +/** + * The catalog's vegetation, as its function leaves (`plants`, `indoor-plants`, `trees`) and item + * tags (`tree`, `plant`, `garden`) write it. A tag counts by its hyphen-separated words, so + * `indoor-plants` is plants and `planter` is not. + */ +const VEGETATION_WORDS: ReadonlySet = new Set([ + 'plant', + 'plants', + 'tree', + 'trees', + 'palm', + 'palms', + 'bush', + 'bushes', + 'shrub', + 'shrubs', + 'hedge', + 'hedges', + 'grass', + 'flower', + 'flowers', + 'fern', + 'ferns', + 'cactus', + 'cacti', + 'vegetation', + 'foliage', +]) + +export function isVegetation( + item: Pick, +): boolean { + const tags = [item.category, ...(item.functionTags ?? []), ...(item.tags ?? [])] + return tags.some((tag) => tag.split('-').some((word) => VEGETATION_WORDS.has(word))) +} + +/** Whether the catalog files a piece as one an open source places: technical equipment or a plant. */ +function placeableFromCatalog(id: string, catalog: readonly AssetInput[] | undefined): boolean { + const item = catalog?.find((candidate) => candidate.id === id) + return item ? isTechnicalEquipment(item) || isVegetation(item) : false +} + /** The catalog ids a placement call names. */ function placedAssets(tool: string, input: Record): string[] { const named = - tool === 'place_items' + tool === 'place_items' || tool === 'place_by_relation' ? (Array.isArray(input.items) ? input.items : []).map((item) => asRecord(item).assetId) : [input.assetId] return [...new Set(named.filter((id): id is string => typeof id === 'string'))] } +/** Whether a call names catalog pieces, which the gate reads the library to decide. */ +export function namesCatalogPieces(tool: string, input: unknown): boolean { + return placedAssets(tool, asRecord(input)).length > 0 +} + +/** What the gate reads beyond the brief: the session's refusals, and the catalog's tags. */ +type BriefGateContext = Pick + /** * Why a furnishing call may not run under this brief, or null. `brief` null is no brief yet. An * `add_object` that names a `nodeId` edits an object that stands: it places and makes nothing. @@ -242,31 +366,49 @@ export function furnishingRefusal( tool: string, input: unknown, brief: DesignBrief | null, + context: BriefGateContext = {}, ): AgentRefusal | null { - if (!(isCatalogPlacement(tool) || isCreation(tool))) return null const args = asRecord(input) + if (tool === 'place_by_relation') { + const pieces = placedAssets(tool, args) + if (!pieces.length) return null + return furnishingRefusal( + 'place_items', + { items: pieces.map((assetId) => ({ assetId })) }, + brief, + context, + ) + } + if (!(isCatalogPlacement(tool) || isCreation(tool))) return null if (tool === 'add_object' && typeof args.nodeId === 'string') return null if (!brief) return new AgentRefusal('design_brief_required', NO_BRIEF, { tool }) if (brief.source !== 'open' || isCreation(tool)) return null - if (tool === 'furnish_room') - return new AgentRefusal( - 'brief_source_open', - openSource("the pieces of furnish_room's stock set"), - { - tool, - source: brief.source, - }, - ) - const unnamed = placedAssets(tool, args).filter( - (id) => !brief.asIs?.some((piece) => piece.assetId === id), - ) - return unnamed.length - ? new AgentRefusal('brief_source_open', openSource(unnamed.join(', ')), { - tool, - source: brief.source, - pieces: unnamed, - }) - : null + const pieces = tool === 'furnish_room' ? [FURNISH_ROOM_PIECES] : placedAssets(tool, args) + const refused = pieces.filter((piece) => !placeableFromCatalog(piece, context.catalog)) + return refused.length ? openSourceRefusal(tool, refused, context.session) : null +} + +/** + * The refusal of a catalog placement under an open source. A piece refused before in the session + * is named briefly; the pieces not refused yet get the facts, and the refusal asks the host to + * remember them (`REFUSED_PIECES_KEY`), so a retry, by any placing tool, is short. + */ +function openSourceRefusal( + tool: string, + pieces: string[], + session: Pick | undefined, +): AgentRefusal { + const held = refusedPieces(session) + const fresh = pieces.filter((piece) => !held.includes(piece)) + const repeated = pieces.filter((piece) => held.includes(piece)) + const message = fresh.length + ? openSource(fresh.join(', ')) + + (repeated.length ? ` Already refused: ${repeated.join(', ')}.` : '') + : alreadyRefused(repeated.join(', ')) + const keep = fresh.length + ? { readings: { [REFUSED_PIECES_KEY]: [...held, ...fresh].slice(-MAX_REFUSED_PIECES) } } + : undefined + return new AgentRefusal('brief_source_open', message, { tool, source: 'open', pieces }, keep) } /** Throws the refusal when the host gates and the call may not run; a host with no brief to keep passes. */ @@ -274,9 +416,10 @@ export function requireFurnishing( tool: string, input: unknown, brief: DesignBrief | null | undefined, + context: BriefGateContext = {}, ): void { if (brief === undefined) return - const refusal = furnishingRefusal(tool, input, brief) + const refusal = furnishingRefusal(tool, input, brief, context) if (refusal) throw refusal } @@ -286,7 +429,7 @@ export function gatedByBrief( operation: AgentOperation, ): AgentOperation { return (nodes, input, context) => { - requireFurnishing(tool, input, context.designBrief) + requireFurnishing(tool, input, context.designBrief, context) return operation(nodes, input, context) } } @@ -301,20 +444,14 @@ export function briefUnlocks(brief: DesignBrief): { unlocks: string[]; closed: s ], closed: [], } - const asIs = brief.asIs ?? [] return { unlocks: [ `${FURNISHING_CREATION_TOOLS.join(', ')} make the pieces.`, - ...(asIs.length - ? [ - `place_items and place_in_room place the technical equipment named in asIs: ${asIs.map((piece) => piece.assetId).join(', ')}.`, - ] - : []), + 'place_items and place_in_room place technical equipment and plants from the catalog.', ], closed: [ 'furnish_room places a whole stock set.', - 'Catalog pieces not named in asIs: place_items and place_in_room refuse them; view_assets shows the catalog for reference.', - 'asIs keeps technical equipment (sanitaryware, appliances); furniture is made.', + 'Every other catalog piece is made; view_assets shows the catalog for reference.', ], } } @@ -342,6 +479,7 @@ export const designBrief: AgentOperation = (_nodes, input, con refuse('source_not_in_request', SOURCE_NOT_IN_REQUEST) } requireDressing(input, axes) + requireRooms(input, axes) const brief: DesignBrief = { axes, source: input.source, @@ -349,9 +487,8 @@ export const designBrief: AgentOperation = (_nodes, input, con ...(input.source === 'brand' && brand ? { brand } : {}), vision: input.vision, beyond: input.beyond, - ...(input.source === 'open' && input.asIs?.length ? { asIs: input.asIs } : {}), + ...(input.rooms?.length ? { rooms: input.rooms } : {}), } - requireAsIs(brief, context) return { result: { status: 'recorded', diff --git a/packages/core/src/agent-operations/design-facade.test.ts b/packages/core/src/agent-operations/design-facade.test.ts new file mode 100644 index 0000000000..30837faead --- /dev/null +++ b/packages/core/src/agent-operations/design-facade.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, test } from 'bun:test' +import { FACADE_REVISION_ROWS, facadeBrief } from './__fixtures__/design-facade-cases' +import { facadeRevision } from './design-facade' + +describe('a facade revised within the turn', () => { + test.each(FACADE_REVISION_ROWS)('$name', ({ first, latest, plainer }) => { + expect(facadeRevision(first, facadeBrief(latest)) !== null).toBe(plainer) + }) +}) diff --git a/packages/core/src/agent-operations/design-facade.ts b/packages/core/src/agent-operations/design-facade.ts new file mode 100644 index 0000000000..b691333e67 --- /dev/null +++ b/packages/core/src/agent-operations/design-facade.ts @@ -0,0 +1,81 @@ +import type { DesignBrief, Treatment } from '../agent-tools/design-brief' + +/** + * The facade a brief states, in words, and a later brief of the turn against the first. The brief's + * `facade` axis states a treatment (the material families it is clad in, its bands, what else it + * carries, the rhythm of its openings); a later brief that states a plainer one is a fact to show. + * Reading what the building has against it is the facade tools' own, and not here. It never + * refuses a write. + */ + +type Cladding = NonNullable[number] +type Element = NonNullable[number] + +const CLADDING_WORDS: Record = { + brick: 'brick', + stone: 'stone', + render: 'render', + siding: 'siding', + wood: 'wood', + metal: 'metal', +} + +const ELEMENT_WORDS: Record = { + corners: 'corner chains', + surrounds: 'opening surrounds', + shutters: 'shutters', + balconies: 'balconies', + entrance: 'an entrance unit', + 'curtain-wall': 'curtain-wall glazing', + porch: 'a porch', + guard: 'guards', + posts: 'posts', +} + +const list = (words: string[]) => + words.length > 1 ? `${words.slice(0, -1).join(', ')} and ${words.at(-1)}` : (words[0] ?? '') + +/** A treatment in words: "brick cladding, base and cornice bands, shutters and a regular rhythm". */ +function treatmentWords(treatment: Treatment): string { + return list( + [ + treatment.cladding?.length + ? `${list(treatment.cladding.map((family) => CLADDING_WORDS[family]))} cladding` + : null, + treatment.bands?.length + ? `${list(treatment.bands)} ${treatment.bands.length === 1 ? 'band' : 'bands'}` + : null, + ...(treatment.elements ?? []).map((element) => ELEMENT_WORDS[element]), + treatment.rhythm ? `a ${treatment.rhythm} rhythm` : null, + ].filter((part): part is string => part !== null), + ) +} + +/** What a treatment asks of a facade: one for each family, band and element, one for a regular rhythm. */ +const demands = (treatment: Treatment) => + (treatment.cladding?.length ?? 0) + + (treatment.bands?.length ?? 0) + + (treatment.elements?.length ?? 0) + + (treatment.rhythm === 'regular' ? 1 : 0) + +export type FacadeRevision = { + code: 'facade_revised_simpler' + message: string +} + +/** + * The finding where a later brief of the turn states a plainer treatment than the first one did: + * it asks for fewer families, bands, elements, or a free rhythm for a regular one. A brief is free + * to revise, so this is a fact to show. Null when either brief states no treatment. + */ +export function facadeRevision( + first: Treatment | undefined, + brief: Pick | null | undefined, +): FacadeRevision | null { + const latest = brief?.axes?.facade?.treatment + if (!(first && latest) || demands(latest) >= demands(first)) return null + return { + code: 'facade_revised_simpler', + message: `The facade was revised during the turn: from ${treatmentWords(first)} to ${treatmentWords(latest) || 'no stated treatment'}.`, + } +} diff --git a/packages/core/src/agent-operations/design-form.test.ts b/packages/core/src/agent-operations/design-form.test.ts new file mode 100644 index 0000000000..05ce02eae3 --- /dev/null +++ b/packages/core/src/agent-operations/design-form.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, test } from 'bun:test' +import { + FORM_ROWS, + formBrief, + massedScene, + REVISION_ROWS, + rect, + U_BUILT, +} from './__fixtures__/design-form-cases' +import { formFinding, formRevision } from './design-form' +import { EMPTY_SESSION, keepInSession, parseSessionRecord } from './scene-checkpoint' +import type { SceneNodes } from './types' + +describe('the form a brief states against the volumes built', () => { + test.each(FORM_ROWS)('$name', ({ scene, massing, differs }) => { + const finding = formFinding(formBrief(massing), scene.nodes as SceneNodes) + expect(finding?.differs ?? []).toEqual(differs) + expect(finding?.code ?? 'form_simpler_than_brief').toBe('form_simpler_than_brief') + }) + + test('no brief, and a brief stored before the form axis, have nothing to compare', () => { + const nodes = U_BUILT.nodes as SceneNodes + expect(formFinding(null, nodes)).toBeNull() + expect(formFinding(undefined, nodes)).toBeNull() + expect(formFinding({ axes: {} }, nodes)).toBeNull() + }) + + test('a scene the massing cannot be read from has no finding, and no throw', () => { + const scene = massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) + const broken = { + ...scene.nodes, + zone_House_0: { ...(scene.nodes.zone_House_0 as object), polygon: undefined }, + } + expect( + formFinding(formBrief({ plan: 'u', volumes: 3, heights: 'several' }), broken as SceneNodes), + ).toBeNull() + }) +}) + +describe('a form revised within the turn', () => { + test.each(REVISION_ROWS)('$name', ({ first, latest, differs }) => { + const revision = formRevision(first, formBrief(latest)) + expect(revision?.differs ?? []).toEqual(differs) + }) + + test('the first massing the turn stated stays while later briefs replace the brief', () => { + const U = { plan: 'u', volumes: 3, heights: 'several' } as const + const box = { plan: 'rectangle', volumes: 1, heights: 'one' } as const + const first = keepInSession(EMPTY_SESSION, { designBrief: formBrief(U) }) + expect(first.firstMassing).toEqual(U) + const revised = keepInSession(first, { designBrief: formBrief(box) }) + expect(revised.firstMassing).toEqual(U) + expect(revised.designBrief?.axes?.form?.massing).toEqual(box) + expect(keepInSession(revised, { made: [] }).firstMassing).toEqual(U) + }) + + test('it goes with the brief: taking the brief away clears it, and the next turn starts anew', () => { + const U = { plan: 'u', volumes: 3, heights: 'several' } as const + const box = { plan: 'rectangle', volumes: 1, heights: 'one' } as const + const kept = keepInSession(EMPTY_SESSION, { designBrief: formBrief(U) }) + const cleared = keepInSession(kept, { designBrief: null }) + expect(cleared.firstMassing).toBeUndefined() + expect(keepInSession(cleared, { designBrief: formBrief(box) }).firstMassing).toEqual(box) + }) + + test('a first brief that states no massing sets none; the first one that states one does', () => { + const none = keepInSession(EMPTY_SESSION, { designBrief: formBrief(undefined) }) + expect(none.firstMassing).toBeUndefined() + const box = { plan: 'rectangle', volumes: 1, heights: 'one' } as const + expect(keepInSession(none, { designBrief: formBrief(box) }).firstMassing).toEqual(box) + }) + + test('it is kept with the session record, and a record without it still reads', () => { + const U = { plan: 'u', volumes: 3, heights: 'several' } as const + const kept = keepInSession(EMPTY_SESSION, { designBrief: formBrief(U) }) + expect(parseSessionRecord(JSON.parse(JSON.stringify(kept))).firstMassing).toEqual(U) + const { firstMassing: _first, ...older } = kept + expect(parseSessionRecord(older).designBrief).toBeDefined() + }) +}) diff --git a/packages/core/src/agent-operations/design-form.ts b/packages/core/src/agent-operations/design-form.ts new file mode 100644 index 0000000000..af8573209f --- /dev/null +++ b/packages/core/src/agent-operations/design-form.ts @@ -0,0 +1,341 @@ +import type { DesignBrief, FormPlan, Massing } from '../agent-tools/design-brief' +import { type Ring, union } from '../lib/polygon-boolean' +import type { AnyNode, AnyNodeId } from '../schema' +import { isLevelBelowGrade } from '../services/storey' +import { type MassingBuilding, readMassing } from './massing-read' +import { queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +/** + * The form a brief states against the volumes the scene has. The brief's `form` axis states a + * massing (a plan shape, a number of volumes, one height or several); this reads the building + * back through the volumes its rooms form and their footprints, and reports a finding only + * where the scene is plainer than the brief says. It never refuses a write, and a form that + * states no massing is not compared. + */ + +/** Tops of volumes within this (m) stand at one height. */ +const SAME_HEIGHT = 0.3 +/** A turn of less than this (sine of the angle) is a straight run, not a corner. */ +const STRAIGHT = 0.0175 +/** An edge within this many degrees of the building's own axes is not angled. */ +const ANGLED_DEGREES = 1 + +/** What the footprints of the above-grade rooms, seen from above, make of the plan. */ +type PlanFacts = { + /** Separate masses: footprints that share no edge. */ + components: number + /** Corners of the outlines, straight runs not counted. */ + corners: number + /** Re-entrant corners of the outlines: 1 for an L, 2 for a U or a T, 4 for an H. */ + reflex: number + /** Open courts: holes in the footprints' union. */ + holes: number + /** An outline edge that runs at an angle to the others. */ + angled: boolean +} + +const PLAN_WORDS: Record = { + rectangle: 'a rectangle', + l: 'an L', + u: 'a U', + t: 'a T', + h: 'an H', + courtyard: 'rooms around an open court', + wing: 'a wing at an angle', + bay: 'a bay with corners cut at 45°', + polygon: 'a free outline', + detached: 'volumes standing apart', +} + +/** + * What each plan needs of the built footprints at least: a rectangle nothing; the letters their + * re-entrant corners (or a court, which closes what they leave open); a court its hole; a wing or + * a bay an edge at an angle; a free outline anything but one plain rectangle; detached two masses. + */ +const PLAN_MET: Record boolean> = { + rectangle: () => true, + l: (plan) => plan.reflex >= 1 || plan.holes >= 1, + t: (plan) => plan.reflex >= 2 || plan.holes >= 1, + u: (plan) => plan.reflex >= 2 || plan.holes >= 1, + h: (plan) => plan.reflex >= 4 || plan.holes >= 1, + courtyard: (plan) => plan.holes >= 1, + wing: (plan) => plan.angled, + bay: (plan) => plan.angled, + polygon: (plan) => plan.corners > 4 || plan.angled || plan.components > 1, + detached: (plan) => plan.components >= 2, +} + +/** What `PLAN_MET` asks of the footprints, in words: how a finding says what the built plan lacks. */ +const PLAN_NEEDS: Record = { + rectangle: 'nothing', + l: 'a re-entrant corner or a court', + t: '2 re-entrant corners or a court', + u: '2 re-entrant corners or a court', + h: '4 re-entrant corners or a court', + courtyard: 'an open court', + wing: 'an edge at an angle', + bay: 'an edge at an angle', + polygon: 'more than 4 corners, an angled edge or separate masses', + detached: '2 separate masses', +} + +const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}` + +/** A stated massing in words: "a U, 3 volumes, at different heights". */ +const statedWords = (massing: Massing) => + [ + massing.plan ? PLAN_WORDS[massing.plan] : null, + massing.volumes !== undefined ? plural(massing.volumes, 'volume') : null, + massing.heights === 'several' ? 'at different heights' : null, + ] + .filter(Boolean) + .join(', ') + +/** How much a plan asks of the scene, for telling a revised form plainer: the letters by their notches, a court the most. */ +const PLAN_RANK: Record = { + rectangle: 0, + bay: 1, + wing: 1, + polygon: 1, + detached: 1, + l: 2, + t: 3, + u: 3, + h: 4, + courtyard: 4, +} + +const unit = ([x, z]: readonly [number, number], [nx, nz]: readonly [number, number]) => { + const length = Math.hypot(nx - x, nz - z) || 1 + return [(nx - x) / length, (nz - z) / length] as const +} + +/** The shoelace sum: positive when the ring runs one way round, negative the other. */ +const winding = (ring: Ring) => + ring.reduce((sum, [x, z], i) => { + const [nx, nz] = ring[(i + 1) % ring.length]! + return sum + (x * nz - nx * z) + }, 0) + +function planFacts(footprints: Ring[]): PlanFacts { + const shapes = union(footprints) + const rings = shapes.map((shape) => shape.outer) + let corners = 0 + let reflex = 0 + let longest = { length: 0, angle: 0 } + const angles: number[] = [] + for (const ring of rings) { + const sign = Math.sign(winding(ring)) + ring.forEach((point, i) => { + const before = ring[(i + ring.length - 1) % ring.length]! + const after = ring[(i + 1) % ring.length]! + const [ax, az] = unit(before, point) + const [bx, bz] = unit(point, after) + const turn = ax * bz - az * bx + if (Math.abs(turn) <= STRAIGHT) return + corners++ + if (Math.sign(turn) !== sign) reflex++ + }) + ring.forEach(([x, z], i) => { + const [nx, nz] = ring[(i + 1) % ring.length]! + const length = Math.hypot(nx - x, nz - z) + const angle = (Math.atan2(nz - z, nx - x) * 180) / Math.PI + angles.push(angle) + if (length > longest.length) longest = { length, angle } + }) + } + const angled = angles.some((angle) => { + const off = (((angle - longest.angle) % 90) + 90) % 90 + return Math.min(off, 90 - off) > ANGLED_DEGREES + }) + return { + components: rings.length, + corners, + reflex, + holes: shapes.reduce((sum, shape) => sum + shape.holes.length, 0), + angled, + } +} + +export type BuiltForm = { + /** The building read: the one with the most floor above grade. */ + buildingId: string + volumes: number + shapes: string[] + /** The volumes the building's rooms form, each with its shape and top. */ + named: { name: string; shape: string; topM: number }[] + plan: PlanFacts + /** Highest and lowest top of a volume in the building's stack (m). */ + tops: [number, number] +} + +/** The building the brief is read against: the one with the most floor above grade, its above-grade volumes. */ +export function builtForm(nodes: SceneNodes): BuiltForm | null { + const above = (building: MassingBuilding) => + building.volumes.flatMap((volume) => { + const storeys = volume.storeyFootprints.filter( + (storey) => !isLevelBelowGrade(nodes as Record, storey.levelId), + ) + return storeys.length ? [{ volume, storeys }] : [] + }) + const footprint = (volumes: ReturnType) => + volumes.flatMap(({ storeys }) => + storeys.flatMap((storey) => + storey.zoneIds.flatMap((id) => { + const zone = nodes[id] + return zone?.type === 'zone' ? [zone.polygon as Ring] : [] + }), + ), + ) + const [main] = readMassing(nodes) + .map((building) => { + const volumes = above(building) + return { + buildingId: building.buildingId, + volumes, + footprints: footprint(volumes), + ground: volumes.reduce( + (sum, { storeys }) => + sum + storeys.reduce((total, storey) => total + storey.areaSqMeters, 0), + 0, + ), + } + }) + .filter(({ footprints }) => footprints.length > 0) + .sort((a, b) => b.ground - a.ground) + if (!main) return null + const tops = main.volumes.map(({ volume }) => volume.topElevationMeters) + return { + buildingId: main.buildingId, + volumes: main.volumes.length, + shapes: main.volumes.map(({ volume }) => volume.shape ?? 'inferred'), + named: main.volumes.map(({ volume }) => ({ + name: String(volume.name), + shape: volume.shape ?? 'inferred', + topM: volume.topElevationMeters, + })), + plan: planFacts(main.footprints), + tops: [Math.max(...tops), Math.min(...tops)], + } +} + +const planWords = (plan: PlanFacts) => + [ + plan.reflex ? plural(plan.reflex, 're-entrant corner') : 'no re-entrant corner', + ...(plan.holes ? [plural(plan.holes, 'court')] : []), + ...(plan.angled ? ['edges at an angle'] : []), + ...(plan.components > 1 ? [`${plan.components} separate masses`] : []), + ].join(', ') + +/** A scene the massing cannot be read from (a room stored without its polygon) says nothing here: verify_scene lists what is wrong with it. */ +function readable(read: () => T): T | null { + try { + return read() + } catch { + return null + } +} + +/** + * The building the brief is read against: the one with the most floor above grade, else the first + * building the scene has. The facade is read on it as the form is. + */ +export function mainBuildingId(nodes: SceneNodes): string | undefined { + return ( + readable(() => builtForm(nodes))?.buildingId ?? queryNodes(nodes, { type: 'building' })[0]?.id + ) +} + +export type FormFinding = { + code: 'form_simpler_than_brief' + message: string + /** What differs: volumes, plan, heights. */ + differs: ('volumes' | 'plan' | 'heights')[] +} + +/** + * The finding where the built form is plainer than the brief's stated massing: fewer volumes, + * a plan that lacks what the stated plan needs, one height where several are stated. Null when + * the brief states no massing, nothing above grade is built, or the scene holds up what is stated. + */ +export function formFinding( + brief: Pick | null | undefined, + nodes: SceneNodes, +): FormFinding | null { + const stated: Massing | undefined = brief?.axes?.form?.massing + if (!stated) return null + const built = readable(() => builtForm(nodes)) + if (!built) return null + const differs: FormFinding['differs'] = [] + if (stated.volumes !== undefined && built.volumes < stated.volumes) differs.push('volumes') + if (stated.plan !== undefined && !PLAN_MET[stated.plan](built.plan)) differs.push('plan') + const spread = built.tops[0] - built.tops[1] + if (stated.heights === 'several' && spread <= SAME_HEIGHT) differs.push('heights') + if (!differs.length) return null + const has = [ + `${plural(built.volumes, 'volume')} (${built.shapes.join(', ')})`, + `a plan with ${planWords(built.plan)}`, + spread <= SAME_HEIGHT + ? `one height (${built.tops[0].toFixed(1)} m)` + : `heights from ${built.tops[1].toFixed(1)} to ${built.tops[0].toFixed(1)} m`, + ].join(', ') + const lacking = differs.map((axis) => lackWords(axis, stated, built)).join('; ') + return { + code: 'form_simpler_than_brief', + message: `The brief states a form of ${statedWords(stated)}; the scene has ${has}. Compared on building ${built.buildingId}: ${lacking}. Either the scene or the brief's form changes: a new design_brief replaces the form.`, + differs, + } +} + +/** One differing axis as stated against built, with the numbers and the volumes that stand. */ +function lackWords( + axis: FormFinding['differs'][number], + stated: Massing, + built: BuiltForm, +): string { + if (axis === 'volumes') { + const standing = built.named + .map(({ name, shape, topM }) => `${name} (${shape}, top ${topM.toFixed(1)} m)`) + .join(', ') + const missing = (stated.volumes ?? 0) - built.volumes + return `volumes: ${stated.volumes} stated, ${built.volumes} built (${standing}), ${missing} missing` + } + if (axis === 'plan' && stated.plan) + return `plan: ${PLAN_WORDS[stated.plan]} needs ${PLAN_NEEDS[stated.plan]}, the footprints have ${planWords(built.plan)}` + return `heights: several stated, every volume tops out at ${built.tops[0].toFixed(1)} m` +} + +export type FormRevision = { + code: 'form_revised_simpler' + message: string + /** What the later form asks less of: volumes, plan, heights. */ + differs: ('volumes' | 'plan' | 'heights')[] +} + +/** + * The finding where a later brief of the turn states a plainer massing than the first one did: + * fewer volumes, a plan lower on the ladder (a letter, a court or an angle for a rectangle), one + * height for several. A brief is free to revise, so this is a fact to show, not a refusal. Null + * when either brief states no massing (a form bounded by the person's words has none to compare), + * or the later one asks as much. + */ +export function formRevision( + first: Massing | undefined, + brief: Pick | null | undefined, +): FormRevision | null { + const latest: Massing | undefined = brief?.axes?.form?.massing + if (!(first && latest)) return null + const differs: FormRevision['differs'] = [] + if (first.volumes !== undefined && latest.volumes !== undefined && latest.volumes < first.volumes) + differs.push('volumes') + if (first.plan && latest.plan && PLAN_RANK[latest.plan] < PLAN_RANK[first.plan]) + differs.push('plan') + if (first.heights === 'several' && latest.heights === 'one') differs.push('heights') + if (!differs.length) return null + return { + code: 'form_revised_simpler', + message: `The form was revised during the turn: from ${statedWords(first)} to ${statedWords(latest)}.`, + differs, + } +} diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index 281f8ac921..f586de9087 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -11,6 +11,7 @@ import { createRoof } from './create-roof' import { createRoom } from './create-room' import { createStair } from './create-stair' import { deleteNode } from './delete-node' +import './brief-findings' import { designBrief, gatedByBrief } from './design-brief' import { placeDesign, validateDesignOperation } from './designs' import { duplicateLevel } from './duplicate-level' @@ -51,6 +52,8 @@ export * from './apply-outcome' export * from './author-scene' export * from './author-scene-checks' export * from './authored-scene-merge' +export * from './brief-findings' +export * from './brief-gaps' export * from './collections' export * from './corner-window' export * from './create-roof' @@ -58,6 +61,8 @@ export * from './create-room' export * from './create-stair' export * from './delete-node' export * from './design-brief' +export * from './design-facade' +export * from './design-form' export * from './designs' export * from './door-clearance' export * from './duplicate-level' diff --git a/packages/core/src/agent-operations/massing-read.ts b/packages/core/src/agent-operations/massing-read.ts new file mode 100644 index 0000000000..88a5d35197 --- /dev/null +++ b/packages/core/src/agent-operations/massing-read.ts @@ -0,0 +1,320 @@ +import type { VOLUME_SHAPES } from '../agent-tools/design-brief' +import { refuse } from '../agent-tools/refusal' +import { type AnyNode, getActiveRoofHeight, type RoofNode } from '../schema' +import { DEFAULT_LEVEL_HEIGHT } from '../services/level-height' +import { getLevelElevations } from '../services/storey' +import { pointInPolygon, polygonArea, polygonBounds, type Vec2 } from './plan-geometry' +import { levelRole, levelsOf, queryNodes } from './scene-queries' +import type { SceneNodes } from './types' + +type Pt = [number, number] + +type Shape = (typeof VOLUME_SHAPES)[number] + +const round2 = (value: number) => Math.round(value * 100) / 100 + +const boundsOf = (polygons: readonly (readonly Pt[])[]) => { + const all = polygons.flatMap((polygon) => polygon.map((point) => point as Vec2)) + const { width: _w, depth: _d, centerX: _x, centerZ: _z, ...bounds } = polygonBounds(all) + return { + minX: round2(bounds.minX), + maxX: round2(bounds.maxX), + minZ: round2(bounds.minZ), + maxZ: round2(bounds.maxZ), + } +} + +function segmentsMeet(a: Pt, b: Pt, c: Pt, d: Pt, proper: boolean): boolean { + const cross = (p: Pt, q: Pt, r: Pt) => + (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) + const d1 = cross(c, d, a) + const d2 = cross(c, d, b) + const d3 = cross(a, b, c) + const d4 = cross(a, b, d) + if (proper) + return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0)) + const on = (p: Pt, q: Pt, r: Pt) => + Math.abs(cross(p, q, r)) < 1e-9 && + r[0] >= Math.min(p[0], q[0]) - 1e-9 && + r[0] <= Math.max(p[0], q[0]) + 1e-9 && + r[1] >= Math.min(p[1], q[1]) - 1e-9 && + r[1] <= Math.max(p[1], q[1]) + 1e-9 + if ( + ((d1 >= 0 && d2 <= 0) || (d1 <= 0 && d2 >= 0)) && + ((d3 >= 0 && d4 <= 0) || (d3 <= 0 && d4 >= 0)) + ) + return true + return on(c, d, a) || on(c, d, b) || on(a, b, c) || on(a, b, d) +} + +function eachEdge(polygon: readonly Pt[], fn: (a: Pt, b: Pt) => boolean): boolean { + for (let i = 0; i < polygon.length; i++) + if (fn(polygon[i]!, polygon[(i + 1) % polygon.length]!)) return true + return false +} + +/** Area overlap: a corner strictly inside the other, or edges crossing. A shared edge is not overlap. */ + +/** Area overlap: a corner strictly inside the other, or edges crossing. A shared edge is not overlap. */ +export function polygonsOverlap(a: readonly Pt[], b: readonly Pt[]): boolean { + const ab = polygonBounds(a as Vec2[]) + const bb = polygonBounds(b as Vec2[]) + if (ab.maxX <= bb.minX || bb.maxX <= ab.minX || ab.maxZ <= bb.minZ || bb.maxZ <= ab.minZ) + return false + if (a.some((point) => pointInPolygon(point as Vec2, b as Vec2[], false))) return true + if (b.some((point) => pointInPolygon(point as Vec2, a as Vec2[], false))) return true + return eachEdge(a, (a1, a2) => eachEdge(b, (b1, b2) => segmentsMeet(a1, a2, b1, b2, true))) +} + +/** Overlap, or contact: a corner on the other's boundary, or edges meeting at all. */ + +/** Overlap, or contact: a corner on the other's boundary, or edges meeting at all. */ +export function polygonsTouch(a: readonly Pt[], b: readonly Pt[]): boolean { + if (polygonsOverlap(a, b)) return true + const ab = polygonBounds(a as Vec2[]) + const bb = polygonBounds(b as Vec2[]) + if ( + ab.maxX < bb.minX - 1e-9 || + bb.maxX < ab.minX - 1e-9 || + ab.maxZ < bb.minZ - 1e-9 || + bb.maxZ < ab.minZ - 1e-9 + ) + return false + if (a.some((point) => pointInPolygon(point as Vec2, b as Vec2[], true))) return true + if (b.some((point) => pointInPolygon(point as Vec2, a as Vec2[], true))) return true + return eachEdge(a, (a1, a2) => eachEdge(b, (b1, b2) => segmentsMeet(a1, a2, b1, b2, false))) +} + +const buildingLevelsOf = (nodes: SceneNodes, buildingId: string) => + levelsOf(nodes).filter((level) => level.parentId === buildingId) + +const occupiedOf = (nodes: SceneNodes, buildingId: string) => + buildingLevelsOf(nodes, buildingId).filter((level) => levelRole(nodes, level).role === 'occupied') + +type VolumeMeta = { + id: string + name: string + shape: Shape + storeyIndex: number + partIndex: number + court?: boolean + setbackMeters?: number + cantileverMeters?: number + cantileverSupport?: string + courtPolygon?: Pt[] +} + +type ZoneLike = AnyNode & { type: 'zone'; polygon: Pt[] } + +const volumeMetaOf = (node: AnyNode): VolumeMeta | null => { + const meta = (node as { metadata?: Record }).metadata?.volume + if (!meta || typeof meta !== 'object') return null + const volume = meta as VolumeMeta + return typeof volume.id === 'string' ? volume : null +} + +function roofFacts(nodes: SceneNodes, roof: AnyNode) { + const childIds = (roof as { children?: string[] }).children ?? [] + const segs = childIds + .map((id: string) => nodes[id]) + .filter((node: AnyNode | undefined) => node?.type === 'roof-segment') as (AnyNode & { + roofType?: string + pitch?: number + })[] + return { + roofIds: [roof.id], + types: [...new Set(segs.map((segment) => segment.roofType ?? 'gable'))], + pitches: [...new Set(segs.map((segment) => segment.pitch ?? 40))], + segmentIds: segs.map((segment) => segment.id), + heightMeters: segs.length + ? round2(Math.max(...segs.map((segment) => getActiveRoofHeight(segment as never)))) + : 0, + } +} + +/** + * The building as volumes. Tagged rooms report their recorded volume; the rest are grouped by + * touching footprints on a level and overlapping footprints between levels, and marked inferred. + */ +export function readMassing(nodes: SceneNodes, buildingId?: string) { + const buildings = queryNodes(nodes, { type: 'building' }).filter( + (node) => !buildingId || node.id === buildingId, + ) + if (buildingId && !buildings.length) + refuse('building_not_found', `Building not found: ${buildingId}.`, { buildingId }) + const elevations = getLevelElevations(nodes as Record) as Map< + string, + { baseY: number; height: number } + > + + const describeBuilding = (building: AnyNode) => { + const occupied = occupiedOf(nodes, building.id) + const levelIndex = new Map( + occupied.map((level, index) => [level.id as string, index]), + ) + const zones = queryNodes(nodes, { type: 'zone' }).filter( + (node) => !!node.parentId && levelIndex.has(node.parentId), + ) + const roofs = queryNodes(nodes, { type: 'roof' }) + + type Group = { zones: ZoneLike[]; meta: VolumeMeta | null } + const groups: Group[] = [] + const tagged = new Map() + const untagged: ZoneLike[] = [] + for (const zone of zones) { + const meta = volumeMetaOf(zone) + if (!meta) { + untagged.push(zone) + continue + } + const group = tagged.get(meta.id) ?? { zones: [], meta } + group.zones.push(zone) + tagged.set(meta.id, group) + } + groups.push(...tagged.values()) + const parent = untagged.map((_, i) => i) + const find = (i: number): number => { + let root = i + while (parent[root] !== root) root = parent[root]! + return root + } + for (let i = 0; i < untagged.length; i++) + for (let j = i + 1; j < untagged.length; j++) { + const a = untagged[i]! + const b = untagged[j]! + const la = levelIndex.get(a.parentId!)! + const lb = levelIndex.get(b.parentId!)! + const linked = + la === lb + ? polygonsTouch(a.polygon, b.polygon) + : Math.abs(la - lb) === 1 && polygonsOverlap(a.polygon, b.polygon) + if (linked) parent[find(i)] = find(j) + } + const inferred = new Map() + untagged.forEach((zone, i) => { + const root = find(i) + inferred.set(root, [...(inferred.get(root) ?? []), zone]) + }) + for (const groupZones of inferred.values()) groups.push({ zones: groupZones, meta: null }) + + const volumes = groups.map((group, groupOrder) => { + const byLevel = new Map() + for (const zone of group.zones) { + if (volumeMetaOf(zone)?.court) continue + byLevel.set(zone.parentId!, [...(byLevel.get(zone.parentId!) ?? []), zone]) + } + const levelIds = [...byLevel.keys()].sort((a, b) => levelIndex.get(a)! - levelIndex.get(b)!) + const storeyFootprints = levelIds.map((levelId) => { + const levelZones = byLevel.get(levelId)! + return { + levelId, + levelIndex: levelIndex.get(levelId)!, + heightMeters: round2(elevations.get(levelId)?.height ?? DEFAULT_LEVEL_HEIGHT), + baseElevationMeters: round2(elevations.get(levelId)?.baseY ?? 0), + areaSqMeters: round2( + levelZones.reduce((sum, zone) => sum + polygonArea(zone.polygon as Vec2[]), 0), + ), + bounds: boundsOf(levelZones.map((zone) => zone.polygon)), + zoneIds: levelZones.map((zone) => zone.id), + } + }) + const topLevelId = levelIds.at(-1)! + const topPolygons = byLevel.get(topLevelId)!.map((zone) => zone.polygon) + const volumeId = group.meta?.id ?? `inferred_${building.id}_${groupOrder}` + const ownRoof = + roofs.find( + (roof) => + (roof as { metadata?: Record }).metadata?.volumeId === volumeId, + ) ?? + roofs.find((roof) => { + const [x, , z] = (roof.position as number[]) ?? [] + if (x === undefined || z === undefined) return false + const reference = (roof as { metadata?: Record }).metadata + ?.referenceLevelId + const levelMatch = roof.parentId === topLevelId || reference === topLevelId + return ( + levelMatch && + topPolygons.some((polygon) => pointInPolygon([x, z], polygon as Vec2[], true)) + ) + }) + const courtPolygon = group.zones + .map(volumeMetaOf) + .find((meta) => meta?.courtPolygon)?.courtPolygon + let setbackMeters = group.meta?.setbackMeters ?? null + let cantilever = group.meta?.cantileverMeters + ? { meters: group.meta.cantileverMeters, support: group.meta.cantileverSupport ?? null } + : null + if (!group.meta && storeyFootprints.length > 1) { + const ground = storeyFootprints[0]!.bounds + const upper = storeyFootprints.at(-1)!.bounds + const insets = [ + upper.minX - ground.minX, + ground.maxX - upper.maxX, + upper.minZ - ground.minZ, + ground.maxZ - upper.maxZ, + ] + if (insets.every((inset) => inset > 0.05)) setbackMeters = round2(Math.min(...insets)) + else if (insets.some((inset) => inset < -0.05)) + cantilever = { meters: round2(-Math.min(...insets)), support: null } + } + return { + volumeId, + name: group.meta?.name ?? group.zones[0]?.name ?? volumeId, + shape: group.meta?.shape ?? null, + source: group.meta ? ('tagged' as const) : ('inferred' as const), + storeys: levelIds.length, + baseLevelIndex: levelIndex.get(levelIds[0]!)!, + totalHeightMeters: round2( + storeyFootprints.reduce((sum, storey) => sum + storey.heightMeters, 0), + ), + topElevationMeters: round2( + (elevations.get(topLevelId)?.baseY ?? 0) + + (elevations.get(topLevelId)?.height ?? DEFAULT_LEVEL_HEIGHT), + ), + storeyFootprints, + roof: ownRoof ? roofFacts(nodes, ownRoof) : null, + court: courtPolygon + ? { + polygon: courtPolygon, + areaSqMeters: round2(polygonArea(courtPolygon as Vec2[])), + bounds: boundsOf([courtPolygon]), + } + : null, + setbackMeters, + cantilever, + attachedTo: [] as string[], + } + }) + const groundPolygons = volumes.map((volume) => { + const first = volume.storeyFootprints[0]! + return first.zoneIds.map((id) => (nodes[id] as ZoneLike).polygon) + }) + volumes.forEach((volume, i) => { + volume.attachedTo = volumes + .filter( + (other, j) => + i !== j && + other.baseLevelIndex === volume.baseLevelIndex && + groundPolygons[i]!.some((a) => groundPolygons[j]!.some((b) => polygonsTouch(a, b))), + ) + .map((other) => other.volumeId) + }) + volumes.sort( + (a, b) => + b.storeys - a.storeys || + b.storeyFootprints[0]!.areaSqMeters - a.storeyFootprints[0]!.areaSqMeters || + a.storeyFootprints[0]!.bounds.minX - b.storeyFootprints[0]!.bounds.minX || + a.storeyFootprints[0]!.bounds.minZ - b.storeyFootprints[0]!.bounds.minZ || + String(a.name).localeCompare(String(b.name)), + ) + return { + buildingId: building.id, + buildingName: building.name ?? null, + volumes, + } + } + + return buildings.map(describeBuilding) +} + +export type MassingBuilding = ReturnType[number] diff --git a/packages/core/src/agent-operations/room-dressing.test.ts b/packages/core/src/agent-operations/room-dressing.test.ts new file mode 100644 index 0000000000..45c2ab0bf3 --- /dev/null +++ b/packages/core/src/agent-operations/room-dressing.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, test } from 'bun:test' +import { dressingBrief, salonBrief } from './__fixtures__/room-dressing-cases' +import { briefRevisions } from './brief-findings' +import { announcedDressing, dressingRevision } from './room-dressing' + +describe('the dressing announced for each room, and revised within the turn', () => { + const first = announcedDressing(salonBrief(['wainscot', 'chairRail', 'crown'])) + test('is kept by the room’s folded name, and only for rooms that announce one', () => { + expect(first).toEqual({ salon: ['wainscot', 'chairRail', 'crown'] }) + expect(announcedDressing(salonBrief())).toEqual({}) + }) + + test.each([ + ['fewer kinds', salonBrief(['wainscot']), true], + ['the same', salonBrief(['wainscot', 'chairRail', 'crown']), false], + ['more', salonBrief(['wainscot', 'chairRail', 'crown', 'accent']), false], + ['a different set of the same size', salonBrief(['wainscot', 'chairRail', 'accent']), true], + ['none stated for the room', salonBrief(), true], + ['the room taken out of the brief', dressingBrief(), false], + ])('%s', (_, latest, plainer) => { + expect(dressingRevision(first, latest) !== null).toBe(plainer) + }) + + test('a first brief that announced none has nothing to revise, and the revision joins the others', () => { + expect(dressingRevision(undefined, salonBrief(['wainscot']))).toBeNull() + expect( + briefRevisions({ + designBrief: salonBrief(['wainscot']), + firstDressing: first, + }).map((finding) => finding.code), + ).toEqual(['room_dressing_revised_simpler']) + }) +}) diff --git a/packages/core/src/agent-operations/room-dressing.ts b/packages/core/src/agent-operations/room-dressing.ts new file mode 100644 index 0000000000..40ac48bc5d --- /dev/null +++ b/packages/core/src/agent-operations/room-dressing.ts @@ -0,0 +1,64 @@ +import type { DesignBrief, RoomDressing } from '../agent-tools/design-brief' +import { foldRoomName } from '../building/room-use' + +/** + * The dressing each room of a brief announces, and a later brief of the turn against the first: the + * kinds of wall dressing (wainscot, chair rail, tiles to height...) a room is announced with, and + * the finding where a later brief announces less. A brief is free to revise, so it is a fact to + * show. It never refuses a write. + */ + +/** A kind as the brief's words say it, with the article. */ +const NOUNS: Record = { + wainscot: 'a wainscot', + chairRail: 'a chair rail', + crown: 'a crown moulding', + 'tiles-to-height': 'tile part way up the walls', + 'tiles-full': 'tile to the ceiling', + splashback: 'a splashback', + accent: 'an accent wall', +} + +const sentence = (words: readonly string[]) => + words.length < 2 ? words.join('') : `${words.slice(0, -1).join(', ')} and ${words.at(-1)}` + +/** The dressing each room of a brief announces, by the room's folded name. */ +export type AnnouncedDressing = Record + +export function announcedDressing( + brief: Pick | null | undefined, +): AnnouncedDressing { + return Object.fromEntries( + (brief?.rooms ?? []).flatMap((room) => + room.finishes?.dressing?.length + ? [[foldRoomName(room.name), [...room.finishes.dressing]]] + : [], + ), + ) +} + +export type DressingRevision = { code: 'room_dressing_revised_simpler'; message: string } + +/** + * The finding where a later brief of the turn announces less dressing for a room than the first + * did: a kind the first announced for it and the latest no longer does. A brief is free to revise, + * so this is a fact to show. Null when nothing was dropped or the first announced none. + */ +export function dressingRevision( + first: AnnouncedDressing | undefined, + brief: Pick | null | undefined, +): DressingRevision | null { + if (!first) return null + const latest = announcedDressing(brief) + const named = new Map((brief?.rooms ?? []).map((room) => [foldRoomName(room.name), room.name])) + const dropped = Object.entries(first).flatMap(([room, kinds]) => { + if (!named.has(room)) return [] + const lost = kinds.filter((kind) => !latest[room]?.includes(kind)) + return lost.length ? [`${named.get(room)}: ${sentence(lost.map((kind) => NOUNS[kind]))}`] : [] + }) + if (!dropped.length) return null + return { + code: 'room_dressing_revised_simpler', + message: `The rooms' dressing was revised during the turn; the brief no longer announces ${dropped.join('; ')}.`, + } +} diff --git a/packages/core/src/agent-operations/room-readings.ts b/packages/core/src/agent-operations/room-readings.ts index d0607616d2..a123063958 100644 --- a/packages/core/src/agent-operations/room-readings.ts +++ b/packages/core/src/agent-operations/room-readings.ts @@ -82,7 +82,6 @@ export type RoomReading = { faces: number facts: FinishFact[] } - /** How its walls are dressed, kind by kind, in the brief's words. */ /** A wet room's walls read against what a wet room is tiled to; absent for the other rooms. */ wet?: WetReading skirting: { faces: number; withSkirting: number } diff --git a/packages/core/src/agent-operations/scene-checkpoint.ts b/packages/core/src/agent-operations/scene-checkpoint.ts index fa075d47dd..c29e08d70d 100644 --- a/packages/core/src/agent-operations/scene-checkpoint.ts +++ b/packages/core/src/agent-operations/scene-checkpoint.ts @@ -1,7 +1,16 @@ import { z } from 'zod' -import { type DesignBrief, DesignBriefRecord } from '../agent-tools/design-brief' +import { + type DesignBrief, + DesignBriefRecord, + type Massing, + massingSchema, + ROOM_DRESSINGS, + type Treatment, + treatmentSchema, +} from '../agent-tools/design-brief' import { type AnyNode, isDefaultGutterNode } from '../schema' import { isDerivedNode } from '../store/derived-node-guard' +import { type AnnouncedDressing, announcedDressing } from './room-dressing' import { measureScene, type SceneMeasure } from './scene-measure' import { levelIdOf } from './scene-queries' import type { SceneChanges, SceneNodes } from './types' @@ -36,6 +45,27 @@ export type SessionRecord = { designBrief?: DesignBrief /** The catalog ids view_assets showed: a brief keeps a catalog piece as it is only after one. */ viewed?: string[] + /** + * The first massing a brief stated since the brief was last taken away: a later brief may + * revise the form, and this is what it is read against. Goes with the brief. + */ + firstMassing?: Massing + /** The first facade treatment a brief stated since the brief was last taken away, as the massing is kept. */ + firstTreatment?: Treatment + /** The dressing the first brief announced for each room (by folded name) since the brief was last taken away, as the treatment is kept. */ + firstDressing?: AnnouncedDressing + /** + * How many entries `made` held when the first brief since the brief was last taken away was + * written: what follows was made under it, which is how "the turn built" is told from what the + * thread built before. Goes with the brief. + */ + briefMadeAt?: number + /** + * What a module read about the scene or the turn when its tool last ran, by the module's own key: + * plain JSON, small, opaque here. The module that wrote a key reads it back from + * `context.session.readings`. + */ + readings?: Record } /** @@ -47,6 +77,8 @@ export type SessionKeep = { made?: readonly MadeEntry[] designBrief?: DesignBrief | null viewed?: readonly string[] | null + /** Keys to set, each replacing the module's last reading; a null takes the key away. */ + readings?: Readonly> } export const EMPTY_SESSION: SessionRecord = { checkpoints: {}, made: [] } @@ -59,6 +91,8 @@ export const MAX_CHECKPOINT_NODES = 5000 export const MAX_MADE = 20_000 /** The viewed list keeps the most recent ids up to here. */ export const MAX_VIEWED = 500 +/** A session keeps the readings of this many modules; the oldest key goes first. */ +export const MAX_READINGS = 16 /** * The record after a keep: a checkpoint of the same name is replaced, made entries accumulate. A node @@ -75,6 +109,17 @@ export function keepInSession(session: SessionRecord, keep: SessionKeep): Sessio return true }) const designBrief = 'designBrief' in keep ? keep.designBrief : session.designBrief + const firstMassing = designBrief + ? (session.firstMassing ?? designBrief.axes?.form?.massing) + : undefined + const firstTreatment = designBrief + ? (session.firstTreatment ?? designBrief.axes?.facade?.treatment) + : undefined + const announced = designBrief ? announcedDressing(designBrief) : undefined + const firstDressing = + designBrief && + (session.firstDressing ?? (Object.keys(announced ?? {}).length ? announced : undefined)) + const briefMadeAt = designBrief ? (session.briefMadeAt ?? session.made.length) : undefined const incomingViewed = new Set(keep.viewed ?? []) const viewed = keep.viewed === null @@ -83,16 +128,41 @@ export function keepInSession(session: SessionRecord, keep: SessionKeep): Sessio ...(session.viewed ?? []).filter((id) => !incomingViewed.has(id)), ...incomingViewed, ].slice(-MAX_VIEWED) + const readings = keptReadings(session.readings, keep.readings) return { checkpoints: keep.checkpoint ? { ...session.checkpoints, [keep.checkpoint.name]: keep.checkpoint } : session.checkpoints, made: fresh.length ? [...session.made, ...fresh].slice(0, MAX_MADE) : session.made, ...(designBrief ? { designBrief } : {}), + ...(firstMassing ? { firstMassing } : {}), + ...(firstTreatment ? { firstTreatment } : {}), + ...(firstDressing ? { firstDressing } : {}), + ...(briefMadeAt === undefined ? {} : { briefMadeAt }), ...(viewed.length ? { viewed } : {}), + ...(readings ? { readings } : {}), } } +/** A module's key: lower case first, then letters, digits, dots, dashes and underscores (`brief.refusedPieces`). */ +const READING_KEY = /^[a-z][\w.-]{0,63}$/ + +/** The readings after a keep: a key set again moves to the end, a null drops it, a key that is not a module's is ignored, and the oldest past the cap go. */ +function keptReadings( + held: SessionRecord['readings'], + keep: SessionKeep['readings'], +): SessionRecord['readings'] { + if (!keep) return held + const next = new Map(Object.entries(held ?? {})) + for (const [key, value] of Object.entries(keep)) { + if (!READING_KEY.test(key)) continue + next.delete(key) + if (value !== null && value !== undefined) next.set(key, value) + } + const kept = [...next].slice(-MAX_READINGS) + return kept.length ? Object.fromEntries(kept) : undefined +} + const FNV_PRIME = 0x01000193 /** Plain JSON in a fixed key order, numbers to a tenth of a millimetre, undefined dropped. */ @@ -234,6 +304,20 @@ const Record_ = z.object({ made: z.array(Made).max(MAX_MADE), designBrief: DesignBriefRecord.optional(), viewed: z.array(z.string()).max(MAX_VIEWED).optional(), + firstMassing: massingSchema.optional(), + firstTreatment: treatmentSchema.optional(), + firstDressing: z.record(z.string(), z.array(z.enum(ROOM_DRESSINGS))).optional(), + briefMadeAt: z.number().int().min(0).optional(), + // a bag that does not read back costs the session its readings, never its brief or its moments + readings: z + .record(z.string(), z.unknown()) + .refine( + (readings) => + Object.keys(readings).length <= MAX_READINGS && + Object.keys(readings).every((key) => READING_KEY.test(key)), + ) + .optional() + .catch(undefined), }) /** diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index d51c6b7ecb..fe40e92cad 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -71,7 +71,7 @@ export type SceneIssue = | CeilingObjectObservation | WallObjectObservation | RoomFinding - | { type: string; message: string; severity?: 'info' } + | { type: string; message: string; severity?: 'info' | 'warning' } | { type: 'schema_invalid'; message: string; nodeId: string; path: string } | { type: 'schema_unknown_kind' diff --git a/packages/core/src/agent-tools/design-brief.ts b/packages/core/src/agent-tools/design-brief.ts index 40c73ba35c..ed129dd0b3 100644 --- a/packages/core/src/agent-tools/design-brief.ts +++ b/packages/core/src/agent-tools/design-brief.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { ROOM_USES } from '../building/room-use' /** Where a brief says the objects come from. */ export const DESIGN_BRIEF_SOURCES = ['open', 'catalog', 'brand', 'existing'] as const @@ -51,6 +52,60 @@ export const beyondSchema = z export type Beyond = z.infer +const phrase = (what: string) => z.string().min(1).max(120).describe(what) + +/** How a room's walls are dressed beyond a plain finish. */ +export const ROOM_DRESSINGS = [ + 'wainscot', + 'chairRail', + 'crown', + 'tiles-to-height', + 'tiles-full', + 'splashback', + 'accent', +] as const + +export type RoomDressing = (typeof ROOM_DRESSINGS)[number] + +export const roomSchema = z.object({ + name: z + .string() + .min(1) + .max(80) + .describe('The room as it is named in the scene: the zone name ("Master bedroom").'), + use: z.enum(ROOM_USES).describe('What the room is for.'), + // Optional in the schema so an absent line is refused by the operation, with its own code. + distinct: z + .string() + .max(300) + .optional() + .describe( + 'One line: what sets this room apart from the other rooms of the same use, who it is for and its character.', + ), + finishes: z + .object({ + floor: phrase('The floor, a short phrase.'), + walls: phrase('The walls, a short phrase.'), + tiled: z.boolean().describe('Whether the floor or the walls are tiled.'), + skirting: z.boolean().describe('Whether the room has skirting.'), + dressing: z + .array(z.enum(ROOM_DRESSINGS)) + .max(ROOM_DRESSINGS.length) + .optional() + .describe( + 'How the walls are dressed beyond a plain finish; tiles-to-height is tile part way up, tiles-full tile to the ceiling, accent one face finished apart. Absent: plain walls.', + ), + }) + .describe("The room's finishes."), + pieces: z + .array(z.string().min(1).max(120)) + .min(1) + .max(24) + .describe('Its main pieces: furniture, fixtures, equipment, each a short phrase.'), +}) + +export type BriefRoom = z.infer + /** The pieces a layer names, or none. */ export const layerPieces = (value: Beyond[keyof Beyond]): string[] => Array.isArray(value) ? value : [] @@ -64,6 +119,8 @@ export const layerPieces = (value: Beyond[keyof Beyond]): string[] => export const BRIEF_AXES = [ 'action', 'size', + 'form', + 'facade', 'pieces', 'openings', 'style', @@ -103,26 +160,197 @@ const axis = (what: string) => ]) .describe(what) +/** The footprints a form can name for its plan. */ +export const VOLUME_SHAPES = [ + 'polygon', + 'rectangle', + 'l', + 'u', + 't', + 'h', + 'courtyard', + 'wing', + 'bay', +] as const + +/** The plans a form names: a footprint, or several volumes standing apart. */ +export const FORM_PLANS = [...VOLUME_SHAPES, 'detached'] as const + +export type FormPlan = (typeof FORM_PLANS)[number] + +/** The massing an open form states, field by field: what a scene can be read back against. */ +export const MASSING_FIELDS = ['plan', 'volumes', 'heights'] as const + +export const massingSchema = z.object({ + plan: z + .enum(FORM_PLANS) + .optional() + .describe( + 'The plan shape of the whole building, rectangle; l, u, t, h (letter plans); courtyard (rooms in bars around an open court); wing (a wing at an angle to a block); bay (a rectangle with two corners cut at 45°); polygon (a free outline); detached (volumes standing apart). any plan can be composed of several volumes.', + ), + volumes: z + .number() + .int() + .min(1) + .max(20) + .optional() + .describe('How many volumes the building is made of (blocks and wings): 1 for a single block.'), + heights: z + .enum(['one', 'several']) + .optional() + .describe( + 'one: the volumes all stand at one height. several: they stand at different heights (a taller block, lower wings).', + ), +}) + +export type Massing = z.infer + +const MASSING_TERMS = + 'plan, volumes and heights: the plan shape, how many volumes, one height or several' + +/** The material families a facade's cladding is read by: what a facade unit paints on a wall face, its piers and its panels. */ +export const FACADE_CLADDINGS = ['brick', 'stone', 'render', 'siding', 'wood', 'metal'] as const +/** The horizontal bands of a facade set. */ +export const FACADE_BANDS = ['base', 'course', 'cornice'] as const +/** What a facade can carry besides cladding and bands, in the facade tools' own words. */ +export const FACADE_ELEMENTS = [ + 'corners', + 'surrounds', + 'shutters', + 'balconies', + 'entrance', + 'curtain-wall', + 'porch', + 'guard', + 'posts', +] as const +/** Whether the openings follow a regular rhythm (stacked storey over storey) or a free one. */ +export const FACADE_RHYTHMS = ['regular', 'free'] as const + +/** What an open facade states of its treatment, field by field. */ +export const TREATMENT_FIELDS = ['cladding', 'rhythm'] as const + +export const treatmentSchema = z.object({ + cladding: z + .array(z.enum(FACADE_CLADDINGS)) + .max(FACADE_CLADDINGS.length) + .optional() + .describe( + 'The material families the facade is clad in: brick, stone, render, siding, wood, metal. A facade unit paints its wall face, piers and panels with them (paint.wall, piers, infill, spandrel, surround).', + ), + bands: z + .array(z.enum(FACADE_BANDS)) + .max(FACADE_BANDS.length) + .optional() + .describe( + 'The horizontal bands of a facade set: base (the foot of the lowest storey), course (a string course at a storey line), cornice (the top). Absent: none stated.', + ), + elements: z + .array(z.enum(FACADE_ELEMENTS)) + .max(FACADE_ELEMENTS.length) + .optional() + .describe( + 'What else the facade carries: corners (a corner chain: harpee, droite, bossage, brick, pilaster), surrounds (opening surrounds), shutters, balconies, entrance (an entrance unit on the front), curtain-wall (curtain-wall glazing). Absent: none stated.', + ), + rhythm: z + .enum(FACADE_RHYTHMS) + .optional() + .describe( + 'regular: the openings stand aligned storey over storey, in bays. free: they are placed one by one.', + ), +}) + +export type Treatment = z.infer + +const TREATMENT_TERMS = + 'cladding, bands, elements and rhythm: the material families, the horizontal bands, what else it carries, regular or free openings' + +const facadeAxis = z + .discriminatedUnion('kind', [ + z.object({ + kind: z.literal('bounded'), + quote: z + .string() + .max(300) + .describe("The person's own words that bound the facade, copied from the request."), + reading: fact.describe('One short line: how those words bound the facade.'), + treatment: treatmentSchema + .optional() + .describe(`What those words fix of the treatment (${TREATMENT_TERMS}), when they fix any.`), + }), + z.object({ + kind: z.literal('open'), + design: z + .string() + .max(600) + .describe( + `How the facade is designed: the exterior identity of the house, its materials, the rhythm of its openings, its elements, at least ${AXIS_DESIGN_MIN_WORDS} words.`, + ), + treatment: treatmentSchema + .optional() + .describe( + `Required: the treatment the design states (${TREATMENT_TERMS}). The building's facade set is read back against it.`, + ), + }), + ]) + .describe( + 'The facade of the building: its exterior identity, as the material families it is clad in, its bands, its elements and the rhythm of its openings. Bounded by the request\'s words when they fix it ("une façade en pierre avec volets", "a black timber-clad house"), or open with a design statement and its treatment. A request that builds or changes no building exterior bounds it by its own words: the exterior stands as it is.', + ) + +const formAxis = z + .discriminatedUnion('kind', [ + z.object({ + kind: z.literal('bounded'), + quote: z + .string() + .max(300) + .describe("The person's own words that bound the form, copied from the request."), + reading: fact.describe('One short line: how those words bound the form.'), + massing: massingSchema + .optional() + .describe(`What those words fix of the massing (${MASSING_TERMS}), when they fix any.`), + }), + z.object({ + kind: z.literal('open'), + design: z + .string() + .max(600) + .describe(`How the form is designed, at least ${AXIS_DESIGN_MIN_WORDS} words.`), + massing: massingSchema + .optional() + .describe( + `Required: the massing the design states (${MASSING_TERMS}). The built volumes are read back against it.`, + ), + }), + ]) + .describe( + 'The form of the building: its massing, as a plan shape, a number of volumes and whether they stand at different heights. Bounded by the request\'s words when they fix it ("an L-shaped house", "a single-storey bungalow"), or open with a design statement and its massing. A request that builds or changes no building (one room, a lamp) bounds it by its own words: the building stands as it is.', + ) + export const axesSchema = z .object({ action: axis( 'What the request asks to be done: add a lamp, make a bedroom, build a house.', ).optional(), size: axis('Dimensions and extents.').optional(), + form: formAxis.optional(), + facade: facadeAxis.optional(), pieces: axis( 'The pieces and counts the request names. Usually bounded as a minimum (extent); words such as "only", "nothing else", "just", "seulement", "rien d\'autre" make it exact.', ).optional(), openings: axis( 'Counts of windows and doors, when the request gives them: exact counts of the architecture.', ).optional(), - style: axis('Style and form of what is made.').optional(), + style: axis( + "Style and character of what is made; the building's massing is the form axis.", + ).optional(), materials: axis('Materials and finishes.').optional(), dressing: axis( 'What makes the space lived-in. When open, beyond carries it layer by layer; when bounded, the quote is the words that bound it and beyond may say none everywhere. The pieces the request names, read as a minimum, do not bound it.', ).optional(), }) .describe( - "The request read axis by axis: action, size, pieces, openings, style, materials, dressing, each bounded (the person's words as quote, the reading in a short line) or open (a design statement saying how it is designed). The eighth axis, the source, is the source fields: open, or bounded by sourceQuote. Every axis is stated; an axis the request does not touch is open.", + "The request read axis by axis: action, size, form, facade, pieces, openings, style, materials, dressing, each bounded (the person's words as quote, the reading in a short line) or open (a design statement saying how it is designed; the form also states its massing, the facade its treatment). The tenth axis, the source, is the source fields: open, or bounded by sourceQuote. Every axis is stated; an axis the request does not touch is open.", ) export type BriefAxes = z.infer @@ -131,13 +359,16 @@ export type AxisReading = NonNullable export const designBriefTool = { name: 'design_brief', title: 'Write the design brief', - description: `The record bottom-up building keeps before furnishing: the request's design brief, written once for the whole request (piece by piece when the request invites it), the request read axis by axis (action, size, pieces, openings, style, materials, source, dressing), each axis bounded by the person's own words or open with a design statement, a vision, and where the objects come from. It is recorded as the design record of the turn and answers with what it unlocks. It changes nothing in the scene. + description: `The record bottom-up building keeps before furnishing: the request's design brief, written once for the whole request (piece by piece when the request invites it), the request read axis by axis (action, size, form, facade, pieces, openings, style, materials, source, dressing), each axis bounded by the person's own words or open with a design statement, a vision, and where the objects come from. It is recorded as the design record of the turn and answers with what it unlocks. It changes nothing in the scene. Furnishings are placed or made after a brief: ${CATALOG_PLACEMENT_TOOLS.join(', ')} (the catalog's) and ${FURNISHING_CREATION_TOOLS.join(', ')} (the agent's own), also inside run_batch. Before one, search_assets and view_assets read the catalog and every other tool works as usual; rooms, walls, openings and finishes are not furnishings. -Bounded and open, in four readings. "a 4 by 5 m bedroom with a double bed, two nightstands, a wardrobe, one window, one door": action, size, pieces (as a minimum: those pieces must be there, more may come) and openings bounded; style, materials, source and dressing open. "add a lamp next to the sofa": action and dressing bounded by "add a lamp" (one object in a room that exists); style open, its design statement saying how this lamp is designed. "a bedroom with only a bed and a lamp": pieces exact and dressing bounded by "only a bed and a lamp"; style and materials open, the bed and the lamp designed, not defaulted. "Build a house": the action bounded only by "a house"; every other axis open, the dressing included. -source open: the pieces are made (add_object, place_design), view_assets shows the catalog's pieces for reference, and furnish_room, which places a whole stock set, stays closed. asIs keeps technical equipment only (sanitaryware, kitchen and laundry appliances, heating and similar services): each piece is named with a reason and was shown by view_assets earlier in the same turn (chat) or session (MCP); furniture is made, not kept as it is. source catalog, brand or existing: place_items, furnish_room and place_in_room are open, and the creation tools stay open for what the catalog lacks. +Bounded and open, in four readings. "a 4 by 5 m bedroom with a double bed, two nightstands, a wardrobe, one window, one door": action, size, form, facade, pieces (as a minimum: those pieces must be there, more may come) and openings bounded, the form and the facade by "a 4 by 5 m bedroom" (one room, no building designed); style, materials, source and dressing open. "add a lamp next to the sofa": action, form, facade and dressing bounded by "add a lamp" (one object in a room that exists, the building and its exterior stand as they are); style open, its design statement saying how this lamp is designed. "a bedroom with only a bed and a lamp": form and facade bounded by "a bedroom", pieces exact and dressing bounded by "only a bed and a lamp"; style and materials open, the bed and the lamp designed, not defaulted. "Build a house": the action bounded only by "a house"; every other axis open, the form, the facade and the dressing included, and rooms with an entry for each room. +source open: technical equipment (sanitaryware, kitchen, laundry and climate appliances) and plants are placed from the catalog (place_items, place_in_room), every other catalog piece is made (add_object, place_design), and furnish_room, which places a whole stock set, stays closed. source catalog, brand or existing: place_items, furnish_room and place_in_room are open, and the creation tools stay open for what the catalog lacks. +The form is the building's massing: a plan shape, a number of volumes, and whether the volumes stand at different heights. Open, its design statement says how the building is composed and massing states it: plan (${FORM_PLANS.join(', ')}), volumes (a count) and heights (one or several). Bounded, the person's own words fix the form ("an L-shaped house", "a single-storey bungalow") and massing may state what they fix; a request that builds or changes no building bounds it by its own words, the building standing as it is. Once volumes are built, verify_scene compares them with the massing the brief states and report form_simpler_than_brief where the scene has fewer volumes, a plainer plan or one height where the brief states several; the form is the brief's, so a new design_brief replaces it, and verify_scene reports form_revised_simpler where the replacing form is plainer than the first one the turn stated. +The facade is the exterior identity of the building: its materials, the bands and elements it carries, the rhythm of its openings. Open, its design statement says how the exterior is designed and treatment states it: cladding (${FACADE_CLADDINGS.join(', ')}), bands (${FACADE_BANDS.join(', ')}), elements (${FACADE_ELEMENTS.join(', ')}) and rhythm (${FACADE_RHYTHMS.join(' or ')}: openings stacked storey over storey, or placed one by one). Bounded, the person's own words fix the facade ("une façade en pierre avec volets", "a black timber-clad house") and treatment may state what they fix; a request that builds or changes no building exterior bounds it by its own words, the exterior standing as it is. verify_scene reports facade_revised_simpler where a replacing design_brief states a plainer treatment than the first one of the turn. +rooms lists the rooms the request builds or refits, when it builds or refits more than one (a single-room request or a focused edit carries none; an open form owes them): for each, name (as the scene names the room), use (${ROOM_USES.join(', ')}), distinct (one line: what sets the room apart from the other rooms of its use, who it is for and its character), finishes (floor and walls as short phrases, tiled and skirting as true or false, and dressing when its walls are dressed) and pieces (its main pieces: furniture, fixtures, equipment). Rooms of the same use are distinct rooms, each with its own distinct line. A form bounded by words that fix no plan is compared with nothing: where a turn built under such a brief, verify_scene reports form_bounded_without_plan, naming the words and what was built, and rooms_not_listed where it built two or more rooms under a brief that lists none. Naming a piece (a double bed) states its function; its form, size within reason and finish are open unless the request fixes them. The pieces a request names are what the room must contain, not all it may contain: where the dressing axis is open, beyond states that design layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each a list of pieces or { none: why }, at least ${BEYOND_MIN_LAYERS} of the 8 layers naming pieces; where the dressing is bounded (words that limit the pieces or the action, such as "only", "nothing else", "just"), none in every layer is accepted. The pieces the request names, read as a minimum, do not bound the dressing. The answer hands the pieces back as dressing. A source other than open is set by the request, not chosen: sourceQuote holds the person's own words that name it, at least two words naming a brand (the brief's brand), the catalog or what is already there ("IKEA furniture only", "que du catalogue", "use my existing furniture"); a request that names no source is open. The chat checks the quote against the person's message of the turn, as it checks every bounded axis's quote; over MCP, where there is no message, a source quote must still name the source and is not compared with a request, and an axis quote is not compared either. -In the chat a brief lasts for the turn; over MCP it lasts for the session. The next design_brief replaces it. Refused: axis_missing (an axis is absent), axis_quote_not_in_request (a bounded axis's quote is not in the person's message), axis_open_without_design (an open axis without a design statement of at least ${AXIS_DESIGN_MIN_WORDS} words), dressing_bounded_by_minimum (the dressing bounded by words inside a pieces quote read as a minimum), brand_required (source brand without a brand name), source_quote_required (a source other than open without sourceQuote), source_not_named (the quote names no brand, catalog or existing source), source_not_in_request (the quote is not in the person's message), beyond_too_thin (dressing open, fewer than ${BEYOND_MIN_LAYERS} layers naming pieces).`, +In the chat a brief lasts for the turn; over MCP it lasts for the session. The next design_brief replaces it. Refused: axis_missing (an axis is absent), axis_quote_not_in_request (a bounded axis's quote is not in the person's message), axis_open_without_design (an open axis without a design statement of at least ${AXIS_DESIGN_MIN_WORDS} words), form_massing_missing (an open form without its massing: plan, volumes, heights), form_massing_inconsistent (one volume stated as detached or at several heights), facade_treatment_missing (an open facade without its treatment: cladding or elements, and rhythm), rooms_missing (an open form with no rooms), room_distinct_missing (a room without its distinct line), rooms_identical (two rooms of one use with the same distinct and the same pieces), dressing_bounded_by_minimum (the dressing bounded by words inside a pieces quote read as a minimum), brand_required (source brand without a brand name), source_quote_required (a source other than open without sourceQuote), source_not_named (the quote names no brand, catalog or existing source), source_not_in_request (the quote is not in the person's message), beyond_too_thin (dressing open, fewer than ${BEYOND_MIN_LAYERS} layers naming pieces).`, input: { // Optional in the schema so an absent axis is refused by the operation, with the list, // on every surface, rather than by each surface's own validation error. @@ -169,17 +400,12 @@ In the chat a brief lasts for the turn; over MCP it lasts for the session. The n 'A few lines: the design intent for what is open (character, forms, materials, how the room is meant to feel).', ), beyond: beyondSchema, - asIs: z - .array( - z.object({ - assetId: z.string().min(1).describe('The catalog id of the piece, from search_assets.'), - reason: fact.describe('One line: why this piece stands as it is.'), - }), - ) - .max(24) + rooms: z + .array(roomSchema) + .max(60) .optional() .describe( - 'With source open: technical equipment placed unchanged (place_items, place_in_room), each piece shown by view_assets first, each with its reason. Sanitaryware, kitchen and laundry appliances, heating and similar services; furniture is made.', + 'One entry per room the request builds or refits, when it builds or refits more than one: a single-room request or a focused edit carries none. Rooms of the same use are distinct rooms: each says what sets it apart.', ), }, } diff --git a/packages/core/src/agent-tools/refusal.ts b/packages/core/src/agent-tools/refusal.ts index c390e6c64e..9f4b740511 100644 --- a/packages/core/src/agent-tools/refusal.ts +++ b/packages/core/src/agent-tools/refusal.ts @@ -10,11 +10,16 @@ export class AgentRefusal extends Error { readonly code: string, message: string, readonly details: Record = {}, + /** What the refusal asks its host to remember with the agent's session, as an outcome's `keep` does. */ + readonly keep?: RefusalKeep, ) { super(message) } } +/** The readings a refusal asks a host to keep (`SessionKeep.readings`): a refused call changes nothing else. */ +export type RefusalKeep = { readonly readings: Readonly> } + export function isAgentRefusal(error: unknown): error is AgentRefusal { return ( error instanceof AgentRefusal || diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 2e4fd0b123..477ceb15af 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -1004,6 +1004,11 @@ export const METADATA_REFERENCES: readonly ExistingReference[] = [ dependents: ['metadata.porchPart', 'metadata.porchSeed'], note: "The porch room a post or beam was made for by the structure kernel (lib/porch-framing-sync), which part of its framing and its shape as made; a porch gone takes its parts with it, one edited by hand stays the user's own.", }), + meta('referenceLevelId', { + ...policy('node', 'membership', 'drop', 'strip'), + targetKinds: ['level'], + note: 'The level a roof or roof level was measured from, a level id as the roof writers record it. Read to find the roof a massing volume carries.', + }), ] const described = (reason: string, paths: readonly string[]) => @@ -1086,6 +1091,10 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'Which building code the project follows (`irc-2021`, `au-ncc`, `fr`): a profile name, never a node id. Read by the code-specific usage checks; a scene that does not name one has no jurisdiction.', ['codeProfile'], ), + ...described( + "The massing volume a room or roof belongs to, as a volume tool wrote it: the volume's own id (it names no node), its name, shape and place in the stack. Read to group rooms into the volumes a form is compared on; nothing follows or remaps it.", + ['volume', 'volumeId'], + ), ...described('Read as a truthy flag only; no editor writer.', [ 'arrayModifier', 'curvedWindowMaster', diff --git a/packages/mcp/src/prompts/scene-guidance.ts b/packages/mcp/src/prompts/scene-guidance.ts index 6693540950..14323fd8c6 100644 --- a/packages/mcp/src/prompts/scene-guidance.ts +++ b/packages/mcp/src/prompts/scene-guidance.ts @@ -10,7 +10,7 @@ export const SCENE_DESIGN_GUIDANCE = [ ' - What it leaves open is design left to the agent: the size and number of storeys, the massing and roofscape, the site and outdoor spaces, the furniture and decor, and the floor, wall and ceiling finishes and materials. An open brief is room for a building with presence (composed volumes, interesting wings, roofs at different heights, good proportions, a considered site, rooms furnished and finished with intent) that stays credible and buildable, rather than a standard catalogue plan.', ' - When a choice would change the project, the person can be asked.', " - The sources to build a scene from stand side by side: the catalog (search_assets, place_items, furnish_room), procedural designs (place_design, validate_design), authored objects of the agent's own (add_object), native materials (paint). The catalog holds a limited set that varies by server: what a search returns is what exists.", - ' - design_brief records the request read axis by axis (action, size, pieces, openings, style, materials, source, dressing: each bounded by the person’s own words or open with a design statement) and where the objects come from; place_items, furnish_room, place_in_room, add_object and place_design follow it, run_batch included (search_assets and view_assets do not). Source open opens the made pieces and the catalog pieces named in asIs; catalog, brand and existing open the catalog.', + ' - design_brief records the request read axis by axis (action, size, form, facade, pieces, openings, style, materials, source, dressing: each bounded by the person’s own words or open with a design statement) and where the objects come from; place_items, furnish_room, place_in_room, add_object and place_design follow it, run_batch included (search_assets and view_assets do not). Source open opens the made pieces and places technical equipment and plants from the catalog; catalog, brand and existing open the catalog.', ' - Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them.', ' - For full homes/apartments, include realistic support spaces: kitchen, living/dining, bathrooms, hallway/entry, storage/laundry where appropriate.', ' - For multi-story buildings, create separate level-owned story shells. Do not stretch first-floor exterior walls to cover upper floors.', diff --git a/packages/mcp/src/resources/agent-guide.ts b/packages/mcp/src/resources/agent-guide.ts index 5d15a1cf93..f94df2b81b 100644 --- a/packages/mcp/src/resources/agent-guide.ts +++ b/packages/mcp/src/resources/agent-guide.ts @@ -89,7 +89,7 @@ export const AGENT_GUIDE = [ '', '- What a request states (sizes, counts, rooms, style, references, "catalog only", a single room) binds the work exactly: a request for one bedroom is one bedroom. What it leaves open is design left to the agent: the size and number of storeys, the massing and roofscape, the site and outdoor spaces, the furniture and decor, and the floor, wall and ceiling finishes and materials. Defaults are for technical values (thicknesses, clearances, heights). An open brief is room for a building with presence (composed volumes, interesting wings, roofs at different heights, good proportions, a considered site, rooms furnished and finished with intent) that stays credible and buildable, rather than a standard catalogue plan. When a choice would change the project, the person can be asked.', '- The sources to build a scene from stand side by side: the catalog (`search_assets`, `place_items`, `furnish_room`), procedural designs (`place_design`, `validate_design`), authored objects of the agent’s own (`add_object`), native materials (`paint`). The catalog holds a limited set that varies by server: what a search returns is what exists.', - '- Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them. `design_brief` records the request as a brief, read axis by axis (action, size, pieces, openings, style, materials, source, dressing: each bounded by the person’s own words or open with a design statement; the source is `open`, `catalog`, `brand` or `existing`) and furnishings are placed or made after it, inside `run_batch` too: `search_assets` and `view_assets` read the catalog at any time. Source `open` opens `add_object` and `place_design`, and places unchanged technical equipment only when the brief names it in `asIs` with a reason after `view_assets` showed it in this session; `furnish_room` stays closed. The other sources open `place_items`, `furnish_room` and `place_in_room`, with creation for what the catalog lacks. A non-open source quotes the request in `sourceQuote`. `beyond` records eight dressing layers; an open `dressing` axis names pieces in at least six, and the result returns them as `dressing`. The brief is the session’s: a scene load starts another, and the next `design_brief` replaces it.', + '- Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them. `design_brief` records the request as a brief, read axis by axis (action, size, form, facade, pieces, openings, style, materials, source, dressing: each bounded by the person’s own words or open with a design statement; the source is `open`, `catalog`, `brand` or `existing`) and furnishings are placed or made after it, inside `run_batch` too: `search_assets` and `view_assets` read the catalog at any time. Source `open` opens `add_object` and `place_design`, and places technical equipment and plants from the catalog (the catalog’s function tags tell them from furniture); every other catalog piece is made, and `furnish_room` stays closed. The other sources open `place_items`, `furnish_room` and `place_in_room`, with creation for what the catalog lacks. A non-open source quotes the request in `sourceQuote`. `beyond` records eight dressing layers; an open `dressing` axis names pieces in at least six, and the result returns them as `dressing`. The brief is the session’s: a scene load starts another, and the next `design_brief` replaces it.', '', '## Output Contract', '', diff --git a/packages/mcp/src/tools/design-brief.test.ts b/packages/mcp/src/tools/design-brief.test.ts index 307e6b03d3..269237a965 100644 --- a/packages/mcp/src/tools/design-brief.test.ts +++ b/packages/mcp/src/tools/design-brief.test.ts @@ -27,15 +27,25 @@ type Result = { structuredContent?: Record } -const asset = (id: string): AssetInput => ({ +const asset = ( + id: string, + category = 'furniture', + extra: Partial = {}, +): AssetInput => ({ id, name: id, - category: id === 'toilet' ? 'toilets' : 'furniture', + category, thumbnail: `/items/${id}/thumbnail.webp`, src: `/items/${id}/model.glb`, dimensions: [0.5, 0.5, 0.4], + ...extra, }) -const CATALOG = ['double-bed', 'bedside-table', 'dresser', 'closet', 'toilet'].map(asset) +const CATALOG = [ + ...['double-bed', 'bedside-table', 'dresser', 'closet', 'sofa'].map((id) => asset(id)), + asset('toilet', 'toilets'), + asset('fridge', 'kitchen-appliances'), + asset('palm', 'outdoor', { tags: ['tree', 'plant', 'garden'] }), +] const compiledBox = (): CompiledGeometryScript => ({ sha256: 'a'.repeat(64), @@ -69,6 +79,14 @@ const openAxis = (design: string) => ({ kind: 'open' as const, design }) const axes = { action: openAxis('the work the request calls for, designed as a whole'), size: openAxis('sizes chosen to fit the rooms they serve'), + form: { + ...openAxis('a single block composed to fit the rooms it holds'), + massing: { plan: 'rectangle' as const, volumes: 1, heights: 'one' as const }, + }, + facade: { + ...openAxis('a plain render facade with a free rhythm of windows'), + treatment: { cladding: ['render' as const], rhythm: 'free' as const }, + }, pieces: openAxis('the pieces each room needs, designed one by one'), openings: openAxis('openings placed for light and passage room by room'), style: openAxis('each piece designed in one calm character throughout'), @@ -76,8 +94,19 @@ const axes = { dressing: openAxis('the rooms dressed lived-in, stated in beyond'), } +const rooms = [ + { + name: 'Bedroom', + use: 'bedroom' as const, + distinct: 'the parents’ room, calm and oak, with its own bathroom', + finishes: { floor: 'oak parquet', walls: 'limewashed white', tiled: false, skirting: true }, + pieces: ['a king bed', 'two nightstands'], + }, +] + const brief = (source: 'open' | 'catalog' | 'brand', extra: Record = {}) => ({ axes, + rooms, source, ...(source === 'open' ? {} @@ -201,62 +230,85 @@ describe('the design brief over MCP', () => { levelId, }) expect(placed.payload.code).toBe('brief_source_open') - expect(placed.payload.error).toBe( - "The brief left the source open: double-bed can be made with add_object or place_design (view_assets shows the catalog's for reference), or, for technical equipment, named in the brief's asIs after view_assets, with a reason.", + expect(placed.payload.error).toContain( + 'The brief left the source open: double-bed cannot be placed from the catalog, pieces are made. Technical equipment (sanitaryware, appliances) and plants are placed from the catalog under an open source;', + ) + // The refusal is kept with the session: a retry, by any placing tool, is answered briefly. + const again = await call('place_items', { + items: [{ assetId: 'double-bed', x: 2, z: 2 }], + levelId, + }) + expect(again.payload.error).toBe( + "Already refused, the brief's source is open: double-bed. Technical equipment and plants are placed from the catalog; add_object and place_design make the other pieces.", ) const set = await call('furnish_room', { zoneId, roomType: 'bedroom' }) expect(set.payload.code).toBe('brief_source_open') }) - test('an open brief: a WC viewed, then named in asIs with its reason, is placed as it is', async () => { - await call('view_assets', { ids: ['toilet'] }) - expect(bridge.agentSession.read().viewed).toEqual(['toilet']) - await call( - 'design_brief', - brief('open', { asIs: [{ assetId: 'toilet', reason: 'technical equipment' }] }), - ) - const wc = await call('place_items', { items: [{ assetId: 'toilet', x: 1, z: 1 }], levelId }) - expect(wc.result.isError).toBeFalsy() + test('an open brief: a toilet and a fridge are placed from the catalog', async () => { + await call('design_brief', brief('open')) + const placed = await call('place_items', { + items: [ + { assetId: 'toilet', x: 1, z: 1 }, + { assetId: 'fridge', x: 3, z: 1 }, + ], + levelId, + }) + expect(placed.result.isError).toBeFalsy() + expect(Object.values(bridge.getNodes()).filter((node) => node.type === 'item')).toHaveLength(2) + }) + + test('an open brief: a palm is placed from the catalog', async () => { + await call('design_brief', brief('open')) + const placed = await call('place_items', { + items: [{ assetId: 'palm', x: 3, z: 4 }], + levelId, + }) + expect(placed.result.isError).toBeFalsy() expect(Object.values(bridge.getNodes()).some((node) => node.type === 'item')).toBe(true) }) - test('the owner’s bedroom: furniture named in asIs is refused, a toilet not viewed is refused, viewed it is kept', async () => { - await call('view_assets', { ids: ['double-bed', 'bedside-table', 'closet', 'toilet'] }) - const furniture = await call( - 'design_brief', - brief('open', { - asIs: ['double-bed', 'bedside-table', 'closet'].map((assetId) => ({ - assetId, - reason: 'fits the room', - })), - }), - ) - expect(furniture.result.isError).toBe(true) - expect(furniture.payload.code).toBe('brief_as_is_furniture') - expect(String(furniture.payload.error)).toContain( - 'double-bed is furniture: in an open brief furniture is made (add_object, place_design) or the request names a catalog source; asIs keeps technical equipment (sanitaryware, appliances).', - ) - expect(bridge.agentSession.read().designBrief).toBeUndefined() + test('an open brief: a sofa is still refused', async () => { + await call('design_brief', brief('open')) + const refused = await call('place_items', { + items: [{ assetId: 'sofa', x: 1, z: 1 }], + levelId, + }) + expect(refused.payload.code).toBe('brief_source_open') + expect(Object.values(bridge.getNodes()).some((node) => node.type === 'item')).toBe(false) + }) - bridge.agentSession.keep({ viewed: null }) - const unseen = await call( - 'design_brief', - brief('open', { asIs: [{ assetId: 'toilet', reason: 'technical equipment' }] }), - ) - expect(unseen.payload.code).toBe('brief_as_is_not_viewed') - expect(String(unseen.payload.error)).toContain('toilet was not viewed') - expect(String(unseen.payload.error)).toContain('view_assets') + test('an open brief: a batch places the fridge and refuses the sofa', async () => { + await call('design_brief', brief('open')) + const batch = await call('run_batch', { + calls: [ + { tool: 'place_in_room', input: { assetId: 'fridge', zoneId } }, + { tool: 'place_in_room', input: { assetId: 'sofa', zoneId } }, + ], + onRefusal: 'skip', + }) + expect(batch.result.isError).toBeFalsy() + expect(batch.payload).toMatchObject({ + applied: 1, + refused: 1, + calls: [ + { index: 0, status: 'ok' }, + { index: 1, status: 'refused', code: 'brief_source_open' }, + ], + }) + }) - await call('view_assets', { ids: ['toilet'] }) - const kept = await call( - 'design_brief', - brief('open', { asIs: [{ assetId: 'toilet', reason: 'technical equipment' }] }), - ) - expect(kept.payload.status).toBe('recorded') - expect( - (await call('place_items', { items: [{ assetId: 'toilet', x: 1, z: 1 }], levelId })).result - .isError, - ).toBeFalsy() + test('a catalog source places the toilet, and an asIs a model still sends is not kept', async () => { + const sent = await call('design_brief', { + ...brief('open'), + asIs: [{ assetId: 'toilet', reason: 'technical equipment' }], + }) + expect(sent.payload.status).toBe('recorded') + expect(bridge.agentSession.read().designBrief).not.toHaveProperty('asIs') + await call('design_brief', brief('catalog')) + const wc = await call('place_items', { items: [{ assetId: 'toilet', x: 1, z: 1 }], levelId }) + expect(wc.result.isError).toBeFalsy() + expect(Object.values(bridge.getNodes()).some((node) => node.type === 'item')).toBe(true) }) test('a source other than open must quote the request; the quote is required here and not checked', async () => { diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index 7f20635e36..088fe273a7 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -10,11 +10,11 @@ import { applyAgentOutcome, assetViewNeeds, assetViewsReadCatalog, - briefReadsCatalog, buildBatchObjects, createAssetViewLoader, createFetchAssetViewIO, furnishingRefusal, + namesCatalogPieces, type SceneChanges, startOfSession, writeCollections, @@ -44,6 +44,7 @@ import { getSiteTool, getWallsTool, getZonesTool, + isAgentRefusal, listLevelsTool, listUnitsTool, measureStairTool, @@ -718,11 +719,26 @@ export function registerOperationTool( // The agent's session begins with its first call, before anything is written. const first = bridge.agentSession && startOfSession(bridge.agentSession.read(), before) if (first) bridge.agentSession?.keep(first) - // Gate before catalog I/O or module compilation. + // Gate before module compilation. The gate reads the catalog's tags to let technical + // equipment and plants through; a batch's calls are checked one by one, so its catalog is + // read too. const designBrief = briefInForce(bridge) + const gateCatalog = + designBrief?.source === 'open' && + (namesCatalogPieces(tool.contract.name, input) || + (tool.contract.name === runBatchTool.name && Array.isArray(input.calls))) + ? await catalog() + : undefined if (designBrief !== undefined) { - const refusal = furnishingRefusal(tool.contract.name, input, designBrief) - if (refusal) return refusalResult(refusal) + const refusal = furnishingRefusal(tool.contract.name, input, designBrief, { + session: bridge.agentSession?.read(), + catalog: gateCatalog, + }) + if (refusal) { + // A refusal can ask the session to remember what it refused (a catalog piece under an open source). + if (refusal.keep) bridge.agentSession?.keep(refusal.keep) + return refusalResult(refusal) + } } const batchPlacesInRoom = tool.contract.name === runBatchTool.name && @@ -734,7 +750,10 @@ export function registerOperationTool( 'tool' in call && call.tool === placeInRoomTool.name && (designBrief === undefined || - !furnishingRefusal(call.tool, 'input' in call ? call.input : {}, designBrief)), + !furnishingRefusal(call.tool, 'input' in call ? call.input : {}, designBrief, { + session: bridge.agentSession?.read(), + catalog: gateCatalog, + })), ) const batchesObjects = tool.contract.name === runBatchTool.name && @@ -756,8 +775,7 @@ export function registerOperationTool( ...(designBrief !== undefined && { designBrief }), ...((tool.catalog || batchPlacesInRoom || - assetViewsReadCatalog(tool.contract.name, input) || - briefReadsCatalog(tool.contract.name, input)) && { catalog: await catalog() }), + assetViewsReadCatalog(tool.contract.name, input)) && { catalog: await catalog() }), ...(batchesObjects && { batchObjects: await buildBatchObjects( input.calls as { tool?: unknown; input?: unknown }[], @@ -774,6 +792,8 @@ export function registerOperationTool( try { outcome = inScene(bridge, () => tool.operation(nodes, input as never, context)) } catch (error) { + // A refusal can ask the session to remember what it refused (a catalog piece under an open source). + if (isAgentRefusal(error) && error.keep) bridge.agentSession?.keep(error.keep) return refusalResult(error) } let result = outcome.result From 0927ca40b6fabc0fe494fb29af073392d7deb7e6 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 18:39:03 +0100 Subject: [PATCH 13/40] The brief's docs say form, facade and rooms, and the tags decide what an open source places README, the pascal-3d skill and the surfaces page describe the brief as nine axes and the source, what an open form owes (massing, treatment, rooms), what verify_scene reads back, and that under an open source technical equipment and plants come from the catalog by its tags where they used to need a declared, previously viewed piece. Co-Authored-By: Claude Sonnet 5.5 --- packages/mcp/README.md | 2 +- skills/pascal-3d/SKILL.md | 2 +- wiki/architecture/agent-surfaces.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 9b29247202..a764c1ffff 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -415,7 +415,7 @@ is a "pitch" fraction like `"1/4 pitch"`, which is rise over span. | `measure` | Distance between two nodes' world-space reference points (hosted doors, windows and items resolved through their host; every node kind); area when applicable. | `{ fromId, toId }` | `{ distanceMeters, fromPoint?, toPoint?, areaSqMeters?, units: 'meters' }` | | `view_scene` | Look at the finished building, every storey and the roof, from a viewpoint the agent picks (a compass side, a side as seen from the house's street, a street-height eye, a photo's camera, square-on, from above), in the scene's own light or a photo's, and get the picture back, with the photo's crop beside it when a region is given. `interior: { zoneId }` stands inside a room at eye height (1.6 m by default), a step in from a corner and looking across it; `interior: { levelId }` looks inside one floor: the other floors and its roofs and ceilings left out, everything on it (walls, openings, furniture) cut at 0.65 of the storey's height, for the picture only. Pictures are 1920 × 1200 unless `maxPx` (64 to 1920) asks for a smaller longest side. The server has no renderer: the host's `sceneViews` renders it (the hosted app, through the user's open editor tab). Read-only. | `{ target?, interior?, from?, elevation?, eyeHeight?, position?, fov?, projection?, camera?, lighting?, maxPx?, photo? }` | image content plus `{ status, camera, size, tab, capturedAt }`; refusals `view_unavailable`, `no_project`, `which_building` (a street side, no target, buildings on several sites), `no_current_camera` (`camera: 'current'`: the server has no view of the person's), `camera_and_viewpoint` (a camera with a viewpoint of the agent's own), `photo_crop_unavailable`, `interior_level_invalid`, `interior_hidden`, `interior_transform_unsupported`, `interior_target_elsewhere`; on the hosted server `editor_tab_required`, `editor_tab_hidden`, `editor_tab_busy` (a tab open but busy or still loading, no link: wait a few seconds and call again, do not ask the user), `editor_tab_timeout` (a tab claimed the view and then stopped answering); what the refusal says about opening the editor follows the person's "Agents may open the editor for me" setting (ask first, allow, never) | | `search_assets` | Search the host's item library (the built-in list on a standalone server), several queries in one call; a query matches name, id, category or tags. A query that finds nothing gets a hint to build the item with `add_object`. | `{ queries: [{ query, category? }] }` | `{ groups: [{ query, total, results[] }], total, hint? }`; refusal `no_catalog` | -| `design_brief` | The request read as a brief, once for the whole request: `axes` (the request read axis by axis: `action`, `size`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; over MCP an axis quote is required and not compared, there being no message), the eighth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open, the dressing of the rooms layer by layer (`beyond`: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the named pieces read as a minimum do not bound it, `dressing_bounded_by_minimum`; handed back as `dressing`), the person's words that set a source other than `open` (`sourceQuote`, required: at least two words naming the brand, the catalog or what is already there; not compared with a request here) and, with an open source, technical equipment placed as it is (`asIs`: sanitaryware, appliances, fixed services; each piece shown by `view_assets` first, each with a reason; furniture is made). Placing or making furnishings follows a brief: `place_items`, `furnish_room`, `place_in_room` (the catalog's) and `add_object`, `place_design` (made), inside `run_batch` too, are refused before one with `design_brief_required`.`search_assets` and `view_assets` stay open. Source `open` opens the made pieces, places technical equipment only when named in `asIs` and keeps `furnish_room` closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. A batch holding a refused call is refused whole. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. Changes nothing in the scene. | +| `design_brief` | The request read as a brief, once: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing`, an open `facade` its `treatment`, an open form owes `rooms`, all read back by `verify_scene` (see the wiki); over MCP an axis quote is required and not compared), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open, the dressing of the rooms layer by layer (`beyond`: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the named pieces read as a minimum do not bound it, `dressing_bounded_by_minimum`; handed back as `dressing`), the person's words that set a source other than `open` (`sourceQuote`, required, naming the brand, the catalog or what is already there; not compared here) and, with an open source, technical equipment and plants placed from the catalog by its tags (furniture is made). Furnishing follows a brief: `place_items`, `furnish_room`, `place_in_room` (the catalog's) and `add_object`, `place_design` (made), inside `run_batch` too, are refused before one with `design_brief_required`.`search_assets` and `view_assets` stay open too. Source `open` opens the made pieces, places technical equipment and plants from the catalog and keeps `furnish_room` closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. A batch checks each call under its own `onRefusal` policy. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. Changes nothing in the scene. | | `view_assets` | Pictures of 1 to 6 catalog items by id, each labelled with its size, category and the names of its paintable surfaces (its model's `slot_` materials; `paint` takes one as `role`), returned as image content. The picture and surfaces are read before the call (a hosted server fetches and resizes the thumbnail to at most 512 px; a standalone server's built-in list has no host to fetch from, so it answers sizes and says it has no picture). Opt-in: nothing changes when it is not called. | `{ ids: string[] (1 to 6) }` | `{ items: [{ id, name, category, dimensions, surfaces, picture, unavailable? }], shown, note? }` plus one labelled image per item shown; refusals `unknown_asset`, `no_catalog` | | `search_materials` | Search or browse the material library, several queries in one call: words match as the library writes them (timber is wood, render is stucco), shades and surfaces; a query without words lists a kind, a surface or the whole library by name. A search lists 12 at a time and a browse 150, a long one saying how many more (`more`) and the offset that lists them (`next`). Reads Pascal's library and the materials the host registered (the editor registers its library; this server registers none). Read-only. | `{ queries: [{ query?, kind?, surface?, offset? }] }` | `{ groups: [{ query?, kind?, surface?, offset?, results: [{ ref, label, kind, surfaces, color? }], missing?, more?, next? }] }` | | `paint` | Give walls, slabs, ceilings, roofs and every other part with surfaces (columns, fences, doors, windows, stairs, blocks, cabinets, shelves…) a finish in one call, as the editor's Paint does: a colour (the nearest library colour), a `library:` or `scene:` ref, a native material kept as a scene material (reused when an equal one exists), or erase. `role` picks the surface (a wall's `exterior`/`interior` faces, by its rooms or else its stored sides, refused when rooms stand on only part of a face, a slot by name, a roof's `top`/`edge`/`wall`, or its `fascia`, the fascia and rake boards, held by every segment; a glazed roof's `glazing-frame`, `glazing-glass` or `glazing-solid`, and without a role its frame and solid panels, the glass kept); a roof shows one finish per surface, so a segment's finish goes on its roof and a roof's clears its segments' own; a wall face is painted whole, over its room's wall finish, its painted parts keeping theirs (named in `note`). | `{ targets[], role?, color?, material?, materialName?, erase? }` (one finish) | `{ ok, painted[], finish, materialId?, material?, createdMaterial?, note?, achieved }`; refusals `target_not_found`, `unknown_role`, `side_unknown`, `unknown_material`, `materials_unavailable`, `not_paintable` | diff --git a/skills/pascal-3d/SKILL.md b/skills/pascal-3d/SKILL.md index 98e853f095..7d1534a4fa 100644 --- a/skills/pascal-3d/SKILL.md +++ b/skills/pascal-3d/SKILL.md @@ -59,7 +59,7 @@ For construction, prefer tools such as `create_story_shell`, `create_room`, `add A building of several dwellings or tenancies (a condo, an apartment building, a duplex, a hotel, shops under flats) groups its rooms into units, one per dwelling, suite or lot: once the rooms exist, `create_unit` names one as a person would (Apartment 2B, Suite 301, Shop 1; `kind` apartment, hotel-room, commercial or common) with the zone ids of its rooms, on any level (a duplex spans two), `set_unit_members` replaces them, and `list_units` reads them with their areas. A zone is in one unit at most (`zone_in_other_unit` names the unit that holds it; `move: true` moves it), a zone in no unit is common area (corridors, the lobby, the stairs), and a single-family house has no units. -Furnishings follow a design brief. `design_brief` records the request once: what it fixes, what it leaves open, where the objects come from (`source`: `open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open and, with an open source, the catalog pieces placed as they are (`asIs`, each with a reason). Before one, `search_assets` and `view_assets` read the catalog; `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` are refused (`design_brief_required`), inside `run_batch` too, where each call is checked under the batch's `onRefusal` policy. Source `open` opens the made pieces, places a catalog piece only when named in `asIs`, and keeps `furnish_room`, which places a whole stock set, closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. +Furnishings follow a design brief. `design_brief` records the request once: what it fixes, what it leaves open, where the objects come from (`source`: `open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open and, for a building, the form, the facade and the rooms it will have. Before one, `search_assets` and `view_assets` read the catalog; `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` are refused (`design_brief_required`), inside `run_batch` too, where each call is checked under the batch's `onRefusal` policy. Source `open` opens the made pieces, places technical equipment and plants from the catalog (the catalog's tags tell them from furniture), makes every other piece, and keeps `furnish_room`, which places a whole stock set, closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. Naming a piece (a double bed) states its function; its form, size within reason and finish are design unless the request fixes them. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. To give a surface a finish, call `paint` as the editor's Paint does: the targets, a `role` when it is not the default surface (a wall's `exterior` or `interior` face, a slot, a roof's `top`, `edge` or `wall`), and one finish: a library material whose `library:` you found with `search_materials`, a `color` (painted with the nearest library colour, or exactly with `exact: true`), or a native material for an exact finish, kept as a scene material and reused when an equal one exists; a textured one takes its `repeat`, an `offset` that lines its joints up, and normal and bump maps. An unknown target, role or material refuses the whole call and nothing is painted. diff --git a/wiki/architecture/agent-surfaces.md b/wiki/architecture/agent-surfaces.md index 15020ca11b..2c855c7a95 100644 --- a/wiki/architecture/agent-surfaces.md +++ b/wiki/architecture/agent-surfaces.md @@ -127,9 +127,9 @@ One check for every surface: `verify_scene` (`verifyScene` in core) reports per ## Furnishing follows a brief: `design_brief` -`design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; over MCP an axis quote is required and not compared, there being no message), the eighth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and, for an open source, `asIs` (technical equipment only: sanitaryware, kitchen and laundry appliances, fixed services; each piece shown by `view_assets` earlier in the turn or session, `SessionRecord.viewed`, each with a reason; furniture is made: `brief_as_is_furniture`, `brief_as_is_not_viewed`). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. +`design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing` (a `plan`, a number of `volumes` and one height or several, `heights`), refused `form_massing_missing`, and `verify_scene` reports `form_simpler_than_brief` where the built volumes are plainer than it states and `form_revised_simpler` where a later brief of the turn states a plainer form than the first; an open `facade` states its `treatment` (`cladding`, `bands`, `elements`, `rhythm`), refused `facade_treatment_missing`, and `verify_scene` reports `facade_revised_simpler` for a plainer revision within the turn; an open form also owes `rooms`, one entry per room (`name`, `use`, `distinct`, `finishes` with an optional `dressing` (wainscot, chairRail, crown, tiles-to-height, tiles-full, splashback, accent), `pieces`), refused `rooms_missing`, `room_distinct_missing` and, for two rooms of one use with the same line and pieces, `rooms_identical`, and `verify_scene` reports `room_dressing_revised_simpler` where a later brief of the turn announces less dressing than the first; a form bounded by words that fix no plan, and a brief with no `rooms`, are reported once the turn built under them (`form_bounded_without_plan`, `rooms_not_listed`); over MCP an axis quote is required and not compared, there being no message), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and `asIs`, which an open source once kept for technical equipment and which a stored brief may still hold (ignored). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. -The gate is a fact of the furnishing tools, in core: `furnishingRefusal(tool, input, brief)` refuses `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` before a brief (`design_brief_required`); under an open brief it refuses the catalog's placements except the `asIs` pieces and all of `furnish_room`, which places a whole stock set (`brief_source_open`); a catalog, brand or existing source opens everything. `run_batch` checks the gate per call under its usual refusal policy, not as a whole-batch host pre-check. Refused objects are not compiled and refused catalog placements do not read the library. Reading the catalog (`search_assets`, `view_assets`), rooms, walls, openings and finishes are never gated, and neither is an `add_object` that edits a standing object (`nodeId`). The operations of the gated tools refuse when the host lends `AgentContext.designBrief` (`null` while there is none, left out where the host does not gate); a host with an async step in front (the compile of an object) asks `furnishingRefusal` first. +The gate is a fact of the furnishing tools, in core: `furnishingRefusal(tool, input, brief, { session, catalog })` refuses `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` before a brief (`design_brief_required`); under an open brief it places technical equipment and plants from the catalog (the catalog's function tags and tags decide, not a list the model declares), refuses every other catalog piece naming the tools that make it, and refuses all of `furnish_room`, which places a whole stock set (`brief_source_open`); a piece refused once is answered briefly the second time, through the session's `brief.refusedPieces` reading; a catalog, brand or existing source opens everything. `run_batch` checks the gate per call under its usual refusal policy, not as a whole-batch host pre-check. Refused objects are not compiled and refused catalog placements do not read the library. Reading the catalog (`search_assets`, `view_assets`), rooms, walls, openings and finishes are never gated, and neither is an `add_object` that edits a standing object (`nodeId`). The operations of the gated tools refuse when the host lends `AgentContext.designBrief` (`null` while there is none, left out where the host does not gate); a host with an async step in front (the compile of an object) asks `furnishingRefusal` first. The brief lives where the host keeps the agent's session (`SessionRecord.designBrief`): over MCP, the bridge's session (`briefInForce`), which a scene load or clear starts anew; a bridge that keeps no session gates nothing. The hosted chat keeps it in the thread's session for the turn (the chat clears it when a new user turn starts) and gates only the scene agent's calls. From dcd3e8623e0b0abb36ef5705231e9c677baeb7fa Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 18:42:18 +0100 Subject: [PATCH 14/40] A facade revised to a plainer treatment informs facade_revised_simpler is a brief against brief: a later brief of the turn states fewer cladding families, bands or elements than the first, or a free rhythm for a regular one. The brief is free to revise, and what the building has is for the facade tools to say, so the finding informs where it was a warning. Co-Authored-By: Claude Sonnet 5.5 --- .../src/agent-operations/__fixtures__/design-facade-cases.ts | 2 +- packages/core/src/agent-operations/design-facade.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts index 7b2b53a92b..256f0fd335 100644 --- a/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts @@ -42,7 +42,7 @@ const keeping = (designBrief: DesignBrief, firstTreatment?: Treatment): AgentToo }), }) -const REVISED = { type: 'facade_revised_simpler', severity: 'warning' } +const REVISED = { type: 'facade_revised_simpler', severity: 'info' } export const DESIGN_FACADE_CASES: AgentToolCase[] = [ { diff --git a/packages/core/src/agent-operations/design-facade.ts b/packages/core/src/agent-operations/design-facade.ts index b691333e67..580c6f233f 100644 --- a/packages/core/src/agent-operations/design-facade.ts +++ b/packages/core/src/agent-operations/design-facade.ts @@ -61,6 +61,8 @@ const demands = (treatment: Treatment) => export type FacadeRevision = { code: 'facade_revised_simpler' message: string + /** A facade finding informs: the brief is free to revise, and what the building has is the facade tools' to say. */ + severity: 'info' } /** @@ -76,6 +78,7 @@ export function facadeRevision( if (!(first && latest) || demands(latest) >= demands(first)) return null return { code: 'facade_revised_simpler', + severity: 'info', message: `The facade was revised during the turn: from ${treatmentWords(first)} to ${treatmentWords(latest) || 'no stated treatment'}.`, } } From a6839bb033a428d78a863388dac7e77fc82999b2 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 15:18:08 +0100 Subject: [PATCH 15/40] A bed head against a window is no finding at all Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/spatial/usage-field/blocked.ts | 6 +++--- .../src/spatial/usage-field/blocking.test.ts | 4 ++-- .../spatial/usage-field/findings-more.test.ts | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/core/src/spatial/usage-field/blocked.ts b/packages/core/src/spatial/usage-field/blocked.ts index feca7524a6..d1892c3f62 100644 --- a/packages/core/src/spatial/usage-field/blocked.ts +++ b/packages/core/src/spatial/usage-field/blocked.ts @@ -146,6 +146,8 @@ export function blockedOpeningIssues( if (piece.z1 < sill + WINDOW_ABOVE_SILL_M || piece.z0 > head) continue if (piece.host?.wallId === wall.id) continue if (isSetAtWindow(itemText(nodes, piece.nodeId))) continue + // a bed head against a window is a design choice, not a finding + if (isBed(nodes[piece.nodeId])) continue if (!boxesMeet(pieceBoxes.get(piece)!, zoneBox)) continue const meet = intersection({ outer: piece.outer, holes: piece.holes }, zone) if (area(meet) < MIN_AREA_M2) continue @@ -169,13 +171,11 @@ export function blockedOpeningIssues( nearest = Math.max(0, nearest) const who = quote(nameOf(nodes, piece.nodeId)) const tall = piece.z1 - sill >= WINDOW_ABOVE_SILL_M - // a bed head against a window is a design choice, not a defect - const warning = tall && nearest <= WINDOW_BLOCK_M && !isBed(nodes[piece.nodeId]) + const warning = tall && nearest <= WINDOW_BLOCK_M // past a curtain's depth, a piece not hosted on the window still shuts it when it is a curtain or blind, or covers all of the glass (its width, and up to its head) const shuts = tall && nearest > WINDOW_BLOCK_M && - !isBed(nodes[piece.nodeId]) && (CURTAIN.test(itemText(nodes, piece.nodeId)) || (cover >= 1 - TOLERANCE_M / (2 * half) && piece.z1 >= head - TOLERANCE_M)) const deepIn = envelopes.reduce((deepest, envelope) => { diff --git a/packages/core/src/spatial/usage-field/blocking.test.ts b/packages/core/src/spatial/usage-field/blocking.test.ts index 8ca6aa0501..301bfecdbf 100644 --- a/packages/core/src/spatial/usage-field/blocking.test.ts +++ b/packages/core/src/spatial/usage-field/blocking.test.ts @@ -388,14 +388,14 @@ describe('usage_opening_blocked: a free piece in front of a window', () => { ]) }) - test('a piece that covers part of the glass, a sofa back, a bed head and a low piece stay information or nothing', () => { + test('a piece that covers part of the glass, a sofa back stays information, a bed head and a low piece are nothing', () => { const narrow = piece('item_n', 'Wardrobe', 'wardrobe', 2, 0.05 + 0.2 + 0.3, 0.8, 0.6, 2) expect(blocked(bedroom([narrow]))).toMatchObject([{ severity: 'info' }]) // a sofa's back across all of the glass, 0.4 m above the sill, is a design choice const sofa = piece('item_f', 'Sofa', 'sofa', 2, 0.05 + 0.2 + 0.3, 1.8, 0.6, 1.3) expect(blocked(bedroom([sofa]))).toMatchObject([{ severity: 'info' }]) const bed = piece('item_b', 'Bed', 'bed', 2, 0.05 + 0.2 + 0.3, 1.6, 0.6, 1.2) - expect(blocked(bedroom([bed]))).toMatchObject([{ severity: 'info' }]) + expect(blocked(bedroom([bed]))).toHaveLength(0) const sideboard = piece('item_s', 'Sideboard', 'sideboard', 2, 0.05 + 0.2 + 0.25, 1.6, 0.5, 0.8) expect(blocked(bedroom([sideboard]))).toHaveLength(0) }) diff --git a/packages/core/src/spatial/usage-field/findings-more.test.ts b/packages/core/src/spatial/usage-field/findings-more.test.ts index 93dcb4f23b..ca5873d586 100644 --- a/packages/core/src/spatial/usage-field/findings-more.test.ts +++ b/packages/core/src/spatial/usage-field/findings-more.test.ts @@ -216,6 +216,22 @@ describe('usage_opening_blocked', () => { const far = piece('item_d', 'Wardrobe', 'wardrobe', 2, 1.5, 1.2, 0.6, 2) expect(run(windowed([far]), 'usage_opening_blocked')).toHaveLength(0) }) + + test('a bed head, a bedside piece or a lamp at a window is nothing', () => { + const bed = piece('item_b', 'Bed', 'bed', 2, 0.05 + 0.3, 1.6, 0.6, 1.2) + expect(run(windowed([bed]), 'usage_opening_blocked')).toHaveLength(0) + const bedside = piece( + 'item_n', + 'Bedside table with lamp', + 'furniture', + 2, + 0.05 + 0.3, + 0.5, + 0.4, + 1.3, + ) + expect(run(windowed([bedside]), 'usage_opening_blocked')).toHaveLength(0) + }) }) describe('beds', () => { From c6f7407d0ef0bf3b9f703e47b767fd1305ed9fae Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 15:18:57 +0100 Subject: [PATCH 16/40] item_mid_room names the piece by its kind and lets sofas and stools float Co-Authored-By: Claude Sonnet 5.5 --- .../src/agent-operations/furniture-kind.ts | 13 +++++++ .../agent-operations/item-mid-room.test.ts | 38 ++++++++++++++++++- .../src/agent-operations/layout-clearance.ts | 7 ++-- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/packages/core/src/agent-operations/furniture-kind.ts b/packages/core/src/agent-operations/furniture-kind.ts index c14e76eaf4..247904adbc 100644 --- a/packages/core/src/agent-operations/furniture-kind.ts +++ b/packages/core/src/agent-operations/furniture-kind.ts @@ -173,6 +173,19 @@ export function furnitureKind(asset: Named): FurnitureKind { return WALL.test(text) ? 'wall' : 'free' } +/** A sofa stands off the wall on its rug and stools stand at an island: in an open plan neither is in the middle of the room. */ +const FLOATS_IN_OPEN_PLAN = /sofa|couch|loveseat|stool/ + +/** + * The word that makes a piece wall-bound ("fridge", "counter"), for a piece that is judged to stand + * against a wall; null for every other piece, a sofa or stools that float by design included. + */ +export function wallBoundWord(asset: Named): string | null { + const text = read(asset) + if (furnitureKind(asset) !== 'wall' || FLOATS_IN_OPEN_PLAN.test(text)) return null + return WALL.exec(text)?.[0].trim() ?? BEDSIDE.exec(text)?.[0] ?? 'piece' +} + /** * What a piece faces when it does not stand against a wall, as a pattern for the name of the item * it belongs with: the coffee table and the TV face the sofa, a chair faces its table. diff --git a/packages/core/src/agent-operations/item-mid-room.test.ts b/packages/core/src/agent-operations/item-mid-room.test.ts index f4e4a4d9f6..235356ed0a 100644 --- a/packages/core/src/agent-operations/item-mid-room.test.ts +++ b/packages/core/src/agent-operations/item-mid-room.test.ts @@ -4,7 +4,12 @@ import { layoutIssuesFromScene } from './layout-clearance' /** A 4 × 3 m room (zone and four walls) on one level, with the named pieces standing at the given centres. */ function room( - ...pieces: { asset: string; at: [number, number]; size?: [number, number, number] }[] + ...pieces: { + asset: string + name?: string + at: [number, number] + size?: [number, number, number] + }[] ) { const corners: [number, number][] = [ [0, 0], @@ -35,7 +40,7 @@ function room( position: [piece.at[0], 0, piece.at[1]], asset: { id: piece.asset, - name: piece.asset, + name: piece.name ?? piece.asset, category: 'furniture', thumbnail: '', src: 'asset://x', @@ -62,6 +67,35 @@ describe('item_mid_room: a wall-bound piece standing away from every wall', () = expect(issues[0]?.message).toMatch(/wall/) }) + it('names the piece by what it is, not by the hash of its script', () => { + const [issue] = midRoom( + room({ asset: 'script_1b81f9fff17d122a', name: 'U1 Fridge', at: [2, 1.5] }), + ) + expect(issue?.message).toContain('a fridge belongs against a wall') + expect(issue?.message).not.toContain('a script_') + }) + + it('lets a sofa and counter stools float: they stand off the wall in an open plan by design', () => { + expect( + midRoom( + room( + { + asset: 'script_47df4bd3c48150a2', + name: 'L-shaped linen sofa', + at: [2, 1.5], + size: [2.2, 0.9, 1.6], + }, + { + asset: 'script_71538f9e74b6d027', + name: 'Oak counter stools (3)', + at: [1, 1.5], + size: [1.6, 0.7, 0.4], + }, + ), + ), + ).toEqual([]) + }) + it('accepts a fridge set against a wall', () => { expect(midRoom(room({ asset: 'fridge', at: [2, 0.46] }))).toEqual([]) }) diff --git a/packages/core/src/agent-operations/layout-clearance.ts b/packages/core/src/agent-operations/layout-clearance.ts index d7ad9b8121..4374bd84b3 100644 --- a/packages/core/src/agent-operations/layout-clearance.ts +++ b/packages/core/src/agent-operations/layout-clearance.ts @@ -36,7 +36,7 @@ import { type PlanAabb, resolveNodeLevelId, } from './door-clearance' -import { designedTogether, furnitureKind, isFloorUnderlay, isWallDressing } from './furniture-kind' +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 { @@ -868,7 +868,8 @@ export function findItemsMidRoom(args: { nodes: Iterable; levelId?: str ...(args.levelId === undefined ? {} : { levelId: args.levelId }), })) { const node = byId.get(footprint.id) - if (node?.type !== 'item' || furnitureKind(node.asset) !== 'wall') continue + const word = node?.type === 'item' ? wallBoundWord(node.asset) : null + if (node?.type !== 'item' || !word) continue const room = zones.find((zone) => pointInPolygon([node.position[0], node.position[2]], zone.polygon as Vec2[], true), ) @@ -877,7 +878,7 @@ export function findItemsMidRoom(args: { nodes: Iterable; levelId?: str if (gap <= MID_ROOM_DISTANCE_M) continue found.push({ id: node.id, - message: `${footprint.name ?? node.asset.id} (${node.id}) stands in the middle of ${room.name || room.id}, ${gap.toFixed(1)} m from the nearest wall: a ${node.asset.id} belongs against a wall (place_in_room puts it there).`, + message: `${footprint.name ?? node.asset.id} (${node.id}) stands in the middle of ${room.name || room.id}, ${gap.toFixed(1)} m from the nearest wall: a ${word} belongs against a wall (place_in_room puts it there).`, }) } return found From 632dda041eba60b4dda1351eb4620efa57a0c621 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 15:22:24 +0100 Subject: [PATCH 17/40] A flight of three risers or fewer has no going or comfort target Co-Authored-By: Claude Sonnet 5.5 --- .../stair-short-flight-targets.test.ts | 63 +++++++++++++++++++ .../core/src/agent-operations/verify-scene.ts | 13 +++- 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/agent-operations/stair-short-flight-targets.test.ts diff --git a/packages/core/src/agent-operations/stair-short-flight-targets.test.ts b/packages/core/src/agent-operations/stair-short-flight-targets.test.ts new file mode 100644 index 0000000000..6af76cbeba --- /dev/null +++ b/packages/core/src/agent-operations/stair-short-flight-targets.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + LevelNode, + SlabNode, + StairNode, + StairSegmentNode, +} from '../schema' +import { verifyScene } from './index' + +/** One stair of a single flight on a ground floor, `steps` risers over `length` m of run. */ +function flight(steps: number, rise: number, length: number) { + const building = BuildingNode.parse({ id: 'building_f', children: ['level_f'] }) + const level = LevelNode.parse({ id: 'level_f', parentId: building.id, level: 0, height: 3 }) + const slab = SlabNode.parse({ + id: 'slab_f', + parentId: level.id, + polygon: [ + [-2, -2], + [6, -2], + [6, 6], + [-2, 6], + ], + elevation: 0.05, + }) + const stair = StairNode.parse({ + id: 'stair_f', + parentId: level.id, + name: 'Flight', + position: [1, 0, 1], + width: 1, + totalRise: rise, + children: ['sseg_f'], + }) + const segment = StairSegmentNode.parse({ + id: 'sseg_f', + parentId: stair.id, + width: 1, + length, + height: rise, + stepCount: steps, + }) + level.children = [slab.id, stair.id] + return Object.fromEntries( + [building, level, slab, stair, segment].map((node) => [node.id, node]), + ) as Record +} + +const targets = (nodes: Record) => + verifyScene(structuredClone(nodes), {}, { activeLevelId: null }) + .result.issues.filter((issue) => /^stair_(comfort|going)_target$/.test(issue.type)) + .map((issue) => issue.type) + +describe('stair design targets on a short flight', () => { + test('two steps up to a door have no going or comfort target to miss', () => { + expect(targets(flight(2, 0.2278, 0.56))).toEqual([]) + }) + + test('a staircase of fifteen steps with a short run still reports its comfort', () => { + expect(targets(flight(15, 2.95, 3))).toContain('stair_comfort_target') + }) +}) diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index fe40e92cad..cfc294ad37 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -330,6 +330,9 @@ function checkSchemas(scene: SceneNodes, hostSchema: AgentContext['nodeSchema']) * openings off their wall, stairs off their slab, blocked doors, overlapping furniture, and every * field a node's schema rejects, by node and path; a kind no schema here knows, once per kind. */ +/** A flight of this many risers or fewer is a step up to a door, not a staircase: no going or comfort target applies. */ +const SHORT_FLIGHT_STEPS = 3 + export const verifyScene: AgentOperation = ( scene, input, @@ -598,12 +601,20 @@ export const verifyScene: AgentOperation = ( const sourceLevelId = levelIdOf(nodes, stair.id) if (sourceLevelId && holdingUnread.has(buildingOf(sourceLevelId) ?? '')) continue const stairName = stair.name ?? stair.id - for (const diagnostic of measureStair(stair, nodes as Record).diagnostics) + const measured = measureStair(stair, nodes as Record) + for (const diagnostic of measured.diagnostics) { + // the going and comfort rules are a staircase's: a step or two up to a door has none to miss + if ( + measured.riserCount <= SHORT_FLIGHT_STEPS && + (diagnostic.code === 'comfort-target' || diagnostic.code === 'going-target') + ) + continue report( `stair_${diagnostic.code.replaceAll('-', '_')}`, `Stair ${stairName}: ${diagnostic.message}`, diagnostic.code.endsWith('-target'), ) + } if (sourceLevelId) { const sourceName = nodes[sourceLevelId]?.name ?? sourceLevelId const footprints = stairFootprintPolygons(nodes, stair) From 2135dfb4e28caa7655f8b7e7c8faccb35ce0c39c Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 15:30:38 +0100 Subject: [PATCH 18/40] A bed with its bedside tables is read along its own head-to-foot axis and classed by its mattress Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/spatial/usage-field/beds.ts | 52 +++++++++++++++++-- .../spatial/usage-field/findings-more.test.ts | 24 +++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) diff --git a/packages/core/src/spatial/usage-field/beds.ts b/packages/core/src/spatial/usage-field/beds.ts index e1c879bbe3..6d9f0e4e42 100644 --- a/packages/core/src/spatial/usage-field/beds.ts +++ b/packages/core/src/spatial/usage-field/beds.ts @@ -1,6 +1,6 @@ import { isFloorUnderlay } from '../../agent-operations/furniture-kind' import { area, intersection, type Ring } from '../../lib/polygon-boolean' -import type { ItemNode, ZoneNode } from '../../schema' +import { type AnyNode, getScaledDimensions, type ItemNode, type ZoneNode } from '../../schema' import type { UsageIssue } from './findings' import { m, nameOf, quote, unique } from './labels' import { type Obstacle, obstaclesInBand, rayHit } from './obstacles' @@ -93,6 +93,52 @@ function boundingRectangle(points: Ring) { } } +type Rect = ReturnType + +const CLASS_WORDS: [BedClass, RegExp][] = [ + ['king', /king/i], + ['queen', /queen/i], + ['double', /double/i], + ['single', /single|twin/i], +] + +/** + * A bed standing wider than long, bedside tables included, reads as lying across its room: its + * head-to-foot axis is the item's own z (a bed's length is never less than its width), whatever the + * box says. Null for any other piece, which keeps the smallest rectangle round its outline. + */ +function ownAxes(node: AnyNode | undefined, outline: Ring): Rect | null { + if (node?.type !== 'item') return null + const [width, , depth] = getScaledDimensions(node) + if (!(width > depth + 0.05)) return null + const angle = node.rotation[1] + const along: [number, number] = [Math.sin(angle), Math.cos(angle)] + const across: [number, number] = [Math.cos(angle), -Math.sin(angle)] + const us = outline.map(([x, z]) => x * across[0] + z * across[1]) + const vs = outline.map(([x, z]) => x * along[0] + z * along[1]) + const [u0, u1] = [Math.min(...us), Math.max(...us)] + const [v0, v1] = [Math.min(...vs), Math.max(...vs)] + const [u, v] = [(u0 + u1) / 2, (v0 + v1) / 2] + return { + centre: [u * across[0] + v * along[0], u * across[1] + v * along[1]], + long: along, + across, + length: v1 - v0, + width: u1 - u0, + } +} + +/** The mattress's class: the width of the item's own bed part when its manifest has one, else a size its name states, else the footprint's width. */ +function classOfBed(node: AnyNode | undefined, name: string, rect: Rect): BedClass { + if (node?.type === 'item') { + const part = node.source?.manifest?.parts?.find((candidate) => candidate.type === 'bed') + if (part?.bounds) return bedClassOf((part.bounds.max[0] - part.bounds.min[0]) * node.scale[0]) + const named = CLASS_WORDS.find(([, words]) => words.test(name)) + if (named && rect.width > rect.length) return named[0] + } + return bedClassOf(rect.width) +} + /** One bed's size class and free space, from its own prisms and those of its level (the bed itself may be a candidate that is not in the scene). */ export function measureBedPrisms( nodes: Nodes, @@ -107,7 +153,7 @@ export function measureBedPrisms( .filter((prism) => prism.z0 < floor + 0.9) .flatMap((prism) => prism.outer as Ring) if (outline.length < 3) return null - const rect = boundingRectangle(outline) + const rect = ownAxes(nodes[bed.id], outline) ?? boundingRectangle(outline) const band = { z0: floor + FEET_FROM_M, z1: floor + FEET_TO_M } // what lies on or under the bed (bedding, a throw) is not an obstacle beside it const overlapsBed = (prism: Prism) => @@ -192,7 +238,7 @@ export function measureBedPrisms( room, widthM: Math.round(rect.width * 100) / 100, lengthM: Math.round(rect.length * 100) / 100, - sizeClass: bedClassOf(rect.width), + sizeClass: classOfBed(nodes[bed.id], bed.name, rect), left: Math.round(sideRays(1) * 100) / 100, right: Math.round(sideRays(-1) * 100) / 100, foot: Math.round(median(footHits) * 100) / 100, diff --git a/packages/core/src/spatial/usage-field/findings-more.test.ts b/packages/core/src/spatial/usage-field/findings-more.test.ts index ca5873d586..ae386bb100 100644 --- a/packages/core/src/spatial/usage-field/findings-more.test.ts +++ b/packages/core/src/spatial/usage-field/findings-more.test.ts @@ -290,6 +290,30 @@ describe('beds', () => { ]) expect(run(roomy, 'usage_bed_clearance')).toHaveLength(0) }) + + test('a queen bed with its bedside tables is read along its own head-to-foot axis, not as a king lying across', () => { + // 2.65 m across with the bedsides, 2.11 m from head to foot, its head to the east wall + const nodes = scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [5.3, -0.3], + [5.3, 5.3], + [-0.3, 5.3], + ]), + wall('wall_s', [0, 0], [5, 0]), + wall('wall_e', [5, 0], [5, 5]), + wall('wall_n', [5, 5], [0, 5]), + wall('wall_w', [0, 5], [0, 0]), + zone('zone_1', 'Bedroom', room(5, 5)), + piece('item_c', 'Queen bed with bedside tables', 'bed', 3.895, 2.5, 2.65, 2.11, 0.5, { + rotation: [0, (3 * Math.PI) / 2, 0], + }), + ]) + const [bed] = measureBeds(nodes, usageShapes(nodes)) + expect(bed).toMatchObject({ sizeClass: 'queen', widthM: 2.65, lengthM: 2.11 }) + expect(bed!.foot).toBeGreaterThan(2.5) + expect(run(nodes, 'usage_bed_clearance')).toHaveLength(0) + }) }) describe('usage_door_swing', () => { From a645ffc4acbdc1f91df8430eb7268b8b9fcd6dbc Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 13:38:43 +0100 Subject: [PATCH 19/40] The turning-circle finding informs, exact outline or not A turning circle measures the room, not a defect of a piece: of 161 raised in the Pro runs the agent fixed 14. usage_turning_narrow is information on an exact outline too (it was a warning there). A room's entry now leads with its pocket when it has one and lists the turning circle after it. Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/agent-tools/verify-scene-usage.test.ts | 8 ++++---- packages/core/src/spatial/usage-field/findings.test.ts | 3 +++ packages/core/src/spatial/usage-field/findings.ts | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/core/src/agent-tools/verify-scene-usage.test.ts b/packages/core/src/agent-tools/verify-scene-usage.test.ts index cd5321803f..ef5b674a86 100644 --- a/packages/core/src/agent-tools/verify-scene-usage.test.ts +++ b/packages/core/src/agent-tools/verify-scene-usage.test.ts @@ -53,7 +53,7 @@ const turning = (room: string, roomId: string, over: Partial = {}): Found type: 'usage_turning_narrow', message: `No 1.50 m turning circle in “${room}”: largest 1.20 m.`, brief: 'no 1.50 m turning circle, largest 1.20 m', - severity: 'warning', + severity: 'info', nodeIds: [roomId], valueM: 1.2, thresholdM: 1.5, @@ -109,7 +109,7 @@ describe('a room’s turning circle and pocket are one entry', () => { type: 'usage_room', severity: 'warning', message: - 'Bath: no 1.50 m turning circle, largest 1.20 m; 0.57 m² of floor with no 0.60 m way out, beside “Tub”.', + 'Bath: 0.57 m² of floor with no 0.60 m way out, beside “Tub”; no 1.50 m turning circle, largest 1.20 m.', nodeIds: ['zone_bath', 'item_tub'], count: 2, }) @@ -201,7 +201,7 @@ describe('a narrow place is one entry for the rooms it leads to', () => { }) describe('every other usage finding arrives one by one', () => { - test('promoted warnings keep their approximation evidence in singles, passages and room entries', () => { + test('approximation evidence stays on singles, passages and room entries; a turning circle alone informs', () => { const { issues } = shownOf( [ clash(1, 'warning'), @@ -211,7 +211,7 @@ describe('every other usage finding arrives one by one', () => { ) expect(issues).toHaveLength(3) for (const issue of issues) { - expect(issue.severity).toBe('warning') + expect(issue.severity).toBe(issue.type === 'usage_room' ? 'info' : 'warning') expect(issue.approximate).toBe(true) } }) diff --git a/packages/core/src/spatial/usage-field/findings.test.ts b/packages/core/src/spatial/usage-field/findings.test.ts index 30f320febc..760b96bbf0 100644 --- a/packages/core/src/spatial/usage-field/findings.test.ts +++ b/packages/core/src/spatial/usage-field/findings.test.ts @@ -438,6 +438,9 @@ describe('turning circles', () => { expect(found[0]!.valueM).toBeGreaterThan(1.2) expect(found[0]!.valueM).toBeLessThan(1.4) expect(found[0]!.message).toBe('No 1.50 m turning circle in “Closet”: largest 1.30 m.') + // A turning circle measures the room: it informs, on an exact outline as well as an approximate one. + expect(found[0]!.approximate).toBe(false) + expect(found[0]!.severity).toBe('info') }) test('a wide room has one', () => { diff --git a/packages/core/src/spatial/usage-field/findings.ts b/packages/core/src/spatial/usage-field/findings.ts index d2d018cb49..4a2d6e0615 100644 --- a/packages/core/src/spatial/usage-field/findings.ts +++ b/packages/core/src/spatial/usage-field/findings.ts @@ -261,8 +261,8 @@ function turningIssue(room: RoomMeasure): UsageIssue | null { type: 'usage_turning_narrow', message: `No ${m(TURNING_M)} m turning circle in ${quote(room.name)}: largest ${m(turning.diameter)} m.`, brief: `no ${m(TURNING_M)} m turning circle, largest ${m(turning.diameter)} m`, - // A turning circle is a measurement of the room, not a use defect of a piece: on an approximate outline it informs. - severity: turning.approximate ? 'info' : 'warning', + // A turning circle measures the room, not a defect of a piece: it informs, exact outline or not. + severity: 'info', nodeIds: [room.roomId], valueM: turning.diameter, thresholdM: TURNING_M, From 6001d8b0b994103f19ef3137953876d509d3b6d7 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 19:11:01 +0100 Subject: [PATCH 20/40] The building package exports the code table The table of code thresholds (the IRC's, the NCC's, the French rules), the project's code profile and the reader that turns a threshold into a value were reachable only by their file path, so a host that applies a code (the Architect's design check) could not import them from the building package. They are exported with the rest of it. Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/building/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/core/src/building/index.ts b/packages/core/src/building/index.ts index 72b02113ab..7e2b2d550e 100644 --- a/packages/core/src/building/index.ts +++ b/packages/core/src/building/index.ts @@ -1,3 +1,4 @@ +export * from './code-profile' export * from './corner-window' export * from './door-types' export * from './floor-item-fit' From b78ad9a362a54ce104387953b40c881855aa3b2c Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 20:44:17 +0100 Subject: [PATCH 21/40] The agent operations export the room check codes A reader of a verify_scene result (a completion gate, a ledger) picks the room checks out of its issues by the same code list the checks use, as it picks the brief's findings by BRIEF_FINDING_CODES. Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/agent-operations/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index f586de9087..36a2efc824 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -88,6 +88,7 @@ export * from './plan-geometry' export * from './point-context' export * from './project-files' export * from './roof-writes' +export { ROOM_CHECK_CODES } from './room-checks' export * from './room-floor-script' export * from './room-structure' export * from './scene-materials' From 7d4b4cfb38009ef22e92c45403f407542497aca9 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 21:25:11 +0100 Subject: [PATCH 22/40] The agent operations export the room reader A reader of the committed scene (the finish's account of the rooms that hold no furniture) reads rooms with the reading the room checks use: the room, its use, whether it is indoors, the pieces standing in it. Co-Authored-By: Claude Sonnet 5.5 --- packages/core/src/agent-operations/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index 36a2efc824..c41cbe504c 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -90,6 +90,7 @@ export * from './project-files' export * from './roof-writes' export { ROOM_CHECK_CODES } from './room-checks' export * from './room-floor-script' +export { type RoomReading, readRooms } from './room-readings' export * from './room-structure' export * from './scene-materials' export * from './scene-measure' From d02bfe0ca5f8926a089b69cc35f4be8f8e205e6c Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 21:34:51 +0100 Subject: [PATCH 23/40] move_node and duplicate_node: the editor's move and duplicate as shared agent tools move_node re-seats one node on its host with the editor's own rules: openings and wall items clamp along their wall (clampDoor/WindowToWall, findWallChildOverlap, the place_items wall seat), ceiling items keep their drop, free nodes move in level plan, roof pieces in segment-local plan, walls translate by delta. duplicate_node clones subtrees with collectSubtree + cloneNodesInto (the editor's duplicate-without-move path), the clipboard's root rules and its wallId/roofSegmentId remap, stair re-aim across levels, and seats offsets through the same move plan. Both are batchable, registered on the MCP shared lane (the hosted tool list grows by two), and classified in the tool-annotation packet. Carried from the R&D branch's first commit (b4e509e25) onto this tree; the later R&D changes that depend on code this tree does not have (the relative placement, the shelf-row carry, the facade release) are not in it. move_node's y and rotation read metres and degrees only: the one notation (N1) is still owed on them (listed in NOT_LENGTHS). Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/notation-cases.ts | 4 + .../src/agent-operations/duplicate-node.ts | 201 +++++++++ packages/core/src/agent-operations/index.ts | 7 + .../agent-operations/move-duplicate.test.ts | 386 ++++++++++++++++++ .../core/src/agent-operations/move-node.ts | 31 ++ .../core/src/agent-operations/move-plan.ts | 379 +++++++++++++++++ packages/core/src/agent-tools/batch.ts | 2 + packages/core/src/agent-tools/index.ts | 4 + .../core/src/agent-tools/move-duplicate.ts | 83 ++++ packages/mcp/src/resources/agent-guide.ts | 1 + packages/mcp/src/tools/move-duplicate.test.ts | 127 ++++++ .../src/tools/read-tool-annotations.test.ts | 2 + packages/mcp/src/tools/shared-tools.ts | 16 + .../tool-annotation-justifications.json | 26 ++ 14 files changed, 1269 insertions(+) create mode 100644 packages/core/src/agent-operations/duplicate-node.ts create mode 100644 packages/core/src/agent-operations/move-duplicate.test.ts create mode 100644 packages/core/src/agent-operations/move-node.ts create mode 100644 packages/core/src/agent-operations/move-plan.ts create mode 100644 packages/core/src/agent-tools/move-duplicate.ts create mode 100644 packages/mcp/src/tools/move-duplicate.test.ts diff --git a/packages/core/src/agent-operations/__fixtures__/notation-cases.ts b/packages/core/src/agent-operations/__fixtures__/notation-cases.ts index 10e04f98b7..18342da5f9 100644 --- a/packages/core/src/agent-operations/__fixtures__/notation-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/notation-cases.ts @@ -330,6 +330,10 @@ export const NOT_LENGTHS = new Set([ 'author_scene.payload.levels[].lights[].intensity', 'author_scene.payload.levels[].lights[].softness', 'author_scene.payload.levels[].lights[].glow.strength', + // move_node reads its sill/bottom height in metres and its yaw in degrees, as its description + // says; the one notation (N1) is still owed on them. + 'move_node.y', + 'move_node.rotation', // Coordinates, in level metres. 'add_column.x', 'add_column.y', diff --git a/packages/core/src/agent-operations/duplicate-node.ts b/packages/core/src/agent-operations/duplicate-node.ts new file mode 100644 index 0000000000..7f25719357 --- /dev/null +++ b/packages/core/src/agent-operations/duplicate-node.ts @@ -0,0 +1,201 @@ +import { refuse } from '../agent-tools/refusal' +import { cloneNodesInto, collectSubtree } from '../registry/subtree' +import type { AnyNode, AnyNodeId } from '../schema' +import { isDerivedNode } from '../store/derived-node-guard' +import { achievedChanges } from './achieved' +import { planNodeMove } from './move-plan' +import { levelIdOf, levelsOf } from './scene-queries' +import type { AgentOperation, SceneChanges, SceneNodes } from './types' + +type DuplicateNodeInput = { + ids: string[] + offset?: number[] + targetLevelId?: string +} + +const DEDICATED_TOOL: Record = { + level: 'duplicate_level', + zone: 'duplicate_zone', + roof: 'create_roof', + 'roof-segment': 'create_roof', +} + +// Kinds the editor does not copy node by node: scene structure with its own tools, plus the +// kinds whose definitions declare themselves not duplicable (a spawn is one per level). +const REFUSED_TYPES = new Set([ + 'site', + 'building', + 'level', + 'zone', + 'roof', + 'roof-segment', + 'guide', + 'unit', + 'floor-opening', + 'stair-segment', + 'separator', + 'facade', + 'scan', + 'spawn', +]) + +/** The parent classes the editor copies a root from, as its clipboard roots are decided. */ +function requireCopyableRoot(nodes: SceneNodes, node: AnyNode) { + if (isDerivedNode(node) || REFUSED_TYPES.has(node.type)) { + const dedicated = DEDICATED_TOOL[node.type] + refuse( + 'duplicate_not_supported', + `A ${node.type} is not copied node by node${dedicated ? `; use ${dedicated}` : ''}.`, + { id: node.id, type: node.type }, + ) + } + const parent = node.parentId ? nodes[node.parentId] : undefined + const hostedRoot = + (parent?.type === 'wall' && + (node.type === 'door' || node.type === 'window' || node.type === 'item')) || + (parent?.type === 'ceiling' && node.type === 'item') || + parent?.type === 'roof-segment' + if (parent?.type !== 'level' && !hostedRoot) + refuse( + 'duplicate_root_invalid', + `${node.type} ${node.id} is copied as part of its parent${parent ? ` (${parent.type} ${parent.id})` : ''}; name the parent instead.`, + { id: node.id, type: node.type, parentId: node.parentId ?? null }, + ) + return parent +} + +function isDescendantOf(nodes: SceneNodes, id: string, rootIds: ReadonlySet): boolean { + let parentId = nodes[id]?.parentId + while (parentId) { + if (rootIds.has(parentId)) return true + parentId = nodes[parentId]?.parentId + } + return false +} + +/** Derived plates are rebuilt by the host's reconciler, as the editor's copy leaves them out. */ +function withoutDerived(subtree: AnyNode[]): AnyNode[] { + const pruned = new Set() + return subtree.filter((node, index) => { + // collectSubtree lists parents before children, so a pruned parent prunes its subtree. + if (index > 0 && (isDerivedNode(node) || (node.parentId && pruned.has(node.parentId)))) { + pruned.add(node.id) + return false + } + return true + }) +} + +/** Host references inside the copied set point at the copies, as the editor's paste remaps them. */ +function remapHostRefs(cloned: AnyNode[], idMap: ReadonlyMap) { + for (const node of cloned) { + const record = node as unknown as Record + for (const field of ['wallId', 'roofSegmentId'] as const) { + const value = record[field] + if (typeof value === 'string') { + const fresh = idMap.get(value as AnyNodeId) + if (fresh) record[field] = fresh + } + } + } +} + +/** A stair copied to another floor climbs from that floor, as the editor's paste re-aims it. */ +function reaimStairs(nodes: SceneNodes, cloned: AnyNode[], targetLevelId: string | undefined) { + if (!targetLevelId) return + const target = nodes[targetLevelId] + if (target?.type !== 'level') return + const next = levelsOf(nodes).find( + (level) => level.parentId === target.parentId && level.level > target.level, + ) + for (const node of cloned) { + if (node.type !== 'stair') continue + const stair = node as unknown as Record + stair.fromLevelId = targetLevelId + stair.toLevelId = next?.id ?? null + } +} + +/** + * `duplicate_node`: the editor's Duplicate — the same clone its duplicate-without-move path + * makes (`collectSubtree` + `cloneNodesInto`), its clipboard's root rules, and its paste's + * host-reference remap, with the offset seated by the same plan as `move_node`. + */ +export const duplicateNode: AgentOperation = (nodes, input) => { + const targetLevel = input.targetLevelId ? nodes[input.targetLevelId] : undefined + if (input.targetLevelId && targetLevel?.type !== 'level') + refuse('level_not_found', `Level not found: ${input.targetLevelId}.`, { + levelId: input.targetLevelId, + }) + + const requested = [...new Set(input.ids)] + for (const id of requested) { + if (!nodes[id]) refuse('node_not_found', `Node not found: ${id}.`, { id }) + } + const roots: AnyNode[] = [] + const skippedIds: string[] = [] + for (const id of requested) { + const node = nodes[id] as AnyNode + const parent = requireCopyableRoot(nodes, node) + if (isDescendantOf(nodes, id, new Set(requested.filter((other) => other !== id)))) { + skippedIds.push(id) + continue + } + if (targetLevel && parent?.type !== 'level' && levelIdOf(nodes, id) !== targetLevel.id) + refuse( + 'hosted_root_level', + `${node.type} ${id} is hosted on ${parent?.type} ${parent?.id} on another level; copy its host, or copy it without targetLevelId.`, + { id, hostId: parent?.id ?? null, targetLevelId: targetLevel.id }, + ) + roots.push(node) + } + + const clonedAll: AnyNode[] = [] + const idMap = new Map() + const copies: { sourceId: string; copyId: string; type: string; descendantCount: number }[] = [] + for (const root of roots) { + const subtree = collectSubtree(nodes as Record, root.id as AnyNodeId) + if (!subtree) refuse('node_not_found', `Node not found: ${root.id}.`, { id: root.id }) + const members = withoutDerived([subtree.root, ...subtree.descendants]) + const parentId = ( + targetLevel && nodes[root.parentId ?? '']?.type === 'level' ? targetLevel.id : root.parentId + ) as AnyNodeId + const cloned = cloneNodesInto(members, { rootId: root.id as AnyNodeId, parentId }) + for (const [source, fresh] of cloned.idMap) idMap.set(source, fresh) + clonedAll.push(...cloned.nodes) + copies.push({ + sourceId: root.id, + copyId: cloned.rootId, + type: root.type, + descendantCount: cloned.nodes.length - 1, + }) + } + remapHostRefs(clonedAll, idMap) + reaimStairs(nodes, clonedAll, input.targetLevelId) + + const offset = input.offset ?? [0, 0] + if (offset[0] || offset[1]) { + const withClones: Record = { ...nodes } + for (const node of clonedAll) withClones[node.id] = node + for (const copy of copies) { + const clone = withClones[copy.copyId] as AnyNode + const plan = planNodeMove(withClones, clone, { by: offset }, { checkOverlap: false }) + Object.assign(clone, plan.data) + } + } + + const changes: SceneChanges = { + create: clonedAll.map((node) => ({ node, parentId: node.parentId ?? undefined })), + } + return { + result: { + ok: true as const, + copies, + totalCreated: clonedAll.length, + skippedIds, + message: `Duplicated ${copies.length} node${copies.length === 1 ? '' : 's'} (${clonedAll.length} created)`, + achieved: achievedChanges(nodes, changes), + }, + changes, + } +} diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index c41cbe504c..ec36515f6b 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -15,12 +15,14 @@ import './brief-findings' import { designBrief, gatedByBrief } from './design-brief' import { placeDesign, validateDesignOperation } from './designs' import { duplicateLevel } from './duplicate-level' +import { duplicateNode } from './duplicate-node' import { findByType } from './find-by-type' import { furnishRoom } from './furnish-room' import { getNode } from './get-node' import { getLevelSummary, getWalls, getZones } from './level-reads' import { listLevels } from './list-levels' import { mergeWindowsOperation } from './merge-windows' +import { moveNode } from './move-node' import { moveRoofsToRoofLevel } from './move-roofs' import { paint } from './paint' import { placeInRoom } from './place-in-room' @@ -66,6 +68,7 @@ export * from './design-form' export * from './designs' export * from './door-clearance' export * from './duplicate-level' +export * from './duplicate-node' export * from './find-by-type' export * from './furnish-room' export * from './get-node' @@ -80,6 +83,8 @@ export * from './list-levels' export * from './material-preset' export * from './material-refs' export * from './merge-windows' +export * from './move-node' +export * from './move-plan' export * from './move-roofs' export * from './node-patch' export * from './paint' @@ -139,6 +144,8 @@ const SINGLE_OPERATIONS = { move_roofs_to_roof_level: moveRoofsToRoofLevel, place_items: gatedByBrief('place_items', placeItems), delete_node: deleteNode, + move_node: moveNode, + duplicate_node: duplicateNode, find_by_type: findByType, create_room: createRoom, furnish_room: gatedByBrief('furnish_room', furnishRoom), diff --git a/packages/core/src/agent-operations/move-duplicate.test.ts b/packages/core/src/agent-operations/move-duplicate.test.ts new file mode 100644 index 0000000000..0de890db82 --- /dev/null +++ b/packages/core/src/agent-operations/move-duplicate.test.ts @@ -0,0 +1,386 @@ +import { describe, expect, test } from 'bun:test' +import { z } from 'zod' +import { + duplicateNodeOutput, + duplicateNodeTool, + moveNodeOutput, + moveNodeTool, +} from '../agent-tools' +import { isAgentRefusal } from '../agent-tools/refusal' +import { cloneNodesInto, collectSubtree } from '../registry/subtree' +import { + type AnyNode, + type AnyNodeId, + CeilingNode, + DoorNode, + ItemNode, + LevelNode, + RoofNode, + RoofSegmentNode, + SkylightNode, + WallNode, + WindowNode, +} from '../schema' +import { applySceneChanges } from './apply-changes' +import { duplicateNode } from './duplicate-node' +import { AGENT_OPERATIONS } from './index' +import { moveNode } from './move-node' +import type { SceneNodes } from './types' + +const context = { activeLevelId: null } + +const asset = (extra: Record = {}) => ({ + id: 'chair', + name: 'Chair', + category: 'seating', + thumbnail: '/items/chair/thumbnail.webp', + src: '/items/chair/model.glb', + dimensions: [0.5, 0.9, 0.5] as [number, number, number], + ...extra, +}) + +/** + * One level holding one node per host class: a 6 m wall (z=0) with a door at 1 m, a window at + * 3 m and a wall shelf at 5 m; a ceiling with a lamp under it; a chair on the floor; a roof + * segment carrying a skylight in segment-local coordinates. + */ +function scene() { + const level = LevelNode.parse({ id: 'level_a' }) + const upper = LevelNode.parse({ id: 'level_b', level: 1 }) + const wall = WallNode.parse({ + id: 'wall_a', + parentId: level.id, + start: [0, 0], + end: [6, 0], + thickness: 0.2, + height: 2.5, + children: ['door_a', 'window_a', 'item_shelf'], + }) + const door = DoorNode.parse({ + id: 'door_a', + parentId: wall.id, + wallId: wall.id, + position: [1, 1.05, 0], + width: 0.9, + height: 2.1, + }) + const win = WindowNode.parse({ + id: 'window_a', + parentId: wall.id, + wallId: wall.id, + position: [3, 1.25, 0], + width: 1.2, + height: 1.0, + }) + const shelf = ItemNode.parse({ + id: 'item_shelf', + parentId: wall.id, + wallId: wall.id, + wallT: 5 / 6, + side: 'front', + position: [5, 1, 0], + asset: asset({ + id: 'wall-shelf', + name: 'Wall shelf', + attachTo: 'wall', + dimensions: [1, 0.6, 0.3], + }), + }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_a', + parentId: level.id, + polygon: [ + [0, 0], + [6, 0], + [6, 4], + [0, 4], + ], + children: ['item_lamp'], + }) + const lamp = ItemNode.parse({ + id: 'item_lamp', + parentId: ceiling.id, + position: [2, -0.3, 2], + asset: asset({ + id: 'pendant', + name: 'Pendant', + attachTo: 'ceiling', + dimensions: [0.3, 0.3, 0.3], + }), + }) + const chair = ItemNode.parse({ + id: 'item_chair', + parentId: level.id, + position: [1, 0, 2], + rotation: [0, 0, 0], + asset: asset(), + }) + const roof = RoofNode.parse({ id: 'roof_a', parentId: level.id, children: ['rseg_a'] }) + const segment = RoofSegmentNode.parse({ + id: 'rseg_a', + parentId: roof.id, + children: ['skylight_a'], + }) + const skylight = SkylightNode.parse({ + id: 'skylight_a', + parentId: segment.id, + roofSegmentId: segment.id, + position: [0.5, 0, 0.5], + }) + const all = [level, upper, wall, door, win, shelf, ceiling, lamp, chair, roof, segment, skylight] + return Object.fromEntries(all.map((node) => [node.id, node])) as unknown as SceneNodes +} + +const refusalCode = (run: () => unknown) => { + try { + run() + } catch (error) { + if (isAgentRefusal(error)) return error.code + throw error + } + throw new Error('expected a refusal') +} + +const moved = (nodes: SceneNodes, input: never) => { + const { result, changes } = moveNode(nodes, input, context) + return { result, after: applySceneChanges(nodes as never, changes) as SceneNodes } +} + +describe('move_node', () => { + test('is registered once, under the shared contract', () => { + expect(AGENT_OPERATIONS.move_node).toBe(moveNode) + expect(moveNodeTool.name).toBe('move_node') + expect(z.object(moveNodeTool.input).safeParse({ id: 'door_a', by: [1, 0] }).success).toBe(true) + expect(z.object(moveNodeTool.input).safeParse({ id: 'door_a' }).success).toBe(true) + }) + + test('a door slides along its wall by a plan delta, seated as add_door seats it', () => { + const { result, after } = moved(scene(), { id: 'door_a', by: [0.5, 0] } as never) + expect(z.object(moveNodeOutput).strict().parse(result)).toEqual(result) + expect(result).toMatchObject({ id: 'door_a', host: 'wall', hostId: 'wall_a', clamped: false }) + expect((after.door_a as DoorNode).position).toEqual([1.5, 1.05, 0]) + }) + + test('a door moved past the start of its wall clamps onto the wall and says so', () => { + const { result, after } = moved(scene(), { id: 'door_a', to: [-5, 0] } as never) + expect(result.clamped).toBe(true) + // A 0.9 m door: its centre stops half a width from the wall's start. + expect((after.door_a as DoorNode).position[0]).toBeCloseTo(0.45, 6) + }) + + test('a door moved onto the window is refused, unless forced as with Alt in the editor', () => { + expect( + refusalCode(() => moveNode(scene(), { id: 'door_a', to: [3, 0] } as never, context)), + ).toBe('opening_overlap') + const { after } = moved(scene(), { id: 'door_a', to: [3, 0], force: true } as never) + expect((after.door_a as DoorNode).position[0]).toBe(3) + }) + + test('a window takes a new sill height through y, clamped under the wall top', () => { + const { result, after } = moved(scene(), { id: 'window_a', by: [0, 0], y: 0.9 } as never) + expect(result.host).toBe('wall') + // Sill 0.9 m + half of its 1 m height is its stored centre. + expect((after.window_a as WindowNode).position).toEqual([3, 1.4, 0]) + const high = moved(scene(), { id: 'window_a', by: [0, 0], y: 2.2 } as never) + expect(high.result.clamped).toBe(true) + expect((high.after.window_a as WindowNode).position[1]).toBeCloseTo(2.0, 6) + }) + + test('a wall item slides along the wall, its wallT following, clamped in span and height', () => { + const { after } = moved(scene(), { id: 'item_shelf', to: [4.3, 0.4], y: 1.2 } as never) + const shelf = after.item_shelf as ItemNode + expect(shelf.position[0]).toBeCloseTo(4.3, 6) + expect(shelf.position[1]).toBe(1.2) + expect(shelf.wallT).toBeCloseTo(4.3 / 6, 6) + expect(shelf.wallId).toBe('wall_a') + expect(shelf.parentId).toBe('wall_a') + }) + + test('a ceiling item moves in plan under its ceiling, keeping its drop', () => { + const { result, after } = moved(scene(), { id: 'item_lamp', to: [3, 3] } as never) + expect(result).toMatchObject({ host: 'ceiling', hostId: 'ceiling_a' }) + expect((after.item_lamp as ItemNode).position).toEqual([3, -0.3, 3]) + }) + + test('a floor item moves in plan and turns by degrees', () => { + const { result, after } = moved(scene(), { + id: 'item_chair', + by: [1, -0.5], + rotation: 90, + } as never) + expect(result.host).toBe('free') + const chair = after.item_chair as ItemNode + expect(chair.position).toEqual([2, 0, 1.5]) + expect(chair.rotation[1]).toBeCloseTo(Math.PI / 2, 9) + }) + + test('a roof piece moves in its segment-local plan, its anchored height kept', () => { + const { result, after } = moved(scene(), { id: 'skylight_a', by: [0.25, -0.25] } as never) + expect(result).toMatchObject({ host: 'roof', hostId: 'rseg_a' }) + expect((after.skylight_a as SkylightNode).position).toEqual([0.75, 0, 0.25]) + }) + + test('a wall translates by a delta, its openings riding in wall-local seats', () => { + const { after } = moved(scene(), { id: 'wall_a', by: [0, 2] } as never) + const wall = after.wall_a as WallNode + expect(wall.start).toEqual([0, 2]) + expect(wall.end).toEqual([6, 2]) + expect((after.door_a as DoorNode).position).toEqual([1, 1.05, 0]) + expect( + refusalCode(() => moveNode(scene(), { id: 'wall_a', to: [1, 1] } as never, context)), + ).toBe('move_to_ambiguous') + }) + + test('refusals name what cannot move and what to use instead', () => { + expect( + refusalCode(() => moveNode(scene(), { id: 'missing', by: [1, 0] } as never, context)), + ).toBe('node_not_found') + expect( + refusalCode(() => moveNode(scene(), { id: 'level_a', by: [1, 0] } as never, context)), + ).toBe('node_not_movable') + expect(refusalCode(() => moveNode(scene(), { id: 'item_chair' } as never, context))).toBe( + 'move_target_required', + ) + expect( + refusalCode(() => + moveNode(scene(), { id: 'item_chair', to: [1, 1], by: [1, 1] } as never, context), + ), + ).toBe('move_target_ambiguous') + expect( + refusalCode(() => + moveNode(scene(), { id: 'door_a', by: [1, 0], rotation: 90 } as never, context), + ), + ).toBe('rotation_not_supported') + expect( + refusalCode(() => + moveNode(scene(), { id: 'item_chair', by: [1, 0], y: 1 } as never, context), + ), + ).toBe('height_not_applicable') + }) + + test('a curved wall refuses its openings, as the editor refuses them there', () => { + const nodes = scene() + const curved = { ...nodes, wall_a: { ...(nodes.wall_a as WallNode), curveOffset: 0.5 } } + expect( + refusalCode(() => moveNode(curved, { id: 'door_a', by: [1, 0] } as never, context)), + ).toBe('curved_wall') + }) +}) + +describe('duplicate_node', () => { + test('is registered once, under the shared contract', () => { + expect(AGENT_OPERATIONS.duplicate_node).toBe(duplicateNode) + expect(duplicateNodeTool.name).toBe('duplicate_node') + expect(z.object(duplicateNodeTool.input).safeParse({ ids: ['door_a'] }).success).toBe(true) + }) + + test('a floor item copy is the node the editor duplicate makes: same fields, fresh id', () => { + const nodes = scene() + const { result, changes } = duplicateNode(nodes, { ids: ['item_chair'] } as never, context) + expect(z.object(duplicateNodeOutput).strict().parse(result)).toEqual(result) + const after = applySceneChanges(nodes as never, changes) as SceneNodes + const copyId = (result.copies as { copyId: string }[])[0]?.copyId ?? '' + // The editor's own duplicate path (duplicateWithoutMove) is collectSubtree + cloneNodesInto. + const subtree = collectSubtree(nodes as Record, 'item_chair' as AnyNodeId) + if (!subtree) throw new Error('chair subtree missing') + const editorClone = cloneNodesInto([subtree.root, ...subtree.descendants], { + rootId: 'item_chair' as AnyNodeId, + parentId: 'level_a' as AnyNodeId, + }).nodes[0] as AnyNode + const { id: _agentId, ...agentRest } = after[copyId] as AnyNode + const { id: _editorId, ...editorRest } = editorClone + expect(agentRest).toEqual(editorRest) + expect(copyId).not.toBe('item_chair') + }) + + test('a wall copy carries its openings and shelf, hosted on the copy, offset as one', () => { + const nodes = scene() + const { result, changes } = duplicateNode( + nodes, + { ids: ['wall_a'], offset: [0, 3] } as never, + context, + ) + const after = applySceneChanges(nodes as never, changes) as SceneNodes + const copyId = (result.copies as { copyId: string }[])[0]?.copyId ?? '' + const wall = after[copyId] as WallNode + expect(wall.start).toEqual([0, 3]) + expect(wall.end).toEqual([6, 3]) + expect(wall.children).toHaveLength(3) + for (const childId of wall.children) { + const child = after[childId] as DoorNode + expect(child.parentId).toBe(copyId) + expect(child.wallId).toBe(copyId) + } + expect(result.totalCreated).toBe(4) + }) + + test('a window copy stays on the same wall, offset along it', () => { + const nodes = scene() + const { result, changes } = duplicateNode( + nodes, + { ids: ['window_a'], offset: [1.4, 0] } as never, + context, + ) + const after = applySceneChanges(nodes as never, changes) as SceneNodes + const copyId = (result.copies as { copyId: string }[])[0]?.copyId ?? '' + const copy = after[copyId] as WindowNode + expect(copy.parentId).toBe('wall_a') + expect(copy.wallId).toBe('wall_a') + expect(copy.position[0]).toBeCloseTo(4.4, 6) + expect((after.wall_a as WallNode).children).toContain(copyId) + }) + + test('a ceiling lamp and a skylight copy onto their same hosts', () => { + const nodes = scene() + const { result, changes } = duplicateNode( + nodes, + { ids: ['item_lamp', 'skylight_a'], offset: [1, 0] } as never, + context, + ) + const after = applySceneChanges(nodes as never, changes) as SceneNodes + const copies = result.copies as { sourceId: string; copyId: string }[] + const lamp = after[copies.find((c) => c.sourceId === 'item_lamp')?.copyId ?? ''] as ItemNode + const sky = after[copies.find((c) => c.sourceId === 'skylight_a')?.copyId ?? ''] as SkylightNode + expect(lamp.parentId).toBe('ceiling_a') + expect(lamp.position).toEqual([3, -0.3, 2]) + expect(sky.parentId).toBe('rseg_a') + expect(sky.roofSegmentId).toBe('rseg_a') + expect(sky.position).toEqual([1.5, 0, 0.5]) + }) + + test('a selection copies across a level; a hosted root refuses the move', () => { + const nodes = scene() + const { result, changes } = duplicateNode( + nodes, + { ids: ['wall_a', 'item_chair'], targetLevelId: 'level_b' } as never, + context, + ) + const after = applySceneChanges(nodes as never, changes) as SceneNodes + for (const copy of result.copies as { copyId: string }[]) { + expect((after[copy.copyId] as AnyNode).parentId).toBe('level_b') + } + expect( + refusalCode(() => + duplicateNode(nodes, { ids: ['door_a'], targetLevelId: 'level_b' } as never, context), + ), + ).toBe('hosted_root_level') + }) + + test('an id inside another copied subtree is skipped, not copied twice', () => { + const { result } = duplicateNode(scene(), { ids: ['wall_a', 'door_a'] } as never, context) + expect(result.skippedIds).toEqual(['door_a']) + expect((result.copies as unknown[]).length).toBe(1) + }) + + test('refusals: unknown id, a level, and a roof each name their own tool', () => { + expect(refusalCode(() => duplicateNode(scene(), { ids: ['missing'] } as never, context))).toBe( + 'node_not_found', + ) + expect(refusalCode(() => duplicateNode(scene(), { ids: ['level_a'] } as never, context))).toBe( + 'duplicate_not_supported', + ) + expect(refusalCode(() => duplicateNode(scene(), { ids: ['roof_a'] } as never, context))).toBe( + 'duplicate_not_supported', + ) + }) +}) diff --git a/packages/core/src/agent-operations/move-node.ts b/packages/core/src/agent-operations/move-node.ts new file mode 100644 index 0000000000..fa613e2766 --- /dev/null +++ b/packages/core/src/agent-operations/move-node.ts @@ -0,0 +1,31 @@ +import { refuse } from '../agent-tools/refusal' +import { achievedChanges } from './achieved' +import { type MoveTarget, planNodeMove } from './move-plan' +import type { AgentOperation } from './types' + +type MoveNodeInput = MoveTarget & { id: string } + +/** + * `move_node`: the editor's move tool for one node — re-seated on its host by `planNodeMove`, + * so the node the agent leaves is the node the editor's drag would leave. + */ +export const moveNode: AgentOperation = (nodes, input) => { + const node = nodes[input.id] + if (!node) refuse('node_not_found', `Node not found: ${input.id}.`, { id: input.id }) + const plan = planNodeMove(nodes, node, input) + const changes = { update: [{ id: node.id, data: plan.data }] } + return { + result: { + ok: true as const, + id: node.id, + type: node.type, + host: plan.host, + hostId: plan.hostId, + position: plan.position, + clamped: plan.clamped, + message: `Moved ${node.type} "${node.name ?? node.id}"${plan.clamped ? ', slid to stay seated' : ''}`, + achieved: achievedChanges(nodes, changes), + }, + changes, + } +} diff --git a/packages/core/src/agent-operations/move-plan.ts b/packages/core/src/agent-operations/move-plan.ts new file mode 100644 index 0000000000..ca83d28ed2 --- /dev/null +++ b/packages/core/src/agent-operations/move-plan.ts @@ -0,0 +1,379 @@ +import { refuse } from '../agent-tools/refusal' +import { clampDoorToWall, clampWindowToWall, findWallChildOverlap } from '../building/wall-openings' +import { + type AnyNode, + type AnyNodeId, + type DoorNode, + getScaledDimensions, + type ItemNode, + type WallNode, + type WindowNode, +} from '../schema' +import { isDerivedNode } from '../store/derived-node-guard' +import { isCurvedWall } from '../systems/wall/wall-curve' +import { getWallLocalFaceZ } from '../systems/wall/wall-frame' +import { projectWorldPointToWallLocalX, wallLength } from './plan-geometry' +import type { SceneNodes } from './types' + +export type MoveTarget = { + to?: number[] + by?: number[] + y?: number + rotation?: number + force?: boolean +} + +export type MoveHostClass = 'wall' | 'ceiling' | 'free' | 'roof' | 'level' + +export type MovePlan = { + host: MoveHostClass + hostId: string | null + /** The node's stored position after the move; for a wall, its start as [x, 0, z]. */ + position: [number, number, number] + clamped: boolean + data: Partial +} + +/** + * Kinds a person can pick up and set down on a level, whose seat is their stored plan position: + * the same kinds the node definitions declare `movable` on x/z (core cannot read those + * definitions, so the seat is decided by kind and parent here, as other operations decide). + */ +const FREE_ON_LEVEL = new Set([ + 'item', + 'column', + 'elevator', + 'shelf', + 'block', + 'cabinet', + 'procedural-item', + 'imported-mesh', + 'scan', + 'spawn', + 'hvac-equipment', + 'duct-terminal', + 'duct-fitting', + 'pipe-fitting', + 'pipe-trap', +]) + +const DEDICATED_TOOL: Record = { + zone: 'move_zone or rotate_zone', + level: 'add_level or duplicate_level', + roof: 'create_roof', + 'roof-segment': 'create_roof', + stair: 'create_stair', + building: 'update_node on the building', +} + +function parentOf(nodes: SceneNodes, node: AnyNode): AnyNode | undefined { + return node.parentId ? nodes[node.parentId] : undefined +} + +function positionOf(node: AnyNode): [number, number, number] | null { + const position = (node as { position?: unknown }).position + return Array.isArray(position) && position.length === 3 + ? (position as [number, number, number]) + : null +} + +/** The host class a node's seat belongs to, or a coded refusal saying why it has no movable seat. */ +export function moveHostClass(nodes: SceneNodes, node: AnyNode): MoveHostClass { + if (isDerivedNode(node)) + refuse( + 'node_not_movable', + `${node.type} ${node.id} is derived from its room; the editor rebuilds it rather than moving it.`, + { id: node.id, type: node.type }, + ) + const parent = parentOf(nodes, node) + if ( + parent?.type === 'wall' && + (node.type === 'door' || node.type === 'window' || node.type === 'item') + ) + return 'wall' + if (parent?.type === 'ceiling' && node.type === 'item') return 'ceiling' + if ( + (node.type === 'door' || node.type === 'window') && + ((node as DoorNode).roofSegmentId || parent?.type === 'roof-segment') + ) + refuse( + 'move_not_supported', + `${node.type} ${node.id} sits on a roof-segment wall face, whose seat the editor keeps in face-local coordinates this tool does not move.`, + { id: node.id, type: node.type }, + ) + if (parent?.type === 'roof-segment') return 'roof' + if (node.type === 'wall' && parent?.type === 'level') return 'level' + if (parent?.type === 'level' && FREE_ON_LEVEL.has(node.type) && positionOf(node)) return 'free' + if (parent?.type === 'item') + refuse( + 'move_not_supported', + `${node.type} ${node.id} rests on item ${parent.id}; moving a node on another item's surface is not supported here. Move its host, or delete and place it again.`, + { id: node.id, hostId: parent.id }, + ) + const dedicated = DEDICATED_TOOL[node.type] + refuse( + 'node_not_movable', + `A ${node.type} has no seat the editor's move tool drags${dedicated ? `; use ${dedicated}` : ''}.`, + { id: node.id, type: node.type }, + ) +} + +function requireTarget(target: MoveTarget) { + if (target.to && target.by) + refuse('move_target_ambiguous', 'Pass one of to (absolute) or by (delta), not both.') + if (!target.to && !target.by && target.rotation === undefined) + refuse( + 'move_target_required', + 'Say where the node goes: to [x, z], by [dx, dz], or a rotation alone.', + ) +} + +function planTargetXZ(current: [number, number, number], target: MoveTarget): [number, number] { + if (target.to) return [target.to[0] ?? current[0], target.to[1] ?? current[2]] + return [current[0] + (target.by?.[0] ?? 0), current[2] + (target.by?.[1] ?? 0)] +} + +function yawData(node: AnyNode, target: MoveTarget, scalar: boolean): Partial { + if (target.rotation === undefined) return {} + const radians = (target.rotation * Math.PI) / 180 + if (scalar) return { rotation: radians } as Partial + const rotation = (node as { rotation?: number[] }).rotation + const tuple: [number, number, number] = [rotation?.[0] ?? 0, radians, rotation?.[2] ?? 0] + return { rotation: tuple } as Partial +} + +function refuseStrayY(target: MoveTarget, node: AnyNode) { + if (target.y !== undefined) + refuse( + 'height_not_applicable', + `y sets a window's sill or a wall item's bottom height; ${node.type} ${node.id} takes neither.`, + { id: node.id, type: node.type }, + ) +} + +function planFreeMove(node: AnyNode, target: MoveTarget, host: MoveHostClass): MovePlan { + refuseStrayY(target, node) + const current = positionOf(node) + if (!current) + refuse('node_not_movable', `${node.type} ${node.id} has no stored position to move.`, { + id: node.id, + }) + const [x, z] = planTargetXZ(current, target) + const position: [number, number, number] = [x, current[1], z] + return { + host, + hostId: node.parentId ?? null, + position, + clamped: false, + data: { position, ...yawData(node, target, host === 'roof') } as Partial, + } +} + +function desiredLocalX(wall: WallNode, node: AnyNode, target: MoveTarget): number { + const current = positionOf(node) + if (target.to) + return projectWorldPointToWallLocalX(wall, [target.to[0] ?? 0, 0, target.to[1] ?? 0]) + if (!current) return 0 + const length = wallLength(wall) + if (!length) return current[0] + const ux = (wall.end[0] - wall.start[0]) / length + const uz = (wall.end[1] - wall.start[1]) / length + return current[0] + (target.by?.[0] ?? 0) * ux + (target.by?.[1] ?? 0) * uz +} + +function overlapRefusal( + nodes: SceneNodes, + wall: WallNode, + node: AnyNode, + centreX: number, + centreY: number, + width: number, + height: number, + target: MoveTarget, + checkOverlap: boolean, +) { + if (!checkOverlap || target.force) return + const blocking = findWallChildOverlap(wall.id, nodes, centreX, centreY, width, height, node.id) + if (blocking) + refuse( + 'opening_overlap', + `Moving ${node.type} ${node.id} there on wall ${wall.id} would overlap ${blocking.type} ${blocking.id}. Move it along the wall, or, if the person asked for the overlap, pass force, like holding Alt in the editor.`, + { id: node.id, wallId: wall.id, blockingId: blocking.id }, + ) +} + +function planOpeningMove( + nodes: SceneNodes, + wall: WallNode, + node: DoorNode | WindowNode, + target: MoveTarget, + checkOverlap: boolean, +): MovePlan { + if (node.type === 'door' && target.y !== undefined) refuseStrayY(target, node) + const length = wallLength(wall) + if (length < node.width) + refuse( + 'wall_too_short', + `Wall ${wall.id} is ${length.toFixed(2)} m long, too short for this ${node.width.toFixed(2)} m ${node.type}.`, + { id: node.id, wallId: wall.id, wallLength: length, width: node.width }, + ) + const rawX = desiredLocalX(wall, node, target) + const rawY = + node.type === 'door' + ? node.height / 2 + : target.y === undefined + ? node.position[1] + : target.y + node.height / 2 + const { clampedX, clampedY } = + node.type === 'door' + ? clampDoorToWall(wall, rawX, node.width, node.height) + : clampWindowToWall( + wall, + rawX, + rawY, + node.width, + node.height, + nodes as Record, + ) + overlapRefusal( + nodes, + wall, + node, + clampedX, + clampedY, + node.width, + node.height, + target, + checkOverlap, + ) + const position: [number, number, number] = [clampedX, clampedY, node.position[2]] + return { + host: 'wall', + hostId: wall.id, + position, + clamped: Math.abs(clampedX - rawX) > 1e-9 || Math.abs(clampedY - rawY) > 1e-9, + data: { position } as Partial, + } +} + +/** A wall item's seat, as place_items seats one: along the wall, bottom at y, on the point's side. */ +function planWallItemMove( + nodes: SceneNodes, + wall: WallNode, + item: ItemNode, + target: MoveTarget, + checkOverlap: boolean, +): MovePlan { + const [width, height] = getScaledDimensions(item) + const wallHeight = wall.height ?? 2.5 + const length = wallLength(wall) + const rawX = desiredLocalX(wall, item, target) + const x = Math.max(width / 2, Math.min(length - width / 2, rawX)) + const rawY = target.y ?? item.position[1] + const y = Math.max(0, Math.min(wallHeight - height, rawY)) + // The side follows the target point when one is named, as the editor's drag crosses the wall. + let side = item.side + let faceZ = item.position[2] + let turn = item.rotation[1] ?? 0 + if (target.to) { + const [dx, dz] = [wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]] + const left = + -dz * ((target.to[0] ?? 0) - wall.start[0]) + dx * ((target.to[1] ?? 0) - wall.start[1]) >= 0 + side = left ? 'front' : 'back' + faceZ = item.asset.attachTo === 'wall-side' ? getWallLocalFaceZ(wall, left ? 'a' : 'b') : 0 + turn = left ? 0 : Math.PI + } + overlapRefusal(nodes, wall, item, x, y + height / 2, width, height, target, checkOverlap) + const position: [number, number, number] = [x, y, faceZ] + return { + host: 'wall', + hostId: wall.id, + position, + clamped: Math.abs(x - rawX) > 1e-9 || Math.abs(y - rawY) > 1e-9, + data: { + position, + rotation: [item.rotation[0] ?? 0, turn, item.rotation[2] ?? 0], + wallId: wall.id, + wallT: length ? x / length : 0, + side, + } as Partial, + } +} + +function planWallHostedMove( + nodes: SceneNodes, + node: AnyNode, + target: MoveTarget, + checkOverlap: boolean, +): MovePlan { + if (target.rotation !== undefined) + refuse( + 'rotation_not_supported', + `${node.type} ${node.id} faces its wall side; rotation does not apply on a wall host.`, + { id: node.id }, + ) + const wall = parentOf(nodes, node) + if (wall?.type !== 'wall') + refuse('move_host_missing', `${node.type} ${node.id} has no host wall.`, { id: node.id }) + if (isCurvedWall(wall)) + refuse( + 'curved_wall', + `Wall ${wall.id} is curved; its hosted nodes do not slide along it, as in the editor.`, + { id: node.id, wallId: wall.id }, + ) + return node.type === 'item' + ? planWallItemMove(nodes, wall, node as ItemNode, target, checkOverlap) + : planOpeningMove(nodes, wall, node as DoorNode | WindowNode, target, checkOverlap) +} + +function planWallMove(node: WallNode, target: MoveTarget): MovePlan { + refuseStrayY(target, node) + if (target.rotation !== undefined) + refuse( + 'rotation_not_supported', + `Wall ${node.id} turns by redrawing its ends; move_node only translates it.`, + { id: node.id }, + ) + if (target.to) + refuse( + 'move_to_ambiguous', + `A wall has two ends; say by how much wall ${node.id} translates, with by [dx, dz].`, + { id: node.id }, + ) + const dx = target.by?.[0] ?? 0 + const dz = target.by?.[1] ?? 0 + const start: [number, number] = [node.start[0] + dx, node.start[1] + dz] + const end: [number, number] = [node.end[0] + dx, node.end[1] + dz] + return { + host: 'level', + hostId: node.parentId ?? null, + position: [start[0], 0, start[1]], + clamped: false, + data: { start, end } as Partial, + } +} + +/** + * Where a node lands when moved, seated the way the editor's move tools seat it — the same plan + * move_node applies to a live node and duplicate_node applies to a copy's offset. + */ +export function planNodeMove( + nodes: SceneNodes, + node: AnyNode, + target: MoveTarget, + options: { checkOverlap?: boolean } = {}, +): MovePlan { + requireTarget(target) + const host = moveHostClass(nodes, node) + const checkOverlap = options.checkOverlap ?? true + if (host === 'wall') return planWallHostedMove(nodes, node, target, checkOverlap) + if (host === 'level') return planWallMove(node as WallNode, target) + if (host === 'roof') { + const parent = parentOf(nodes, node) + if (parent?.type !== 'roof-segment') + refuse('move_host_missing', `${node.type} ${node.id} has no host roof segment.`, { + id: node.id, + }) + } + return planFreeMove(node, target, host) +} diff --git a/packages/core/src/agent-tools/batch.ts b/packages/core/src/agent-tools/batch.ts index 8140472cb3..c5623398d9 100644 --- a/packages/core/src/agent-tools/batch.ts +++ b/packages/core/src/agent-tools/batch.ts @@ -12,6 +12,8 @@ export const BATCHABLE_TOOLS = [ 'duplicate_level', 'verify_scene', 'delete_node', + 'move_node', + 'duplicate_node', 'measure_stair', 'fit_stair', 'find_by_type', diff --git a/packages/core/src/agent-tools/index.ts b/packages/core/src/agent-tools/index.ts index 8c426da779..7bb8773186 100644 --- a/packages/core/src/agent-tools/index.ts +++ b/packages/core/src/agent-tools/index.ts @@ -24,6 +24,7 @@ import { setGroundLevelTool, } from './levels' import { mergeWindowsTool } from './merge-windows' +import { duplicateNodeTool, moveNodeTool } from './move-duplicate' import { deleteNodeTool, getNodeTool } from './nodes' import { paintTool } from './paint' import { placeInRoomTool } from './place-in-room' @@ -57,6 +58,7 @@ export * from './hosted-services' export * from './levels' export * from './measurement' export * from './merge-windows' +export * from './move-duplicate' export { NodeId } from './node-id' export * from './nodes' export * from './notation-inventory' @@ -115,6 +117,8 @@ export const AGENT_TOOL_CONTRACTS = [ createRoofTool, moveRoofsToRoofLevelTool, deleteNodeTool, + moveNodeTool, + duplicateNodeTool, addObjectTool, authorSceneTool, getSourceTool, diff --git a/packages/core/src/agent-tools/move-duplicate.ts b/packages/core/src/agent-tools/move-duplicate.ts new file mode 100644 index 0000000000..cee35064b2 --- /dev/null +++ b/packages/core/src/agent-tools/move-duplicate.ts @@ -0,0 +1,83 @@ +import { z } from 'zod' +import { achievedOutput } from './achieved' +import { NodeId } from './node-id' + +// Arrays avoid tuple-form JSON schemas that some MCP clients cannot call. +const planPoint = z.array(z.number()).length(2) + +export const moveNodeTool = { + name: 'move_node', + title: 'Move node', + description: + "Move one node the way the editor's move tool does, re-seated on its host: a door, window or wall item slides along its wall (the plan point is projected onto the wall, clamped to stay on it, and refused with opening_overlap where it would hit a sibling, unless force, like holding Alt); a ceiling item moves in plan under its ceiling, keeping its drop; a floor or free node moves in plan on its level, keeping its height; a roof piece (skylight, chimney, vents, solar, dormer) moves in its segment-local plan, the frame its stored position uses, its height staying anchored to the segment surface; a wall takes by only (its ends translate, its openings ride in their wall-local seats). to and by are plan metres [x, z]: level plan for level, wall and ceiling hosts, segment-local for a roof host. Exactly one of to (absolute) or by (delta), or rotation alone. y is a window's sill height or a wall item's bottom height in metres, and nothing else takes it. rotation is yaw in degrees for free, ceiling and roof nodes. Returns the host class and id, the node's stored position after the move (a wall: its start point as [x, 0, z]), and whether the seat clamped. Refusals: node_not_found, node_not_movable (site, building, level, zone — use move_zone — roof, roof segment, stair, derived plates and other geometry-defined kinds), move_target_required, move_target_ambiguous (both to and by, or to on a wall), move_host_missing (its wall, ceiling or segment is gone), curved_wall, wall_too_short, opening_overlap, rotation_not_supported (wall-hosted nodes face their wall side), height_not_applicable, move_not_supported (an item resting on another item).", + input: { + id: NodeId.describe('The node id.'), + to: planPoint + .optional() + .describe( + 'Absolute plan target [x, z] in metres, in the frame the description names for its host.', + ), + by: planPoint + .optional() + .describe('Plan delta [dx, dz] in metres from where the node sits, same frame as to.'), + y: z + .number() + .optional() + .describe( + "A window's sill height or a wall item's bottom height above the floor, in metres.", + ), + rotation: z.number().optional().describe('Yaw in degrees (free, ceiling and roof nodes).'), + force: z + .boolean() + .optional() + .describe('Allow a wall seat that overlaps a sibling, like holding Alt in the editor.'), + }, +} + +export const moveNodeOutput = { + ok: z.literal(true), + id: z.string(), + type: z.string(), + host: z.enum(['wall', 'ceiling', 'free', 'roof', 'level']), + hostId: z.string().nullable(), + position: z.array(z.number()).length(3), + clamped: z.boolean(), + message: z.string(), + achieved: achievedOutput, +} + +export const duplicateNodeTool = { + name: 'duplicate_node', + title: 'Duplicate node', + description: + "Duplicate nodes with everything under them, as the editor's Duplicate does: fresh ids, hosted children re-hosted on the copies (a wall brings its doors, windows and wall items, their wallId pointing at the copy), an id inside another listed subtree skipped rather than copied twice. A door, window, wall item, ceiling item or roof piece copied on its own stays on its same host. offset [dx, dz] in plan metres moves every copy from its source's seat (default [0, 0], an exact copy in place, as the editor's duplicate starts); a wall offset translates its ends, a hosted copy's offset slides it on its host, clamped to stay seated. targetLevelId puts level-parented copies on that level instead; a hosted copy refuses it (hosted_root_level) because its host stays behind. Returns copies (sourceId, copyId, type, descendantCount), totalCreated and skippedIds. Refusals: node_not_found, duplicate_not_supported (a site, building, level — use duplicate_level — zone — use duplicate_zone — roof or roof segment, or a derived plate), duplicate_root_invalid (a node the editor only copies as part of its parent), hosted_root_level, level_not_found.", + input: { + ids: z + .array(NodeId) + .min(1) + .max(64) + .describe('The node ids to copy, each with everything under it.'), + offset: planPoint + .optional() + .describe('Plan delta [dx, dz] in metres applied to every copy. Default [0, 0].'), + targetLevelId: NodeId.optional().describe( + 'Copy level-parented roots onto this level instead of their own.', + ), + }, +} + +export const duplicateNodeOutput = { + ok: z.literal(true), + copies: z.array( + z.object({ + sourceId: z.string(), + copyId: z.string(), + type: z.string(), + descendantCount: z.number().int(), + }), + ), + totalCreated: z.number().int(), + skippedIds: z.array(z.string()), + message: z.string(), + achieved: achievedOutput, +} diff --git a/packages/mcp/src/resources/agent-guide.ts b/packages/mcp/src/resources/agent-guide.ts index f94df2b81b..6005aca4f5 100644 --- a/packages/mcp/src/resources/agent-guide.ts +++ b/packages/mcp/src/resources/agent-guide.ts @@ -58,6 +58,7 @@ export const AGENT_GUIDE = [ '- Adjacent rooms can share one wall (or have openings that line up). A door keeps about 0.65 m clear on both sides; furniture footprints do not overlap.', '- A complete home is an exterior shell, interior rooms, openings, a roof, furniture and landscaping.', '- On doors and windows, `t` or `position` runs from 0 to 1 along the wall unless a tool explicitly says otherwise.', + '- `move_node` moves one node re-seated on its host, as the editor’s move tool does: a door, window or wall item slides along its wall (plan target projected onto the wall, clamped, overlap refused unless force), a ceiling item in plan under its ceiling, a floor node in level plan, a roof piece in its segment-local plan, a wall by translation only. `duplicate_node` copies nodes with their hosted children onto fresh ids, on the same hosts or another level for level-parented roots.', '- X/Z are floor-plan axes and Y is vertical; dimensions are meters.', "- `create_roof` roofs the storeys and exterior walls standing when it runs. A building's roof goes on its roof level, the level directly above the top storey (named Roof, made when there is none), so exploded and solo level views lift it off the plan; a roof level is not an occupied story. `add_level` puts a new storey under it. A storey takes one roof: `roof_exists` names the one there. A project built before the roof level holds its roof on the storey (`verify_scene`'s `roof_mixed_in_storey`): `move_roofs_to_roof_level` moves it there as it stands, without a delete and rebuild.", '- Glazed roof construction supports gable, straight shed and barrel roofs. For barrel, depth is the span and barrelRise is the arch rise, at most half the span. glazing configures frame, glass, grids and panels. Paint glazing-frame, glazing-glass or glazing-solid; without a role, frame and solid panels are painted while glass keeps its finish.', diff --git a/packages/mcp/src/tools/move-duplicate.test.ts b/packages/mcp/src/tools/move-duplicate.test.ts new file mode 100644 index 0000000000..d87e261ddb --- /dev/null +++ b/packages/mcp/src/tools/move-duplicate.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, test } from 'bun:test' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { duplicateNodeTool, moveNodeTool } from '@pascal-app/core/agent-tools' +import { DoorNode, LevelNode, WallNode, WindowNode } from '@pascal-app/core/schema' +import { SceneBridge } from '../bridge/scene-bridge' +import { registerSharedTools } from './shared-tools' + +/** One level, one 6 m wall carrying a door at 1 m and a window at 3 m. */ +function wallScene() { + const level = LevelNode.parse({ id: 'level_move' }) + const wall = WallNode.parse({ + id: 'wall_move', + parentId: level.id, + start: [0, 0], + end: [6, 0], + thickness: 0.2, + height: 2.5, + children: ['door_move', 'window_move'], + }) + const door = DoorNode.parse({ + id: 'door_move', + parentId: wall.id, + wallId: wall.id, + position: [1, 1.05, 0], + width: 0.9, + height: 2.1, + }) + const win = WindowNode.parse({ + id: 'window_move', + parentId: wall.id, + wallId: wall.id, + position: [3, 1.25, 0], + width: 1.2, + height: 1.0, + }) + return [level, wall, door, win] +} + +async function withWall(run: (client: Client, bridge: SceneBridge) => Promise) { + const nodes = wallScene() + const bridge = new SceneBridge() + bridge.setScene(Object.fromEntries(nodes.map((node) => [node.id, node])), ['level_move']) + bridge.clearHistory() + const server = new McpServer({ name: 'move-duplicate-test', version: '0.0.0' }) + registerSharedTools(server, bridge) + const client = new Client({ name: 'move-duplicate-client', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + await run(client, bridge) + } finally { + await client.close() + await server.close() + } +} + +describe('move_node and duplicate_node over MCP', () => { + test('both register under the shared contracts, as scene writes', async () => { + await withWall(async (client) => { + const tools = (await client.listTools()).tools + const move = tools.find((tool) => tool.name === 'move_node') + const duplicate = tools.find((tool) => tool.name === 'duplicate_node') + expect(move?.description).toBe(moveNodeTool.description) + expect(duplicate?.description).toBe(duplicateNodeTool.description) + // A move overwrites an existing seat (destructive, like move_zone); a copy only adds. + expect(move?.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true }) + expect(duplicate?.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: false }) + }) + }) + + test('move_node slides the door along its wall and the scene holds the seat', async () => { + await withWall(async (client, bridge) => { + const result = await client.callTool({ + name: 'move_node', + arguments: { id: 'door_move', by: [0.5, 0] }, + }) + expect(result.isError).toBeFalsy() + expect(result.structuredContent).toMatchObject({ + id: 'door_move', + host: 'wall', + hostId: 'wall_move', + position: [1.5, 1.05, 0], + clamped: false, + }) + const door = bridge.getNodes().door_move as DoorNode + expect(door.position).toEqual([1.5, 1.05, 0]) + expect(bridge.getHistory().pastCount).toBe(1) + }) + }) + + test('move_node onto the window answers the core refusal, coded', async () => { + await withWall(async (client, bridge) => { + const before = structuredClone(bridge.getNodes()) + const result = await client.callTool({ + name: 'move_node', + arguments: { id: 'door_move', to: [3, 0] }, + }) + expect(result.isError).toBeTruthy() + const text = result.content.find((part) => part.type === 'text') + if (text?.type !== 'text') throw new Error('Expected the refusal as text') + expect(JSON.parse(text.text)).toMatchObject({ code: 'opening_overlap' }) + expect(bridge.getNodes()).toEqual(before) + }) + }) + + test('duplicate_node copies the wall with its openings onto fresh ids', async () => { + await withWall(async (client, bridge) => { + const result = await client.callTool({ + name: 'duplicate_node', + arguments: { ids: ['wall_move'], offset: [0, 3] }, + }) + expect(result.isError).toBeFalsy() + expect(result.structuredContent).toMatchObject({ totalCreated: 3, skippedIds: [] }) + const copies = result.structuredContent?.copies as { copyId: string }[] + const wallCopy = bridge.getNodes()[copies[0]?.copyId ?? ''] as WallNode + expect(wallCopy.start).toEqual([0, 3]) + expect(wallCopy.children).toHaveLength(2) + for (const childId of wallCopy.children) { + const child = bridge.getNodes()[childId] as DoorNode + expect(child.parentId).toBe(wallCopy.id) + expect(child.wallId).toBe(wallCopy.id) + } + }) + }) +}) diff --git a/packages/mcp/src/tools/read-tool-annotations.test.ts b/packages/mcp/src/tools/read-tool-annotations.test.ts index 5869740d43..1cf16c78b9 100644 --- a/packages/mcp/src/tools/read-tool-annotations.test.ts +++ b/packages/mcp/src/tools/read-tool-annotations.test.ts @@ -75,6 +75,7 @@ const TOOL_POLICIES = [ 'create_unit', 'cut_floor_opening', 'duplicate_level', + 'duplicate_node', 'furnish_room', 'place_in_room', 'generate_variants', @@ -109,6 +110,7 @@ const TOOL_POLICIES = [ 'delete_zone', 'divide_zone', 'duplicate_zone', + 'move_node', 'move_zone', 'place_building', 'rotate_zone', diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index 088fe273a7..07e890cfc7 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -36,6 +36,8 @@ import { deleteNodeTool, designBriefTool, duplicateLevelTool, + duplicateNodeOutput, + duplicateNodeTool, findByTypeTool, fitStairTool, furnishRoomTool, @@ -49,6 +51,8 @@ import { listUnitsTool, measureStairTool, mergeWindowsTool, + moveNodeOutput, + moveNodeTool, moveRoofsToRoofLevelTool, paintTool, placeBuildingTool, @@ -420,6 +424,18 @@ const SHARED_TOOLS: SharedTool[] = [ annotations: DESTRUCTIVE_TOOL_ANNOTATIONS, outputSchema: { deletedIds: z.array(z.string()), ...achievedOutput, ...liveSyncOutput }, }, + { + contract: moveNodeTool, + operation: AGENT_OPERATIONS.move_node, + annotations: DESTRUCTIVE_TOOL_ANNOTATIONS, + outputSchema: { ...moveNodeOutput, ...liveSyncOutput }, + }, + { + contract: duplicateNodeTool, + operation: AGENT_OPERATIONS.duplicate_node, + annotations: ADDITIVE_TOOL_ANNOTATIONS, + outputSchema: { ...duplicateNodeOutput, ...liveSyncOutput }, + }, { contract: createRoomTool, operation: AGENT_OPERATIONS.create_room, diff --git a/plugin-evals/tool-annotation-justifications.json b/plugin-evals/tool-annotation-justifications.json index 185c1209c9..738144238c 100644 --- a/plugin-evals/tool-annotation-justifications.json +++ b/plugin-evals/tool-annotation-justifications.json @@ -396,6 +396,19 @@ "openWorldHint": "It operates on the connected Pascal scene, project, and configured catalog data without accessing the public internet." } }, + { + "name": "duplicate_node", + "annotations": { + "readOnlyHint": false, + "destructiveHint": false, + "openWorldHint": false + }, + "justifications": { + "readOnlyHint": "It is not read-only because it creates copies of existing nodes and everything under them.", + "destructiveHint": "Its intended operation adds new modeled state without deleting or replacing existing Pascal scene or project state.", + "openWorldHint": "It operates on the connected Pascal scene or project service without accessing the public internet." + } + }, { "name": "duplicate_zone", "annotations": { @@ -747,6 +760,19 @@ "openWorldHint": "Uses only the connected scene; no public internet access." } }, + { + "name": "move_node", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, + "justifications": { + "readOnlyHint": "It is not read-only because it moves an existing node to a new seat on its host.", + "destructiveHint": "The operation overwrites the existing node's position and can displace hosted construction that rides with it.", + "openWorldHint": "It operates on the connected Pascal scene or project service without accessing the public internet." + } + }, { "name": "move_roofs_to_roof_level", "annotations": { From 6c8772ce14c6d30e99ec1ab1c444c0a10f65f9a1 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 22:58:32 +0100 Subject: [PATCH 24/40] The OpenAI tool annotation policy lists set_code_profile, move_node and duplicate_node The justification packet already held the three tools (90 in all) but the policy table the validation compares it with held 87, so skills:validate failed with "unexpected tool" for each and "must contain the exact 87-tool inventory". The table gets the three tools with the hints the packet states: set_code_profile and move_node change the scene (destructive), duplicate_node adds to it. Co-Authored-By: Claude Sonnet 5.5 --- scripts/openai-tool-annotation-policy.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/openai-tool-annotation-policy.ts b/scripts/openai-tool-annotation-policy.ts index 6ab045341d..a51e85830e 100644 --- a/scripts/openai-tool-annotation-policy.ts +++ b/scripts/openai-tool-annotation-policy.ts @@ -52,6 +52,7 @@ export const EXPECTED_OPENAI_TOOL_ANNOTATIONS = { divide_zone: policy(false, true, false), set_ground_level: policy(false, true, false), duplicate_level: policy(false, false, false), + duplicate_node: policy(false, false, false), duplicate_zone: policy(false, true, false), export_glb: policy(true, false, false), export_json: policy(true, false, false), @@ -73,7 +74,9 @@ export const EXPECTED_OPENAI_TOOL_ANNOTATIONS = { measure: policy(true, false, false), merge_windows: policy(false, true, false), merge_zones: policy(false, true, false), + move_node: policy(false, true, false), move_zone: policy(false, true, false), + set_code_profile: policy(false, true, false), move_roofs_to_roof_level: policy(false, true, false), paint: policy(false, true, false), photo_to_scene: policy(false, true, true), From 798c6bf047d0e42e7ae565151e030d04a24021c1 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 22:52:22 +0100 Subject: [PATCH 25/40] author_scene's description states the output limit and that a payload is the whole design Answers that planned and wrote a whole house as one payload have stopped at the output limit before the payload was complete; the limit counts thinking and the call's arguments together. A later payload with replace: true removes what it leaves out, and one without replace on a converted scene is refused, so the description says the payload is the whole design and names the native tools that add to the scene a call at a time. The sentence that advertised "in one call" is gone. A pin test shows the behaviour the text states: a revision naming only the ground floor removes the upper floor's walls, and a second payload without replace is refused. Co-Authored-By: Claude Sonnet 5.5 --- .../src/agent-operations/author-scene.test.ts | 42 +++++++++++++++++++ .../author-scene-description.test.ts | 22 ++++++++++ packages/core/src/agent-tools/author-scene.ts | 4 +- 3 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/agent-tools/author-scene-description.test.ts diff --git a/packages/core/src/agent-operations/author-scene.test.ts b/packages/core/src/agent-operations/author-scene.test.ts index a2d411a090..8b99c3ba49 100644 --- a/packages/core/src/agent-operations/author-scene.test.ts +++ b/packages/core/src/agent-operations/author-scene.test.ts @@ -222,6 +222,48 @@ describe('author_scene', () => { expect(scene).toEqual(before) }) + test('a payload is the whole design: a revision removes the level it no longer names, and a second payload without replace is refused', () => { + const ground = bedroom.levels[0]! + const upper = { + ...ground, + name: 'Upper floor', + elevation: 2.8, + walls: ground.walls!.map((wall) => ({ ...wall, id: `up_${wall.id}` })), + items: [], + lights: [], + } + const whole = authorScenePayload.parse({ levels: [ground, upper] }) + const first = authorScene( + scaffold(), + { payload: whole, compiled: { bed, lamp: bed } }, + { activeLevelId: null }, + ) + const saved = applySceneChanges(scaffold(), first.changes) + const upperWalls = ['north', 'east', 'south', 'west'].map((id) => first.result.ids[`up_${id}`]!) + for (const id of upperWalls) expect(saved[id]).toBeDefined() + + expect(() => + authorScene( + saved, + { payload: authorScenePayload.parse({ levels: [upper] }), compiled: {} }, + { activeLevelId: null }, + ), + ).toThrow('already holds a conversion') + + const revised = authorScene( + saved, + { + payload: authorScenePayload.parse({ levels: [ground] }), + compiled: { bed, lamp: bed }, + replace: true, + }, + { activeLevelId: null }, + ) + for (const id of upperWalls) expect(revised.changes!.delete).toContain(id) + const after = applySceneChanges(saved, revised.changes) + for (const id of upperWalls) expect(after[id]).toBeUndefined() + }) + test('item ids cannot overwrite another item or a generated source mapping', () => { for (const id of ['bed', 'room/0/0']) { const scene = scaffold() diff --git a/packages/core/src/agent-tools/author-scene-description.test.ts b/packages/core/src/agent-tools/author-scene-description.test.ts new file mode 100644 index 0000000000..6c8561facf --- /dev/null +++ b/packages/core/src/agent-tools/author-scene-description.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from 'bun:test' +import { authorSceneTool } from './author-scene' + +// An answer stops at its output limit, and the limit counts the thinking and the call's arguments +// together. Answers that planned and wrote a whole house as one payload have stopped there before +// the payload was complete, and a payload that names only part of the house does not add to the +// scene: a revision removes what its payload leaves out. The description says both, as facts. +test("author_scene's description states what one answer holds and that a payload is the whole design", () => { + const { description } = authorSceneTool + expect(description).toContain('output limit') + expect(description).toContain("thinking and the call's arguments together") + expect(description).toContain('stopped there before the payload was complete') + expect(description).toContain('the payload holds the whole design') + expect(description).toContain('removes what its payload leaves out') + expect(description).toContain('conversion_exists') + expect(description).not.toContain('in one call') +}) + +test("author_scene's description names the native tools that add to the scene a call at a time", () => { + for (const tool of ['create_room', 'add_wall', 'add_door', 'add_window', 'create_stair']) + expect(authorSceneTool.description).toContain(tool) +}) diff --git a/packages/core/src/agent-tools/author-scene.ts b/packages/core/src/agent-tools/author-scene.ts index 750bd2b7c5..ce43fb16d8 100644 --- a/packages/core/src/agent-tools/author-scene.ts +++ b/packages/core/src/agent-tools/author-scene.ts @@ -7,12 +7,14 @@ import { measurement, roofPitch } from './measurement' import { NodeId } from './node-id' import { unitKind } from './units' -const DESCRIPTION = `Turn a whole design you wrote as free three.js into an editable Pascal scene, in one call. You read your own module however you like (its source, running it and reading the objects, both) and hand over a conversion payload: levels, walls (straight, curved or glass) with their openings, rooms (each naming its unit in a building of several dwellings or tenancies: a condo, an apartment building, a hotel; a room naming none is common area), slabs, voids, columns, railings, stairs, every piece of furniture as an authored object with its own module, and lights. Pascal does the rest server-side: compiles and stores each item, places it, derives the rooms and their floors, paints, runs its checks, saves, and answers with a gate report you iterate against. Nothing you hand over is silently dropped: what cannot be placed comes back by name with a reason, and what Pascal corrected (a wall end snapped onto the centerline it meets) is listed. +const DESCRIPTION = `Turn a whole design you wrote as free three.js into an editable Pascal scene: the payload holds the whole design. You read your own module however you like (its source, running it and reading the objects, both) and hand over a conversion payload: levels, walls (straight, curved or glass) with their openings, rooms (each naming its unit in a building of several dwellings or tenancies: a condo, an apartment building, a hotel; a room naming none is common area), slabs, voids, columns, railings, stairs, every piece of furniture as an authored object with its own module, and lights. Pascal does the rest server-side: compiles and stores each item, places it, derives the rooms and their floors, paints, runs its checks, saves, and answers with a gate report you iterate against. Nothing you hand over is silently dropped: what cannot be placed comes back by name with a reason, and what Pascal corrected (a wall end snapped onto the centerline it meets) is listed. Coordinates: metres, plan x/z, Y up, each level's floor at y = 0 in its own frame. A wall is its centerline; walls meet where centerlines meet, so end a partition on the centerline of the wall it runs into. An opening's 'along' is measured from the wall's start to the opening's centre; give each opening its type (how it opens) and style (its look), or its own module for a shape they cannot express. An item's position is where its bottom centre stands, except a ceiling item's (mount 'ceiling': a pendant, a ceiling light): it hangs from the ceiling of the room containing its plan position, its top on that ceiling, and its y is not read. A rug, a mat or a runner is an item lying on the room's floor. What stands on a floor stands on its finish: on a room with a floorCode, on the top of its planks or tiles, so its y stays 0. Its module follows the add_object contract (metres, Y up, built in its installed orientation; at most 300k triangles and 32 materials per item; name materials slot_; drawers, doors and lids as animation clips; a THREE light named light: where a bulb is: a SpotLight for a cone, castShadow for shadows, userData.glow for a halo). A hex colour is written as an exact material, one per distinct colour. Pascal builds a wall's cap, the floor plate and the ceiling itself: fold a module's caps, underlays and floor planks into the wall, the room's floor finish and the room (say so in notes), never into slabs or regions: baseboards are the wall's skirting, a plank or tile floor is the room's floorCode (a terrace's decking or paving its slab's surfaceCode), tiles, panelling or boards on a wall are its faceLeft / faceRight (or the room's wallCode), cladding, brick or battens outside its faceOutside; a slab is a terrace, a platform, a balcony; a stair is its level's stairs, which open the floor above; the roof over the top level is roof, Pascal's own segments when its shape is one of theirs, else your geometry as roof items, both on the building's roof level above the top storey. Pascal draws what bold architecture needs natively: a curved wall is one wall with the point its arc passes through, through (never a run of short straight ones), a glass front a curtain wall, a double-height room a void in the floor of the level above it (its ceiling opens with it, a railing along its edges), an archway a passage with an arch shape. Paint a wall by what its faces look onto, colorInside and colorOutside: which face is inside is Pascal's to find. Build the building as it is built: a wall at its real height, nothing lowered or removed for viewing. Hand over the payload, or your module and its adapter, the program that reads the module and returns the payload: Pascal runs the adapter (one that throws comes back with its error, and nothing is written). A payload too large for one call goes by reference: upload it as a JSON project file (upload_project_file, phase prepare, PUT, complete) and pass its fileId as payloadFile. An item names its piece instead of code when add_object makes it from words; one still being made is written when it lands, with no call from you. Pieces made from words are written many at a time while you go on, so furniture made that way does not lengthen your turn the way pieces you write yourself do. +One answer has an output limit, and the limit counts thinking and the call's arguments together; answers that planned and wrote a whole house as one payload have stopped there before the payload was complete. The payload is the whole design: a later call with replace: true removes what its payload leaves out, and a call without replace on a scene that holds a conversion is refused (conversion_exists). create_room, add_wall, add_door, add_window and create_stair add to the scene a call at a time. + The report says what was written, what Pascal defaulted (defaults: a window with no type is fixed and cannot open), what it warns about but wrote (warnings: thin slabs, too many slabs or regions), what it refused (defects, by your ids), the items waiting for their pieces (pending), and Pascal's checks of what stands (checks, each passed or with what failed: doors and windows a person opens move, glazing is glass, every room's floor covered, every placed piece standing, nothing written as loose debris or buried, wall finishes built, stairs arriving inside a room clear of walls, every level holding rooms or walls: the ground, terraces and foundations belong to the ground level, Pascal draws the site and foundations; where units are named, every room in one or plausibly common). Call again with replace: true to revise the previous conversion: the module and adapter you leave out are the stored ones, edits change parts of them, and with neither a payload nor a module, adapter or edits the stored conversion is written again. Stable element identities and manual changes are retained; overlapping changes are refused. An existing building without a conversion baseline is never cleared.` From 17e22aa4f7cfb11dc08830ddda734ba08eca66bc Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 22:57:23 +0100 Subject: [PATCH 26/40] The pascal-3d workflow states the output limit and that the payload is the whole design The conversion workflow no longer says author_scene writes a design "in one call". It states that the payload holds the whole design and that one answer's output limit counts the thinking and the payload together, the facts the tool's description now carries. Co-Authored-By: Claude Sonnet 5.5 --- skills/pascal-3d/references/tool-workflows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/pascal-3d/references/tool-workflows.md b/skills/pascal-3d/references/tool-workflows.md index 9666ad9c61..e00d60b844 100644 --- a/skills/pascal-3d/references/tool-workflows.md +++ b/skills/pascal-3d/references/tool-workflows.md @@ -57,7 +57,7 @@ If a live-sync version conflict occurs, call `load_scene`, inspect the newer gra ## Convert a design written as three.js -`author_scene` turns a whole design you wrote as one three.js module into native, editable Pascal nodes in one call. The reading is yours; the writing is Pascal's. +`author_scene` turns a whole design you wrote as one three.js module into native, editable Pascal nodes: the payload holds the whole design, and one answer's output limit counts the thinking and the payload together. The reading is yours; the writing is Pascal's. 1. Read your module: its source for intent (helper names, declared opening types), the executed graph for truth (world transforms, deleted objects gone). Most designs make walls with a helper such as `wall(x1, z1, x2, z2, height, thickness, openings)`: those arguments are the payload's walls. 2. Build the payload: per level, `walls` (centerline `start`/`end`, `height`, `thickness`, `through` to bend it into an arc from start through that plan point to end (the arc's middle: put it outside the building for a bay that bulges out; at most half the span from the straight line): one curved wall for a bay, an apse or a drum, never a run of short straight ones, its openings' `along` measured along the arc, rooms derived from the arc, nothing hung on it, no face module; `curtain` for a glass wall between mullions, straight or curved (`spacing`, default 1.5 m, `frameColor`), whose faces take no paint or skirting, `color` for both faces, `colorInside` / `colorOutside` for the faces that look into a room of the level and the face that does not (Pascal finds which once the rooms are derived and says so in `defaults`; give an outside wall's two finishes this way), or `colorLeft` / `colorRight` for one face, the left being on your left looking from start to end, over the other two; a hex is written as an exact material, one per colour; `skirting` with `height` (default 0.1 m), `depth` (default 0.012 m) and `color` for the baseboard, native on the wall along the faces its rooms stand on), their `openings` (`kind` door, window or passage, a doorway with no leaf, `along` from the wall's start, `width`, `height`, `sill`, `shape` rectangle, rounded or arch with `archHeight`, `type` for how it opens: hinged, double, french, sliding, pocket… for a door, fixed, casement, awning, double-hung… for a window; `style` for its look: glass, six-panel, modern… for a leaf, grid, transom, double-hung… for a fixed window's panes; `leaves`, `hinge`; or `code`, a module with mount `wall`, for a shape those cannot express), `rooms` (`name`, `seed`, `unit`, in a building of several dwellings or tenancies, the name of the dwelling, suite or lot the room belongs to (Apartment 2B, Suite 301, Shop 1; a room naming none is common area: a corridor, a lobby, the stairs; a single-family house has no units), `floor` as `library:` from `search_materials` or `#rrggbb`; `floorCode` for planks, tiles or boards, a module that receives `params.polygon` and `params.holes`, plan x/z in level coordinates and metres, and lays out the finish with y = 0 at the floor's surface (lay it from there up; Pascal stands the build on the floor plate and what stands on that floor, a rug or a sofa at y = 0, on the build's top), which Pascal cuts to that floor and its holes: Pascal rebuilds it when the room changes, `floor` stays the fallback, `get_source` with the room's id reads it back; `wallCode`, with `wallToHeight`, for the finish of every wall face the room looks into), each wall's `faceLeft` / `faceRight` (`code`, `toHeight` from the face's base, default the whole face) for tiles, panelling or boards on that face, or `faceOutside` for cladding, brick or battens on the face no room looks into (Pascal finds it, as for `colorOutside`), a module that receives `params.outline`, `params.holes`, `params.base` and `params.thickness` in wall-local metres (x along the wall from its start, y up from the face's base, z out of the face) and lays out the finish, which Pascal cuts to the outline and its openings, over the room's `wallCode`, `colorLeft` / `colorRight` staying the paint under it, `slabs` (terraces, platforms, balconies: Pascal builds floor plates, wall caps and ceilings itself, so fold a module's caps, underlays and floor planks into the wall, the floor finish and the room, and say so in `notes`; `surfaceCode` for a terrace's decking or paving, a module that receives the slab's `params.polygon` and `params.holes` and lays the finish from y = 0, the slab's top, as a room's `floorCode` does; each `railing` run (`start`, `end`, `height`, `color`) a fence standing on the slab), `voids` (a `polygon` in the level's floor that the room below rises through: a double-height living room under a gallery, an atrium; Pascal cuts that floor and the ceiling under it, stops the cut at the faces of the level's walls, and runs a `railing` (`height`, default 1.1 m, `color`; null for none) along its open edges, broken at walls and where a stair arrives; a ceiling item or a light under it hangs from the ceiling above; never on the first level), `columns` (`shape` square or round, a round one's `width` its diameter, `rotation`, `color` as an exact material, or `code`, a module with mount `floor` as `add_column` takes it, whose build sets the size and keeps its own colours), `stairs` (`start`, the middle of the bottom step's front edge, `rotation` 0 climbing toward +z, 90 toward +x, `width` (default 1 m), `layout` straight, l or u, `turn` left or right, `length`, `railing` none, left, right or both, `railingStyle`, `color` for the flight, `treads` over it, `railingColor`: each rises to the next level in `levels`, as `create_stair` builds it, and opens the floor above over its flights; a stair is never an item), `items` (`id`, `name`, `category`, `code` as its own module, `position` at its bottom centre, `rotation`, `host` for a lamp on a nightstand or a mirror on a wall; a module with mount `ceiling`, a pendant or a ceiling light, hangs from the ceiling of the room containing its plan position, its top on that ceiling, y not read; a rug, a mat or a runner on a room's floor is an item), `lights` (`position`, `fixture`); and, on the payload, `units` (`name`, `kind` apartment, hotel-room, commercial or common, `color`) to type or colour the units the rooms name: Pascal makes one unit per distinct name under the building, holding the rooms that name it, on whatever levels they are (a duplex); a unit named only by rooms is an apartment. A light without `fixture` gets a minimal ceiling point hosted on its room’s ceiling; outside every room it falls back to the nearest item on the level, reported in `defaults`. Item and scripted-opening slots keep their authored colour, roughness and metalness as exact materials; a material named `glass` or made transparent stays Pascal’s glass, and an emissive one keeps its own glow. Opening `color` paints the door’s panel and frame or the window’s frame; `frameColor` overrides the frame (default: `color`). Scripted openings keep their declared `type`; only `style` is ignored. Wall-hosted items keep their bottom centre’s outward distance from the nearest face; a point inside the wall moves to the face and is reported in `defaults`. Give each level its `elevation`, its floor's surface: a storey is as tall as the climb to the next level's floor (the top one as its tallest wall); walls keep their height and Pascal draws the floor between storeys from the tallest wall within 0.5 m under it up to that floor (2.7 m walls under a floor at 2.9 m: 2.7 m rooms and a 0.2 m floor); a wall reaching into that floor stops under it. End a partition on the centerline of the wall it meets. One item per piece: a bed, each nightstand, each chair. From 3557deebb085208587a7c3193909faaf3506d156 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Mon, 2 Nov 2026 23:00:10 +0100 Subject: [PATCH 27/40] The pascal-3d skill's author_scene paragraph states facts, not an order The paragraph told an agent not to rebuild a design tool by tool and to call author_scene once. It now says what author_scene does and what an answer holds: the payload is the whole design, one answer's output limit counts the thinking and the payload together, and a revision removes what its payload leaves out of the previous conversion. Co-Authored-By: Claude Sonnet 5.5 --- skills/pascal-3d/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/pascal-3d/SKILL.md b/skills/pascal-3d/SKILL.md index 7d1534a4fa..39487a236b 100644 --- a/skills/pascal-3d/SKILL.md +++ b/skills/pascal-3d/SKILL.md @@ -77,7 +77,7 @@ Stair `targets` are design preferences in meters (`maxRiserHeight`, `minimumGoin When those tools and the catalog cannot reproduce something faithfully (custom columns, a porch, lanterns, a garage door, a vaulted or tray ceiling), build it with `add_object`: a plain three.js module, or with `language: 'bpy'` a Blender module when the shape needs Blender's modelling (bevels, smooth organic forms, booleans, curves), with the naming conventions its description lists for paint slots, parts, lights, cutouts and clips; its slot colours show as the library finishes they match, and `exact: true` keeps them as written. Edit it by passing its `nodeId`. A new object needs a `reason` (why no Pascal tool or catalog item builds it); `verify_scene` lists every authored object with its reason. On a floor, a plain box with a wall's size or a floor plate is refused with the tool to use (`use_walls`, `use_slab`); a detailed object with a wall's size (a bookcase, a screen) is built with a hint naming `add_wall`. Servers without a script host answer `scripts_unavailable`. The hosted server builds three.js scripts in the user's open Pascal editor tab (Blender modules run in its Blender service and need no tab); when no tab has the project open it answers `editor_tab_required` with an `editorUrl`: give the user that link, wait until they say it is open, then repeat the same call. `editor_tab_busy` means a tab is open but busy or still loading: wait a few seconds and repeat the same call; the user need not be asked. Whether you may open the link yourself is the person's setting ("Agents may open the editor for me"; Ask first: ask the user to open the link (or bring the tab forward), or ask their permission before opening it yourself; Allow: you may open the link yourself, in a tab in front; Never: ask the user, and do not open or switch windows yourself); the refusal's words say which, so follow them. It applies to `editor_tab_required` and `editor_tab_hidden`; `editor_tab_busy` carries no link, and an autonomous agent account, which has no editor login, is refused with `editor_host_identity_required` whatever the setting says. To count or locate things by what they are, including typed parts inside authored objects, use `find_by_type`. To group elements of any kind into a named set the editor lists (all the lights, the windows, the kitchen cabinetry), use `edit_collection`, starting from a template when one fits; `list_collections` reads them back. -When you have written a whole design as free three.js (a room, a flat, a house: the richest results come from building it that way, with no Pascal tools in the loop), do not rebuild it tool by tool. Read your own module however you like (its source, running it and reading the objects, both) and call `author_scene` once with a conversion payload: levels, walls as centerlines (`through`, a plan point its arc passes at its middle, bends one into an arc; a `curtain` makes it a glass wall) with their colour (`color`; `colorInside` / `colorOutside` for the faces that look into a room of the level and the face that does not, which Pascal finds once the rooms are derived and reports in `defaults`: say an outside wall's two finishes this way; `colorLeft` / `colorRight` per face win over both; a hex is kept as an exact material) and their openings (each with `type`, how it opens, and `style`, its look, `shape` for an arch or rounded top, or its own `code` for a shape those cannot express; a window with no type is written fixed and cannot open; a `passage` is a doorway with no leaf), rooms with a seed point, a floor material and, in a building of several dwellings or tenancies (a condo, an apartment building, a hotel, shops under flats), the `unit` each belongs to by name (Apartment 2B, Suite 301, Shop 1; `units` on the payload gives a unit its `kind`, apartment, hotel-room, commercial or common, and its colour; a unit may span levels, a duplex; a room naming no unit is common area, a corridor, a lobby, the stairs; a single-family house has no units), slabs (a terrace's decking or paving its `surfaceCode`, a module laid on the slab's outline from its top, as a room's `floorCode` is; each `railing` run a fence standing on it, at its `height` and `color`), `voids` (an opening in a level's floor that the room below rises through, a double-height room: Pascal cuts that floor and the ceiling under it and runs a railing along its open edges), columns (square or round, `rotation`, `color`, or their own `code` for a shape those cannot express, mount `floor` as `add_column` takes it), railings, `stairs` (per level: `start`, the middle of the bottom step's front edge, `rotation`, the climb's direction, `width`, `layout` straight, l or u, `turn`, `railing` sides and `railingStyle`, `color` for the flight, `treads` over it, `railingColor`; each rises to the next level in `levels` as `create_stair` builds it and opens the floor above over its flights; never a stair as an item), every piece of furniture as an authored object with its own module (`host` names the item it rests on, or the wall a casing or mirror is fixed to; a module with mount `ceiling`, a pendant or a ceiling light, hangs from the ceiling of the room containing its plan position, its top on that ceiling; a rug, a mat or a runner lying on a room's floor is an item), and lights. A wall's baseboard is its `skirting` (`height`, `depth`, `color`), native on the wall along the faces its rooms stand on, never an item. A plank, tile or board floor is the room's `floorCode`, a module that receives `params.polygon` and `params.holes` (plan x/z in level coordinates) and builds the finish for exactly that floor, with y = 0 at the floor's surface: lay the finish from there up, and Pascal stands it on the floor plate and everything on that floor (a rug, a sofa) on its top, so give such an item y = 0; Pascal rebuilds it when the room changes, keeps `floor` as the fallback, and `get_source` on the room reads it back. Tiles with joints, panelling to a dado or boards on a wall are the wall's `faceLeft` / `faceRight` (`code`, `toHeight` from the face's base, default the whole face), a module that receives `params.outline`, `params.holes` (its doors and windows), `params.base` and `params.thickness` in wall-local metres and builds the finish for exactly that face, or the room's `wallCode` (`wallToHeight`) for every face the room looks into; cladding, brick, banded render or battens outside are the wall's `faceOutside`, the same module on the face no room looks into (which face that is, is Pascal's to find, as for `colorOutside`); Pascal rebuilds it when the wall or its openings change, `colorLeft` / `colorRight` stay the paint under it, and `get_source` with the wall's id and `face` reads it back. A light without `fixture` gets a minimal ceiling point hosted on its room’s ceiling; outside every room it falls back to the nearest item on the level, reported in `defaults`. Item and scripted-opening slots keep their authored colour, roughness and metalness as exact materials; a material named `glass` or made transparent stays Pascal’s glass, and an emissive one keeps its own glow. Opening `color` paints the door’s panel and frame or the window’s frame; `frameColor` overrides the frame (default: `color`). Scripted openings keep their declared `type`; only `style` is ignored. Wall-hosted items keep their bottom centre’s outward distance from the nearest face; a point inside the wall moves to the face and is reported in `defaults`. Pascal compiles and stores the modules, derives the rooms and floors, paints, runs its checks and answers with a gate report: what it wrote, what it filled in (`defaults`: a window written fixed, a handle set opposite its hinge, a ceiling point for a light without a fixture, the ceiling a ceiling item hangs from, which faces `colorInside` took, each stair and its floor opening), what it wrote but doubts (`warnings`: thin or many slabs, many floor regions, a stair given as an item, a stair no floor above covers), what it could not place and why (`defects`: a floor module that failed is `floor_script_failed`, the room keeping its `floor`; a face module that failed is `face_script_failed`, a face no room looks into `no_face`, a ceiling item outside every room `no_ceiling`, a stair on the top level `no_level_above`), what it corrected (a wall end snapped onto the centerline it meets). Pascal builds a wall's cap, the floor plate and the ceiling itself: fold a module's caps, underlays and individual floor planks into the native wall, the floor finish and the room, and say so in `notes`; a slab over a wall's top is refused. Fix your program, call again with `replace: true`, until the report is clean and the editor shows the design. A payload too large for one call goes as a JSON project file (`upload_project_file`) named by `payloadFile`. Pass the module and your program as `module` and `adapter`: they are kept with the scene, and with no `payload` Pascal runs the adapter itself; a revision names only what changed (`edits` against the stored module and adapter). An item may name an `add_object` `piece` (furniture described in words, written by Pascal's own model in the background) instead of carrying `code`. The report's `checks` say what still falls short. Build the building as it is built: a wall at its real height (a half-height partition is fine), nothing lowered or removed for viewing. A level's `elevation` (its floor's surface) sets the storey below it: a storey is as tall as the climb to the next level's floor, the top one as its tallest wall. Walls keep the height you give them (the room's height as built) and Pascal draws the floor between storeys from the tallest wall within 0.5 m under it up to that floor: 2.7 m walls under a floor at 2.9 m give 2.7 m rooms and a 0.2 m floor, reported in `defaults`; a wall reaching into the floor above stops under it. In the module, name a piece's group `item:` when you can, one helper per piece, and give everything that opens (drawers, wardrobe doors, windows) an `open` animation clip: named pieces convert with exact names and moving parts keep working after conversion. +When you have written a whole design as free three.js (a room, a flat, a house: the richest results come from building it that way, with no Pascal tools in the loop), `author_scene` converts it into native nodes without rebuilding it tool by tool; its payload is the whole design, and one answer's output limit counts the thinking and the payload together. Read your own module however you like (its source, running it and reading the objects, both) and hand `author_scene` a conversion payload: levels, walls as centerlines (`through`, a plan point its arc passes at its middle, bends one into an arc; a `curtain` makes it a glass wall) with their colour (`color`; `colorInside` / `colorOutside` for the faces that look into a room of the level and the face that does not, which Pascal finds once the rooms are derived and reports in `defaults`: say an outside wall's two finishes this way; `colorLeft` / `colorRight` per face win over both; a hex is kept as an exact material) and their openings (each with `type`, how it opens, and `style`, its look, `shape` for an arch or rounded top, or its own `code` for a shape those cannot express; a window with no type is written fixed and cannot open; a `passage` is a doorway with no leaf), rooms with a seed point, a floor material and, in a building of several dwellings or tenancies (a condo, an apartment building, a hotel, shops under flats), the `unit` each belongs to by name (Apartment 2B, Suite 301, Shop 1; `units` on the payload gives a unit its `kind`, apartment, hotel-room, commercial or common, and its colour; a unit may span levels, a duplex; a room naming no unit is common area, a corridor, a lobby, the stairs; a single-family house has no units), slabs (a terrace's decking or paving its `surfaceCode`, a module laid on the slab's outline from its top, as a room's `floorCode` is; each `railing` run a fence standing on it, at its `height` and `color`), `voids` (an opening in a level's floor that the room below rises through, a double-height room: Pascal cuts that floor and the ceiling under it and runs a railing along its open edges), columns (square or round, `rotation`, `color`, or their own `code` for a shape those cannot express, mount `floor` as `add_column` takes it), railings, `stairs` (per level: `start`, the middle of the bottom step's front edge, `rotation`, the climb's direction, `width`, `layout` straight, l or u, `turn`, `railing` sides and `railingStyle`, `color` for the flight, `treads` over it, `railingColor`; each rises to the next level in `levels` as `create_stair` builds it and opens the floor above over its flights; never a stair as an item), every piece of furniture as an authored object with its own module (`host` names the item it rests on, or the wall a casing or mirror is fixed to; a module with mount `ceiling`, a pendant or a ceiling light, hangs from the ceiling of the room containing its plan position, its top on that ceiling; a rug, a mat or a runner lying on a room's floor is an item), and lights. A wall's baseboard is its `skirting` (`height`, `depth`, `color`), native on the wall along the faces its rooms stand on, never an item. A plank, tile or board floor is the room's `floorCode`, a module that receives `params.polygon` and `params.holes` (plan x/z in level coordinates) and builds the finish for exactly that floor, with y = 0 at the floor's surface: lay the finish from there up, and Pascal stands it on the floor plate and everything on that floor (a rug, a sofa) on its top, so give such an item y = 0; Pascal rebuilds it when the room changes, keeps `floor` as the fallback, and `get_source` on the room reads it back. Tiles with joints, panelling to a dado or boards on a wall are the wall's `faceLeft` / `faceRight` (`code`, `toHeight` from the face's base, default the whole face), a module that receives `params.outline`, `params.holes` (its doors and windows), `params.base` and `params.thickness` in wall-local metres and builds the finish for exactly that face, or the room's `wallCode` (`wallToHeight`) for every face the room looks into; cladding, brick, banded render or battens outside are the wall's `faceOutside`, the same module on the face no room looks into (which face that is, is Pascal's to find, as for `colorOutside`); Pascal rebuilds it when the wall or its openings change, `colorLeft` / `colorRight` stay the paint under it, and `get_source` with the wall's id and `face` reads it back. A light without `fixture` gets a minimal ceiling point hosted on its room’s ceiling; outside every room it falls back to the nearest item on the level, reported in `defaults`. Item and scripted-opening slots keep their authored colour, roughness and metalness as exact materials; a material named `glass` or made transparent stays Pascal’s glass, and an emissive one keeps its own glow. Opening `color` paints the door’s panel and frame or the window’s frame; `frameColor` overrides the frame (default: `color`). Scripted openings keep their declared `type`; only `style` is ignored. Wall-hosted items keep their bottom centre’s outward distance from the nearest face; a point inside the wall moves to the face and is reported in `defaults`. Pascal compiles and stores the modules, derives the rooms and floors, paints, runs its checks and answers with a gate report: what it wrote, what it filled in (`defaults`: a window written fixed, a handle set opposite its hinge, a ceiling point for a light without a fixture, the ceiling a ceiling item hangs from, which faces `colorInside` took, each stair and its floor opening), what it wrote but doubts (`warnings`: thin or many slabs, many floor regions, a stair given as an item, a stair no floor above covers), what it could not place and why (`defects`: a floor module that failed is `floor_script_failed`, the room keeping its `floor`; a face module that failed is `face_script_failed`, a face no room looks into `no_face`, a ceiling item outside every room `no_ceiling`, a stair on the top level `no_level_above`), what it corrected (a wall end snapped onto the centerline it meets). Pascal builds a wall's cap, the floor plate and the ceiling itself: fold a module's caps, underlays and individual floor planks into the native wall, the floor finish and the room, and say so in `notes`; a slab over a wall's top is refused. Fix your program, call again with `replace: true` (the payload is the whole design: what it leaves out of the previous conversion is removed), until the report is clean and the editor shows the design. A payload too large for one call goes as a JSON project file (`upload_project_file`) named by `payloadFile`. Pass the module and your program as `module` and `adapter`: they are kept with the scene, and with no `payload` Pascal runs the adapter itself; a revision names only what changed (`edits` against the stored module and adapter). An item may name an `add_object` `piece` (furniture described in words, written by Pascal's own model in the background) instead of carrying `code`. The report's `checks` say what still falls short. Build the building as it is built: a wall at its real height (a half-height partition is fine), nothing lowered or removed for viewing. A level's `elevation` (its floor's surface) sets the storey below it: a storey is as tall as the climb to the next level's floor, the top one as its tallest wall. Walls keep the height you give them (the room's height as built) and Pascal draws the floor between storeys from the tallest wall within 0.5 m under it up to that floor: 2.7 m walls under a floor at 2.9 m give 2.7 m rooms and a 0.2 m floor, reported in `defaults`; a wall reaching into the floor above stops under it. In the module, name a piece's group `item:` when you can, one helper per piece, and give everything that opens (drawers, wardrobe doors, windows) an `open` animation clip: named pieces convert with exact names and moving parts keep working after conversion. Pascal uses meters. X and Z are floor-plan axes; Y is vertical. Tool fields that accept measurements may also accept strings such as `"6 ft"` or `"180cm"`, but report final spatial values in meters and retain the user's original units when useful. From 7bff976786ea80323f85e2214dea3ddc64700470 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 13:31:29 +0100 Subject: [PATCH 28/40] author_scene's description states what a conversion stores and what a later call changes of it A conversion stores one module and one adapter, and only when it succeeds. A later call with replace: true and edits changes parts of them: each find text must occur exactly once, and the adapter runs on the whole edited module. The sentence states these as facts, next to the one on replace and conversion_exists; no order. Co-Authored-By: Claude Sonnet 5.5 --- .../agent-tools/author-scene-description.test.ts | 13 +++++++++++++ packages/core/src/agent-tools/author-scene.ts | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/core/src/agent-tools/author-scene-description.test.ts b/packages/core/src/agent-tools/author-scene-description.test.ts index 6c8561facf..83469c91ec 100644 --- a/packages/core/src/agent-tools/author-scene-description.test.ts +++ b/packages/core/src/agent-tools/author-scene-description.test.ts @@ -20,3 +20,16 @@ test("author_scene's description names the native tools that add to the scene a for (const tool of ['create_room', 'add_wall', 'add_door', 'add_window', 'create_stair']) expect(authorSceneTool.description).toContain(tool) }) + +// The module and the adapter are what a conversion stores, when it succeeds; a later call with +// replace: true and edits changes parts of them (each find text occurring once) and the adapter runs +// on the whole edited module (`packages/mcp/src/tools/author-scene.ts`). The description says so, as facts. +test("author_scene's description states what a conversion stores and what a later call changes of it", () => { + const { description } = authorSceneTool + expect(description).toContain( + 'A conversion stores one module and one adapter, and only when it succeeds', + ) + expect(description).toContain('a later call with replace: true and edits') + expect(description).toContain('each find text occurring exactly once') + expect(description).toContain('the adapter runs on the whole edited module') +}) diff --git a/packages/core/src/agent-tools/author-scene.ts b/packages/core/src/agent-tools/author-scene.ts index ce43fb16d8..4393f57260 100644 --- a/packages/core/src/agent-tools/author-scene.ts +++ b/packages/core/src/agent-tools/author-scene.ts @@ -13,7 +13,7 @@ Coordinates: metres, plan x/z, Y up, each level's floor at y = 0 in its own fram Hand over the payload, or your module and its adapter, the program that reads the module and returns the payload: Pascal runs the adapter (one that throws comes back with its error, and nothing is written). A payload too large for one call goes by reference: upload it as a JSON project file (upload_project_file, phase prepare, PUT, complete) and pass its fileId as payloadFile. An item names its piece instead of code when add_object makes it from words; one still being made is written when it lands, with no call from you. Pieces made from words are written many at a time while you go on, so furniture made that way does not lengthen your turn the way pieces you write yourself do. -One answer has an output limit, and the limit counts thinking and the call's arguments together; answers that planned and wrote a whole house as one payload have stopped there before the payload was complete. The payload is the whole design: a later call with replace: true removes what its payload leaves out, and a call without replace on a scene that holds a conversion is refused (conversion_exists). create_room, add_wall, add_door, add_window and create_stair add to the scene a call at a time. +One answer has an output limit, and the limit counts thinking and the call's arguments together; answers that planned and wrote a whole house as one payload have stopped there before the payload was complete. The payload is the whole design: a later call with replace: true removes what its payload leaves out, and a call without replace on a scene that holds a conversion is refused (conversion_exists). A conversion stores one module and one adapter, and only when it succeeds; a later call with replace: true and edits (each find text occurring exactly once) changes parts of them, and the adapter runs on the whole edited module. create_room, add_wall, add_door, add_window and create_stair add to the scene a call at a time. The report says what was written, what Pascal defaulted (defaults: a window with no type is fixed and cannot open), what it warns about but wrote (warnings: thin slabs, too many slabs or regions), what it refused (defects, by your ids), the items waiting for their pieces (pending), and Pascal's checks of what stands (checks, each passed or with what failed: doors and windows a person opens move, glazing is glass, every room's floor covered, every placed piece standing, nothing written as loose debris or buried, wall finishes built, stairs arriving inside a room clear of walls, every level holding rooms or walls: the ground, terraces and foundations belong to the ground level, Pascal draws the site and foundations; where units are named, every room in one or plausibly common). From 23fe50758646ed88759fb79b8121d17b3a88b4bd Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 15:27:19 +0100 Subject: [PATCH 29/40] A probation list withholds usage_wall_object_protrudes from verify_scene Most of its findings were towel rails and robe fit-outs, which stand out from the wall by design. The check's code stays and usageIssues still returns it; it comes back after an improvement, or is removed. Co-Authored-By: DeepSeek V4.1 Flash Co-Authored-By: Claude Sonnet 5.5 --- .../scene-check-policy.test.ts | 136 ++++++++++++++++++ .../agent-operations/scene-check-policy.ts | 16 +++ .../core/src/agent-operations/verify-scene.ts | 2 + 3 files changed, 154 insertions(+) create mode 100644 packages/core/src/agent-operations/scene-check-policy.test.ts create mode 100644 packages/core/src/agent-operations/scene-check-policy.ts diff --git a/packages/core/src/agent-operations/scene-check-policy.test.ts b/packages/core/src/agent-operations/scene-check-policy.test.ts new file mode 100644 index 0000000000..edf2f37524 --- /dev/null +++ b/packages/core/src/agent-operations/scene-check-policy.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + ItemNode, + LevelNode, + SlabNode, + WallNode, + ZoneNode, +} from '../schema' +import { usageIssues } from '../spatial/usage-field/findings' +import { setSdfChecks } from '../spatial/usage-field/flag' +import './index' +import { SCENE_CHECK_PROBATION, withoutProbation } from './scene-check-policy' +import type { SceneNodes } from './types' +import { verifyScene } from './verify-scene' + +// A 6 x 4 m kitchen; its south wall is along z = 0, the room on the +z side of it. +function kitchen(extra: AnyNode[], wallChildren: string[] = []): SceneNodes { + const nodes: AnyNode[] = [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), + SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [-0.3, -0.3], + [6.3, -0.3], + [6.3, 4.3], + [-0.3, 4.3], + ], + elevation: 0.05, + }), + WallNode.parse({ + id: 'wall_s', + parentId: 'level_1', + start: [0, 0], + end: [6, 0], + thickness: 0.1, + children: wallChildren, + }), + WallNode.parse({ + id: 'wall_e', + parentId: 'level_1', + start: [6, 0], + end: [6, 4], + thickness: 0.1, + }), + WallNode.parse({ + id: 'wall_n', + parentId: 'level_1', + start: [6, 4], + end: [0, 4], + thickness: 0.1, + }), + WallNode.parse({ + id: 'wall_w', + parentId: 'level_1', + start: [0, 4], + end: [0, 0], + thickness: 0.1, + }), + ZoneNode.parse({ + id: 'zone_k', + parentId: 'level_1', + name: 'Kitchen', + polygon: [ + [0.05, 0.05], + [5.95, 0.05], + [5.95, 3.95], + [0.05, 3.95], + ], + }), + ...extra, + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes +} + +/** A wall-hung piece whose depth stands it out of the face it is on. */ +const hanging = () => + ItemNode.parse({ + id: 'item_hung', + parentId: 'wall_s', + wallId: 'wall_s', + position: [3, 1.4, 0], + side: 'front', + asset: { + id: 'rail', + name: 'Rail', + category: 'bathroom', + thumbnail: '/thumb.webp', + src: '/items/rail/model.glb', + dimensions: [0.85, 0.6, 0.46], + attachTo: 'wall-side', + }, + }) + +const typesOf = (nodes: SceneNodes) => + (verifyScene(nodes, {}, { activeLevelId: 'level_1' }).result as { issues: { type: string }[] }) + .issues + +describe('a finding type on probation', () => { + test('is withheld; the others keep their order', () => { + const issues = [ + { type: 'usage_pocket', message: 'first' }, + { type: 'usage_wall_object_protrudes', message: 'second' }, + { type: 'empty_levels', message: 'third' }, + ] + expect(withoutProbation(issues)).toEqual([issues[0], issues[2]]) + }) + + test('an empty list stays empty', () => { + expect(withoutProbation([])).toEqual([]) + }) + + test('the list names the type and why it is withheld', () => { + expect(Object.keys(SCENE_CHECK_PROBATION)).toEqual(['usage_wall_object_protrudes']) + expect(SCENE_CHECK_PROBATION.usage_wall_object_protrudes).toContain('towel rails') + }) + + test('verify_scene reports none of it while usageIssues still finds it', () => { + const nodes = kitchen([hanging()], ['item_hung']) + expect(usageIssues(nodes).some((issue) => issue.type === 'usage_wall_object_protrudes')).toBe( + true, + ) + setSdfChecks(true) + try { + const withheld = typesOf(nodes).filter( + (issue) => issue.type === 'usage_wall_object_protrudes', + ) + expect(withheld).toEqual([]) + } finally { + setSdfChecks(false) + } + }) +}) diff --git a/packages/core/src/agent-operations/scene-check-policy.ts b/packages/core/src/agent-operations/scene-check-policy.ts new file mode 100644 index 0000000000..66aa627b3e --- /dev/null +++ b/packages/core/src/agent-operations/scene-check-policy.ts @@ -0,0 +1,16 @@ +/** + * A type withheld from what verify_scene reports while its check keeps emitting it. + * + * `usage_wall_object_protrudes` is on probation: most of its findings were towel rails and robe + * fit-outs, which stand out from the wall by design; it comes back after an improvement, or is + * removed. + */ +export const SCENE_CHECK_PROBATION: Readonly> = { + usage_wall_object_protrudes: + 'most findings were towel rails and robe fit-outs, which stand out from the wall by design', +} + +/** The issues whose type is not on probation, in the order they came. */ +export function withoutProbation(issues: T[]): T[] { + return issues.filter((issue) => !Object.hasOwn(SCENE_CHECK_PROBATION, issue.type)) +} diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index cfc294ad37..0e98b44e10 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -42,6 +42,7 @@ import { pointInPolygon, polygonContainsPolygon, type Vec2 } from './plan-geomet import type { RoomCheckIssue } from './room-checks' import { type RoomFinding, roomFindings } from './room-findings' import { roomIssueScope } from './room-readings' +import { withoutProbation } from './scene-check-policy' import { EMPTY_SESSION } from './scene-checkpoint' import { sceneIssueGroups } from './scene-issue-groups' import { changesSince, type SceneCheckpoint } from './scene-measure' @@ -808,6 +809,7 @@ export const verifyScene: AgentOperation = ( if (check.order >= CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {}, context)) const occupiedStoryCount = levels.filter((level) => level.isOccupiedStory).length + issues.splice(0, issues.length, ...withoutProbation(issues)) const issueGroups = sceneIssueGroups(issues, nodes) return { result: { From a52c5248a54cdf558aef1ef938990ba987eda818 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 15:27:20 +0100 Subject: [PATCH 30/40] verify_scene drops a whole-room pocket that room_unreachable already names A whole-room usage_pocket repeats the room_unreachable finding for a closed room; a pocket beside objects and a pocket of a room nothing names are kept. Co-Authored-By: DeepSeek V4.1 Flash Co-Authored-By: Claude Sonnet 5.5 --- .../scene-check-policy-pockets.test.ts | 192 ++++++++++++++++++ .../agent-operations/scene-check-policy.ts | 34 ++++ .../core/src/agent-operations/verify-scene.ts | 4 +- 3 files changed, 228 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/agent-operations/scene-check-policy-pockets.test.ts diff --git a/packages/core/src/agent-operations/scene-check-policy-pockets.test.ts b/packages/core/src/agent-operations/scene-check-policy-pockets.test.ts new file mode 100644 index 0000000000..c0dfd8fea7 --- /dev/null +++ b/packages/core/src/agent-operations/scene-check-policy-pockets.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + DoorNode, + ItemNode, + LevelNode, + SlabNode, + WallNode, + ZoneNode, +} from '../schema' +import { usageIssues } from '../spatial/usage-field/findings' +import { setSdfChecks } from '../spatial/usage-field/flag' +import './index' +import { withoutDuplicatePockets } from './scene-check-policy' +import type { SceneNodes } from './types' +import { verifyScene } from './verify-scene' + +type Pt = [number, number] + +const wall = (id: string, start: Pt, end: Pt, children: string[] = []) => + WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.1, children }) + +const door = (id: string, wallId: string, x: number) => + DoorNode.parse({ + id, + parentId: wallId, + wallId, + position: [x, 1.05, 0], + width: 0.9, + height: 2.1, + frameDepth: 0.07, + }) + +const room = (id: string, name: string, x0: number, x1: number) => + ZoneNode.parse({ + id, + parentId: 'level_1', + name, + polygon: [ + [x0, 0], + [x1, 0], + [x1, 4], + [x0, 4], + ], + }) + +/** A stored piece centred on (x, z), its solid outline exact. */ +const piece = (id: string, x: number, z: number, width: number, depth: number) => + ItemNode.parse({ + id, + parentId: 'level_1', + position: [x, 0, z], + name: id, + asset: { + id, + name: id, + category: 'storage', + thumbnail: '/t.webp', + src: `/items/${id}/model.glb`, + dimensions: [width, 1.0, depth], + }, + }) + +// A 6 x 4 m shell with the street door in the west room; a partition at x = 3, with or without a +// door, makes the east room reachable or not. The extra pieces stand in the west room. +function house({ partitionDoor }: { partitionDoor: boolean }, extra: AnyNode[] = []): SceneNodes { + const nodes: AnyNode[] = [ + BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), + LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), + SlabNode.parse({ + id: 'slab_1', + parentId: 'level_1', + polygon: [ + [0, 0], + [6, 0], + [6, 4], + [0, 4], + ], + }), + wall('wall_s', [0, 0], [6, 0], ['door_front']), + wall('wall_e', [6, 0], [6, 4]), + wall('wall_n', [6, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + wall('wall_p', [3, 0], [3, 4], partitionDoor ? ['door_inner'] : []), + door('door_front', 'wall_s', 1.5), + ...(partitionDoor ? [door('door_inner', 'wall_p', 2)] : []), + room('zone_west', 'West room', 0, 3), + room('zone_east', 'East room', 3, 6), + ...extra, + ] + return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes +} + +const pocket = (roomId: string, over: Record = {}) => ({ + type: 'usage_pocket', + message: 'a pocket', + nodeIds: [roomId], + place: { room: roomId, roomId, at: [1, 2] as Pt }, + ...over, +}) + +const unreachable = (...nodeIds: string[]) => ({ + type: 'room_unreachable', + message: 'a room no walk reaches', + nodeIds, +}) + +describe('a whole-room pocket a room_unreachable finding already says', () => { + test('is dropped when its room is named', () => { + const named = unreachable('zone_a') + const found = pocket('zone_a', { wholeRoom: true, nodeIds: ['zone_a', 'item_x'] }) + expect(withoutDuplicatePockets([named, found])).toEqual([named]) + }) + + test('is kept when no finding names its room', () => { + const named = unreachable('zone_a') + const found = pocket('zone_b', { wholeRoom: true }) + expect(withoutDuplicatePockets([named, found])).toEqual([named, found]) + }) + + test('a pocket beside objects stays, even in a room a finding names', () => { + const named = unreachable('zone_a') + const found = pocket('zone_a', { nodeIds: ['zone_a', 'item_x', 'item_y'] }) + expect(withoutDuplicatePockets([named, found])).toEqual([named, found]) + }) + + test('a whole-floor pocket goes only when every room it names is named', () => { + const both = unreachable('zone_a', 'zone_b') + const floor = pocket('level_1', { + wholeRoom: true, + nodeIds: ['level_1', 'zone_a', 'zone_b'], + }) + expect(withoutDuplicatePockets([both, floor])).toEqual([both]) + const one = unreachable('zone_a') + expect(withoutDuplicatePockets([one, floor])).toEqual([one, floor]) + const noZones = pocket('level_1', { wholeRoom: true, nodeIds: ['level_1'] }) + expect(withoutDuplicatePockets([one, noZones])).toEqual([one, noZones]) + }) + + test('other types are untouched', () => { + const named = unreachable('zone_a') + const other = { type: 'empty_levels', message: 'nothing here' } + expect(withoutDuplicatePockets([named, other])).toEqual([named, other]) + }) +}) + +describe('verify_scene and a closed room', () => { + test('room_unreachable is reported and the room has no whole-room pocket of its own', () => { + const nodes = house({ partitionDoor: false }, [ + piece('item_a', 1.2, 1.0, 0.4, 1.4), + piece('item_b', 2.0, 1.4, 0.6, 0.4), + ]) + expect( + usageIssues(nodes).some( + (issue) => + issue.type === 'usage_pocket' && issue.place.roomId === 'zone_east' && issue.wholeRoom, + ), + ).toBe(true) + setSdfChecks(true) + try { + const issues = ( + verifyScene(nodes, {}, { activeLevelId: 'level_1' }).result as { + issues: { + type: string + place?: { roomId: string } + wholeRoom?: boolean + nodeIds?: string[] + }[] + } + ).issues + expect( + issues.some( + (issue) => issue.type === 'room_unreachable' && issue.nodeIds?.includes('zone_east'), + ), + ).toBe(true) + expect( + issues.filter( + (issue) => issue.type === 'usage_pocket' && issue.place?.roomId === 'zone_east', + ), + ).toEqual([]) + const west = issues.filter( + (issue) => issue.type === 'usage_pocket' && issue.place?.roomId === 'zone_west', + ) + expect(west).toHaveLength(1) + expect(west[0]?.wholeRoom).toBeUndefined() + expect(west[0]?.nodeIds).toEqual(['zone_west', 'item_a', 'item_b']) + } finally { + setSdfChecks(false) + } + }) +}) diff --git a/packages/core/src/agent-operations/scene-check-policy.ts b/packages/core/src/agent-operations/scene-check-policy.ts index 66aa627b3e..6e22214769 100644 --- a/packages/core/src/agent-operations/scene-check-policy.ts +++ b/packages/core/src/agent-operations/scene-check-policy.ts @@ -14,3 +14,37 @@ export const SCENE_CHECK_PROBATION: Readonly> = { export function withoutProbation(issues: T[]): T[] { return issues.filter((issue) => !Object.hasOwn(SCENE_CHECK_PROBATION, issue.type)) } + +type PocketFields = { + type: string + wholeRoom?: boolean + nodeIds?: string[] + place?: { roomId?: string } +} + +const fieldsOf = (issue: { type: string }): PocketFields => issue + +const isZoneId = (id: string) => id.startsWith('zone_') + +/** + * A whole-room pocket of a room, or of every room of a whole floor, that a room_unreachable + * finding already names. + */ +function repeatsUnreachable(pocket: PocketFields, named: ReadonlySet): boolean { + if (pocket.type !== 'usage_pocket' || pocket.wholeRoom !== true) return false + const roomId = pocket.place?.roomId + if (!roomId) return false + if (isZoneId(roomId)) return named.has(roomId) + const zoneIds = (pocket.nodeIds ?? []).filter(isZoneId) + return zoneIds.length > 0 && zoneIds.every((id) => named.has(id)) +} + +/** Drops the whole-room pockets a room_unreachable finding of the same list says. */ +export function withoutDuplicatePockets(issues: T[]): T[] { + const named = new Set( + issues + .filter((issue) => issue.type === 'room_unreachable') + .flatMap((issue) => fieldsOf(issue).nodeIds ?? []), + ) + return issues.filter((issue) => !repeatsUnreachable(fieldsOf(issue), named)) +} diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 0e98b44e10..d4a411eac9 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -42,7 +42,7 @@ import { pointInPolygon, polygonContainsPolygon, type Vec2 } from './plan-geomet import type { RoomCheckIssue } from './room-checks' import { type RoomFinding, roomFindings } from './room-findings' import { roomIssueScope } from './room-readings' -import { withoutProbation } from './scene-check-policy' +import { withoutDuplicatePockets, withoutProbation } from './scene-check-policy' import { EMPTY_SESSION } from './scene-checkpoint' import { sceneIssueGroups } from './scene-issue-groups' import { changesSince, type SceneCheckpoint } from './scene-measure' @@ -809,7 +809,7 @@ export const verifyScene: AgentOperation = ( if (check.order >= CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {}, context)) const occupiedStoryCount = levels.filter((level) => level.isOccupiedStory).length - issues.splice(0, issues.length, ...withoutProbation(issues)) + issues.splice(0, issues.length, ...withoutDuplicatePockets(withoutProbation(issues))) const issueGroups = sceneIssueGroups(issues, nodes) return { result: { From 829703bbb2fde9263abcc880b965887ee820e4c9 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 15:27:21 +0100 Subject: [PATCH 31/40] A doorway limited only by a standard door leaf informs A passage whose pinch is one door frame drawn at least 0.80 m is a standard leaf: the finding stays, as information, and says what the frame leaves clear. A narrower leaf, and a jamb-and-object pinch, still warn. Co-Authored-By: DeepSeek V4.1 Flash Co-Authored-By: Claude Sonnet 5.5 --- .../src/spatial/usage-field/findings.test.ts | 40 +++++++++++++++++++ .../core/src/spatial/usage-field/findings.ts | 9 ++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/packages/core/src/spatial/usage-field/findings.test.ts b/packages/core/src/spatial/usage-field/findings.test.ts index 760b96bbf0..076e5db0e8 100644 --- a/packages/core/src/spatial/usage-field/findings.test.ts +++ b/packages/core/src/spatial/usage-field/findings.test.ts @@ -222,6 +222,33 @@ describe('passages', () => { expect(issue!.message).not.toMatch(/non conforme/i) }) + test('a doorway limited only by its standard 0.82 m leaf informs: the frame leaves 0.72 m clear', () => { + const found = issues(twoRooms(0.82)).filter((i) => i.type === 'usage_passage_narrow') + expect(found).toHaveLength(1) + const [issue] = found + expect(issue!.severity).toBe('info') + expect(issue!.valueM).toBeCloseTo(0.72, 2) + expect(issue!.thresholdM).toBe(0.8) + expect(issue!.doorWidthM).toBe(0.82) + expect(issue!.message).toContain( + '0.72 m clear between the jambs of “Inner door”, a 0.82 m door', + ) + expect(issue!.message).toContain('(a 0.82 m door leaf: the frame leaves 0.72 m clear).') + expect(issue!.message).not.toContain('a doorway)') + expect(issue!.brief).toContain('(a 0.82 m door leaf: the frame leaves 0.72 m clear).') + expect(issue!.brief).not.toContain('a doorway)') + }) + + test('a leaf drawn 0.80 m informs at the boundary; 0.79 m is still a warning', () => { + const [boundary] = issues(twoRooms(0.8)).filter((i) => i.type === 'usage_passage_narrow') + expect(boundary!.severity).toBe('info') + expect(boundary!.doorWidthM).toBe(0.8) + const [narrow] = issues(twoRooms(0.79)).filter((i) => i.type === 'usage_passage_narrow') + expect(narrow!.severity).toBe('warning') + expect(narrow!.doorWidthM).toBe(0.79) + expect(narrow!.message).toContain('(below 0.80 m, a doorway)') + }) + test('a bookcase that leaves 0.70 m in a corridor narrows a passage that is not a doorway', () => { const found = issues(corridorWithBookcase()).filter( (i) => i.type === 'usage_passage_narrow' && i.place.room === 'Study', @@ -234,6 +261,19 @@ describe('passages', () => { expect(found[0]!.message).toMatch(/between “[^”]+” and “[^”]+”/) }) + test('a pinch between one jamb and a bookcase of the same clear width stays a warning', () => { + // a wide doorway whose north side a bookcase fills, leaving 0.72 m between it and the south jamb + const found = issues(twoRooms(1.2, [bookcase('item_1', 2.7, 2.77, 0.5, 1.2)])).filter( + (i) => i.type === 'usage_passage_narrow', + ) + expect(found).toHaveLength(1) + expect(found[0]!.valueM).toBeCloseTo(0.72, 2) + expect(found[0]!.thresholdM).toBe(0.8) + expect(found[0]!.obstacles.map((o) => o.kind).sort()).toEqual(['item', 'jamb']) + expect(found[0]!.severity).toBe('warning') + expect(found[0]!.message).not.toContain('door leaf') + }) + test('an approximate bookcase narrowing the corridor is a warning, not just a measurement', () => { const nodes = corridorWithBookcase() const bookcase = nodes.item_1 diff --git a/packages/core/src/spatial/usage-field/findings.ts b/packages/core/src/spatial/usage-field/findings.ts index 4a2d6e0615..5a85db3bbf 100644 --- a/packages/core/src/spatial/usage-field/findings.ts +++ b/packages/core/src/spatial/usage-field/findings.ts @@ -225,14 +225,19 @@ function passageIssue(nodes: Nodes, members: Narrow[]): UsageIssue { : `${m(passage.width)} m${between(sides)}` }${shared ? `; ${alternativeOf(shared)}` : ''}` const sentence = `${targets}: ${clause}` - const tail = ` (below ${m(limit)} m${doorway ? ', a doorway' : ''}).` + // a leaf drawn at least the doorway's 0.80 m is a standard door: what it leaves is information + const standardLeaf = typeof drawn === 'number' && drawn >= DOOR_M - TOLERANCE_M ? drawn : null + const tail = + standardLeaf === null + ? ` (below ${m(limit)} m${doorway ? ', a doorway' : ''}).` + : ` (a ${m(standardLeaf)} m door leaf: the frame leaves ${m(passage.width)} m clear).` const lead = members[0]!.room return { type: 'usage_passage_narrow', message: `Narrow passage to ${sentence}${door ? `, measured from ${quote(door)}` : ''}${tail}`, brief: `Passage to ${sentence}${tail}`, ...(door ? { fromDoor: door } : {}), - severity: 'warning', + severity: standardLeaf === null ? 'warning' : 'info', nodeIds: unique([ ...members.map(({ room }) => (room.roomId.startsWith('zone_') ? room.roomId : undefined)), ...sides.map((s) => s.nodeId), From d82c95b8faebfdf67881b5c898a16315137f6feb Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 15:27:22 +0100 Subject: [PATCH 32/40] usage_clash: an approximate outline warns from 12 cm An approximate outline's own error is of the order of 8-10 cm; below 12 cm it informs, an exact outline still warns from 8 cm. Co-Authored-By: DeepSeek V4.1 Flash Co-Authored-By: Claude Sonnet 5.5 --- .../core/src/spatial/usage-field/clash.ts | 9 ++++-- .../spatial/usage-field/findings-more.test.ts | 29 +++++++++++++++++-- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/core/src/spatial/usage-field/clash.ts b/packages/core/src/spatial/usage-field/clash.ts index f25a287586..82b2f4dd55 100644 --- a/packages/core/src/spatial/usage-field/clash.ts +++ b/packages/core/src/spatial/usage-field/clash.ts @@ -21,6 +21,8 @@ import type { Nodes } from './walls' export const CLASH_INFO_M = 0.02 /** From this depth a clash is a warning; between the two it is information. */ export const CLASH_WARNING_M = 0.08 +/** An approximate shape needs a warning at a greater depth: its outline's own error is this order. */ +export const CLASH_APPROX_WARNING_M = 0.12 /** A clash smaller than this in plan is a sliver (m²). */ export const CLASH_MIN_AREA_M2 = 0.002 /** A wall-fixed piece (a cabinet, a wall unit) may sink this far into a wall: it is scribed to it. */ @@ -138,7 +140,7 @@ export function pairClash( * door or window frame or sill, a stair or a guard (a curtain or a blind is read with its opening). Read on the real outlines, so a * contact (under 2 cm), a piece resting on another, a rug, foliage, a building element (trim, soffit, * pier, beam) and a wall-fixed piece scribed to its wall (5 cm) stay quiet. From 2 cm it is information, - * from 8 cm a warning, with approximate outlines still labeled as such. + * from 8 cm a warning, and from 12 cm for an approximate outline, still labeled as such. */ export function clashIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { const out: UsageIssue[] = [] @@ -187,14 +189,15 @@ export function clashIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { const target = isPiecePrism(b) ? `${quote(nameOf(nodes, b.nodeId))}` : `${WHAT[b.kind] ?? 'the'} ${quote(nameOf(nodes, b.nodeId))}` - const severity = depth >= CLASH_WARNING_M ? 'warning' : 'info' + const warnAt = approximate ? CLASH_APPROX_WARNING_M : CLASH_WARNING_M + const severity = depth >= warnAt ? 'warning' : 'info' out.push({ type: 'usage_clash', message: `${who} ${isPiecePrism(b) ? 'overlaps' : 'stands'} ${cm(depth)} ${isPiecePrism(b) ? 'of' : 'into'} ${target}${room ? ` in ${quote(room.name)}` : ''}${size >= 0.1 || approximate ? ` (${[size >= 0.1 ? `${Math.round(size * 1e4)} cm² in plan` : '', approximate ? 'approximate shape' : ''].filter(Boolean).join(', ')})` : ''}.`, severity, nodeIds: unique([room?.id, a.nodeId, b.nodeId]), valueM: Math.round(depth * 1000) / 1000, - thresholdM: CLASH_WARNING_M, + thresholdM: warnAt, place: { room: room?.name ?? '', roomId: room?.id ?? level.levelId, at }, obstacles: [a, b].map((prism) => ({ nodeId: prism.nodeId, diff --git a/packages/core/src/spatial/usage-field/findings-more.test.ts b/packages/core/src/spatial/usage-field/findings-more.test.ts index ae386bb100..2576e9f531 100644 --- a/packages/core/src/spatial/usage-field/findings-more.test.ts +++ b/packages/core/src/spatial/usage-field/findings-more.test.ts @@ -147,15 +147,38 @@ const closed = (extra: AnyNode[], heights: number[] = []) => ) describe('usage_clash', () => { - test('deep overlaps on approximate bounds warn, while shallow contacts stay information', () => { + test('an approximate outline 10 cm into a wall is information, and so is a contact', () => { const cupboard = piece('item_w', 'Wardrobe', 'wardrobe', 0.25, 2, 0.6, 1.5, 2) delete cupboard.source expect(run(closed([cupboard]), 'usage_clash')).toContainEqual( - expect.objectContaining({ severity: 'warning', approximate: true }), + expect.objectContaining({ severity: 'info', approximate: true, thresholdM: 0.12 }), ) cupboard.position[0] = 0.3 expect(run(closed([cupboard]), 'usage_clash')).toContainEqual( - expect.objectContaining({ severity: 'info', approximate: true }), + expect.objectContaining({ severity: 'info', approximate: true, thresholdM: 0.12 }), + ) + }) + + test('approximate outlines warn from 12 cm, exact outlines from 8 cm', () => { + const approximate = piece('item_a', 'Wardrobe', 'wardrobe', 0.25, 2, 0.6, 1.5, 2) + delete approximate.source + expect(run(closed([approximate]), 'usage_clash')).toContainEqual( + expect.objectContaining({ severity: 'info', valueM: 0.1, thresholdM: 0.12 }), + ) + const exact = piece('item_b', 'Wardrobe', 'wardrobe', 0.25, 2, 0.6, 1.5, 2) + expect(run(closed([exact]), 'usage_clash')).toContainEqual( + expect.objectContaining({ severity: 'warning', valueM: 0.1, thresholdM: 0.08 }), + ) + }) + + test('an approximate clash of 13 cm is a warning', () => { + const sofa = piece('item_a', 'Sofa', 'sofa', 2, 2, 2, 0.9, 0.8) + delete sofa.source + const cabinet = piece('item_b', 'Sideboard', 'sideboard', 3.12, 2, 0.5, 0.5, 0.8) + delete cabinet.source + const found = run(closed([sofa, cabinet]), 'usage_clash') + expect(found).toContainEqual( + expect.objectContaining({ severity: 'warning', valueM: 0.13, thresholdM: 0.12 }), ) }) From fca92192e2d2afe0f7c5e69a292b61b667f8dcf6 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 15:27:22 +0100 Subject: [PATCH 33/40] usage_clash: a bed against a window sill or frame is no finding Like a bed head at a window in usage_opening_blocked, it is a design choice. Co-Authored-By: DeepSeek V4.1 Flash Co-Authored-By: Claude Sonnet 5.5 --- .../core/src/spatial/usage-field/clash.ts | 3 ++ .../spatial/usage-field/findings-more.test.ts | 44 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/packages/core/src/spatial/usage-field/clash.ts b/packages/core/src/spatial/usage-field/clash.ts index 82b2f4dd55..96e6fa02b8 100644 --- a/packages/core/src/spatial/usage-field/clash.ts +++ b/packages/core/src/spatial/usage-field/clash.ts @@ -6,6 +6,7 @@ import { cm, nameOf, quote, unique } from './labels' import { boxesMeet, hosts, + isBed, isBuildingElement, isFoliage, isPiecePrism, @@ -183,6 +184,8 @@ export function clashIssues(nodes: Nodes, shapes: UsageShapes): UsageIssue[] { } } for (const { a, b, depth, area: size, at } of found.values()) { + // a bed head against a window is a design choice, not a finding + if (isBed(nodes[a.nodeId]) && (b.kind === 'sill' || b.kind === 'window-frame')) continue const approximate = a.shape === 'approx' || b.shape === 'approx' const room = roomAt(nodes, level.levelId, at) const who = quote(nameOf(nodes, a.nodeId)) diff --git a/packages/core/src/spatial/usage-field/findings-more.test.ts b/packages/core/src/spatial/usage-field/findings-more.test.ts index 2576e9f531..bd3d661e0d 100644 --- a/packages/core/src/spatial/usage-field/findings-more.test.ts +++ b/packages/core/src/spatial/usage-field/findings-more.test.ts @@ -182,6 +182,50 @@ describe('usage_clash', () => { ) }) + /** A bedroom whose south window carries a sill 0.3 m deep: its front is at z = 0.35. */ + const silled = (extra: AnyNode[]) => + scene(1, [ + slab('slab_1', 'level_1', [ + [-0.3, -0.3], + [4.3, -0.3], + [4.3, 4.3], + [-0.3, 4.3], + ]), + wall('wall_s', [0, 0], [4, 0], ['window_1']), + wall('wall_e', [4, 0], [4, 4]), + wall('wall_n', [4, 4], [0, 4]), + wall('wall_w', [0, 4], [0, 0]), + WindowNode.parse({ + id: 'window_1', + parentId: 'wall_s', + wallId: 'wall_s', + position: [2, 1.5, 0], + width: 1.6, + height: 1.2, + name: 'South window', + sillDepth: 0.3, + sillThickness: 0.05, + }), + zone('zone_1', 'Bedroom', room(4, 4)), + ...extra, + ]) + + test('a bed 10 cm into a window sill is nothing, a sofa stays a clash and a bed into a wall stays one', () => { + // z = 0.55 is 10 cm into the sill (0.05 to 0.35) and clear of the wall face + const sillBed = piece('item_b', 'Bed', 'bed', 2, 0.55, 1.6, 0.6, 1.2) + expect(run(silled([sillBed]), 'usage_clash')).toHaveLength(0) + const sillSofa = piece('item_s', 'Sofa', 'sofa', 2, 0.55, 1.6, 0.6, 1.3) + expect(run(silled([sillSofa]), 'usage_clash')).toContainEqual( + expect.objectContaining({ severity: 'warning' }), + ) + const wallBed = piece('item_w', 'Bed', 'bed', 0.25, 2, 1.6, 2.1, 0.5, { + rotation: [0, Math.PI / 2, 0], + }) + expect(run(silled([wallBed]), 'usage_clash')).toContainEqual( + expect.objectContaining({ severity: 'warning', valueM: 0.1 }), + ) + }) + test('two pieces: an overlap is a clash, a piece resting on another, a rug under a table, and foliage are not', () => { const sofa = piece('item_a', 'Sofa', 'sofa', 2, 2, 2, 0.9, 0.8) const chair = piece('item_b', 'Armchair', 'armchair', 2.9, 2, 0.9, 0.9, 0.8) From 67afcffe0e9f000f43b5e6ae121b26b5b189cbee Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 19:46:56 +0100 Subject: [PATCH 34/40] Move the wall-object check out: usage_wall_object_protrudes and its probation list The check was already withheld from every report (most findings were towel rails and robe fit-outs, which stand out from the wall by design) and nothing outside the usage checks referenced it. Its code, its tests, the probation list and the three code-table rows only it read leave; the code stays on rd/editor-later-20261103 and comes back with an improvement. withoutDuplicatePockets, the other half of scene-check-policy.ts, stays. Co-Authored-By: Claude Sonnet 5.5 --- .../scene-check-policy.test.ts | 136 ----------- .../agent-operations/scene-check-policy.ts | 17 -- .../core/src/agent-operations/verify-scene.ts | 4 +- packages/core/src/building/code-profile.ts | 21 -- packages/core/src/schema/geometry-source.ts | 2 +- .../core/src/spatial/usage-field/findings.ts | 18 -- .../spatial/usage-field/protrusion.test.ts | 191 --------------- .../src/spatial/usage-field/protrusion.ts | 223 ------------------ .../core/src/spatial/usage-field/types.ts | 2 +- 9 files changed, 4 insertions(+), 610 deletions(-) delete mode 100644 packages/core/src/agent-operations/scene-check-policy.test.ts delete mode 100644 packages/core/src/spatial/usage-field/protrusion.test.ts delete mode 100644 packages/core/src/spatial/usage-field/protrusion.ts diff --git a/packages/core/src/agent-operations/scene-check-policy.test.ts b/packages/core/src/agent-operations/scene-check-policy.test.ts deleted file mode 100644 index edf2f37524..0000000000 --- a/packages/core/src/agent-operations/scene-check-policy.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { - type AnyNode, - BuildingNode, - ItemNode, - LevelNode, - SlabNode, - WallNode, - ZoneNode, -} from '../schema' -import { usageIssues } from '../spatial/usage-field/findings' -import { setSdfChecks } from '../spatial/usage-field/flag' -import './index' -import { SCENE_CHECK_PROBATION, withoutProbation } from './scene-check-policy' -import type { SceneNodes } from './types' -import { verifyScene } from './verify-scene' - -// A 6 x 4 m kitchen; its south wall is along z = 0, the room on the +z side of it. -function kitchen(extra: AnyNode[], wallChildren: string[] = []): SceneNodes { - const nodes: AnyNode[] = [ - BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), - LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), - SlabNode.parse({ - id: 'slab_1', - parentId: 'level_1', - polygon: [ - [-0.3, -0.3], - [6.3, -0.3], - [6.3, 4.3], - [-0.3, 4.3], - ], - elevation: 0.05, - }), - WallNode.parse({ - id: 'wall_s', - parentId: 'level_1', - start: [0, 0], - end: [6, 0], - thickness: 0.1, - children: wallChildren, - }), - WallNode.parse({ - id: 'wall_e', - parentId: 'level_1', - start: [6, 0], - end: [6, 4], - thickness: 0.1, - }), - WallNode.parse({ - id: 'wall_n', - parentId: 'level_1', - start: [6, 4], - end: [0, 4], - thickness: 0.1, - }), - WallNode.parse({ - id: 'wall_w', - parentId: 'level_1', - start: [0, 4], - end: [0, 0], - thickness: 0.1, - }), - ZoneNode.parse({ - id: 'zone_k', - parentId: 'level_1', - name: 'Kitchen', - polygon: [ - [0.05, 0.05], - [5.95, 0.05], - [5.95, 3.95], - [0.05, 3.95], - ], - }), - ...extra, - ] - return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes -} - -/** A wall-hung piece whose depth stands it out of the face it is on. */ -const hanging = () => - ItemNode.parse({ - id: 'item_hung', - parentId: 'wall_s', - wallId: 'wall_s', - position: [3, 1.4, 0], - side: 'front', - asset: { - id: 'rail', - name: 'Rail', - category: 'bathroom', - thumbnail: '/thumb.webp', - src: '/items/rail/model.glb', - dimensions: [0.85, 0.6, 0.46], - attachTo: 'wall-side', - }, - }) - -const typesOf = (nodes: SceneNodes) => - (verifyScene(nodes, {}, { activeLevelId: 'level_1' }).result as { issues: { type: string }[] }) - .issues - -describe('a finding type on probation', () => { - test('is withheld; the others keep their order', () => { - const issues = [ - { type: 'usage_pocket', message: 'first' }, - { type: 'usage_wall_object_protrudes', message: 'second' }, - { type: 'empty_levels', message: 'third' }, - ] - expect(withoutProbation(issues)).toEqual([issues[0], issues[2]]) - }) - - test('an empty list stays empty', () => { - expect(withoutProbation([])).toEqual([]) - }) - - test('the list names the type and why it is withheld', () => { - expect(Object.keys(SCENE_CHECK_PROBATION)).toEqual(['usage_wall_object_protrudes']) - expect(SCENE_CHECK_PROBATION.usage_wall_object_protrudes).toContain('towel rails') - }) - - test('verify_scene reports none of it while usageIssues still finds it', () => { - const nodes = kitchen([hanging()], ['item_hung']) - expect(usageIssues(nodes).some((issue) => issue.type === 'usage_wall_object_protrudes')).toBe( - true, - ) - setSdfChecks(true) - try { - const withheld = typesOf(nodes).filter( - (issue) => issue.type === 'usage_wall_object_protrudes', - ) - expect(withheld).toEqual([]) - } finally { - setSdfChecks(false) - } - }) -}) diff --git a/packages/core/src/agent-operations/scene-check-policy.ts b/packages/core/src/agent-operations/scene-check-policy.ts index 6e22214769..6bdcc05ba6 100644 --- a/packages/core/src/agent-operations/scene-check-policy.ts +++ b/packages/core/src/agent-operations/scene-check-policy.ts @@ -1,20 +1,3 @@ -/** - * A type withheld from what verify_scene reports while its check keeps emitting it. - * - * `usage_wall_object_protrudes` is on probation: most of its findings were towel rails and robe - * fit-outs, which stand out from the wall by design; it comes back after an improvement, or is - * removed. - */ -export const SCENE_CHECK_PROBATION: Readonly> = { - usage_wall_object_protrudes: - 'most findings were towel rails and robe fit-outs, which stand out from the wall by design', -} - -/** The issues whose type is not on probation, in the order they came. */ -export function withoutProbation(issues: T[]): T[] { - return issues.filter((issue) => !Object.hasOwn(SCENE_CHECK_PROBATION, issue.type)) -} - type PocketFields = { type: string wholeRoom?: boolean diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 984c9ee22d..ccc2787a4a 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -42,7 +42,7 @@ import { pointInPolygon, polygonContainsPolygon, type Vec2 } from './plan-geomet import type { RoomCheckIssue } from './room-checks' import { type RoomFinding, roomFindings } from './room-findings' import { roomIssueScope } from './room-readings' -import { withoutDuplicatePockets, withoutProbation } from './scene-check-policy' +import { withoutDuplicatePockets } from './scene-check-policy' import { EMPTY_SESSION } from './scene-checkpoint' import { sceneIssueGroups } from './scene-issue-groups' import { changesSince, type SceneCheckpoint } from './scene-measure' @@ -809,7 +809,7 @@ export const verifyScene: AgentOperation = ( if (check.order >= CHECKPOINT_ORDER) issues.push(...check.run(settled, input ?? {}, context)) const occupiedStoryCount = levels.filter((level) => level.isOccupiedStory).length - issues.splice(0, issues.length, ...withoutDuplicatePockets(withoutProbation(issues))) + issues.splice(0, issues.length, ...withoutDuplicatePockets(issues)) const issueGroups = sceneIssueGroups(issues, nodes) return { result: { diff --git a/packages/core/src/building/code-profile.ts b/packages/core/src/building/code-profile.ts index 9062fec496..83e2df03c0 100644 --- a/packages/core/src/building/code-profile.ts +++ b/packages/core/src/building/code-profile.ts @@ -308,27 +308,6 @@ export const USAGE_INDICATORS = { cite: "wheelchair turning space, 1.50 m: an espace de manœuvre avec possibilité de demi-tour, Ø 1,50 m (annexe 2), in a bedroom and a salle d'eau, arrêté du 24 décembre 2015 art. 13 (consolidated text in force on 27 October 2026, Légifrance); ADA 304.3 not read", source: 'code text', }, - protrusionLimit: { - value: 0.1, - unit: 'm', - section: 'ADA 307.2, 4 in', - cite: 'nearer than this to the wall, an object is not an obstacle', - source: 'secondary source', - }, - protrusionLowest: { - value: 0.685, - unit: 'm', - section: 'ADA 307.2, 27 in', - cite: 'what a cane finds: a wall object whose lower edge is at or above this', - source: 'secondary source', - }, - protrusionHighest: { - value: 2.03, - unit: 'm', - section: 'ADA 307.2, 80 in', - cite: 'what a cane finds: a wall object whose lower edge is at or below this', - source: 'secondary source', - }, } as const satisfies Record export type IrcThresholdId = keyof typeof IRC_2021 diff --git a/packages/core/src/schema/geometry-source.ts b/packages/core/src/schema/geometry-source.ts index 02346b15e5..228784ea58 100644 --- a/packages/core/src/schema/geometry-source.ts +++ b/packages/core/src/schema/geometry-source.ts @@ -65,7 +65,7 @@ const planRing = z.array(planPoint).min(3) /** * What a build occupies in plan, height band by height band, for the usage checks (passages, - * pockets, wall protrusions): `y0`..`y1` in the artifact's frame and the plan outlines (x, z) of + * pockets, clashes): `y0`..`y1` in the artifact's frame and the plan outlines (x, z) of * everything it has in that band, traced from a conservative raster of its meshes, so an outline * is never inside the build and at most `tolerance` metres outside it. Written by the compiler * only when usage checks are on, so it is absent from older artifacts. diff --git a/packages/core/src/spatial/usage-field/findings.ts b/packages/core/src/spatial/usage-field/findings.ts index 5a85db3bbf..ded10c145e 100644 --- a/packages/core/src/spatial/usage-field/findings.ts +++ b/packages/core/src/spatial/usage-field/findings.ts @@ -18,7 +18,6 @@ import { type Passage, type RoomMeasure, } from './measure' -import { PROTRUSION_LIMIT_M, type Protrusion, wallProtrusions } from './protrusion' import { usageShapes } from './shapes' import { doorSwingIssues } from './swings' import type { Nodes } from './walls' @@ -50,7 +49,6 @@ export type UsageIssue = { | 'usage_passage_narrow' | 'usage_turning_narrow' | 'usage_pocket' - | 'usage_wall_object_protrudes' | 'usage_clash' | 'usage_opening_blocked' | 'usage_door_swing' @@ -299,20 +297,6 @@ function pocketIssue(nodes: Nodes, room: RoomMeasure, from: string): UsageIssue } } -function protrusionIssue(nodes: Nodes, found: Protrusion): UsageIssue { - return { - type: 'usage_wall_object_protrudes', - message: `${quote(nameOf(nodes, found.nodeId))} protrudes ${m(found.depth)} m from the wall at ${m(found.bottom)} m above a free floor in ${quote(found.roomName)} (over ${m(PROTRUSION_LIMIT_M)} m).`, - severity: 'warning', - nodeIds: [found.nodeId, found.wallId], - valueM: found.depth, - thresholdM: PROTRUSION_LIMIT_M, - place: { room: found.roomName, roomId: found.roomId, at: found.at }, - obstacles: [], - approximate: found.approximate, - } -} - /** * The usage findings of a scene: narrow passages (measured from the chosen entrance, one for each * place that is narrow with the rooms it leads to, and the best other door as a fact), missing turning circles, floor a 0.60 m unit cannot get out of, wall @@ -359,8 +343,6 @@ export function usageIssues(nodes: Nodes, options: MeasureOptions = {}): UsageIs } } } - for (const found of wallProtrusions(nodes, shapes)) - if (found.depth > PROTRUSION_LIMIT_M + TOLERANCE_M) issues.push(protrusionIssue(nodes, found)) issues.push( ...clashIssues(nodes, shapes), ...blockedOpeningIssues(nodes, shapes), diff --git a/packages/core/src/spatial/usage-field/protrusion.test.ts b/packages/core/src/spatial/usage-field/protrusion.test.ts deleted file mode 100644 index 8e97a63f62..0000000000 --- a/packages/core/src/spatial/usage-field/protrusion.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { - type AnyNode, - BuildingNode, - CabinetModuleNode, - CabinetNode, - ItemNode, - LevelNode, - SlabNode, - WallNode, - ZoneNode, -} from '../../schema' -import { usageIssues } from './findings' -import { wallProtrusions } from './protrusion' -import { usageShapes } from './shapes' -import type { Nodes } from './walls' - -const asset = (over: Record = {}) => ({ - id: 'thing', - name: 'Thing', - category: 'kitchen', - thumbnail: '/thumb.webp', - src: '/items/thing/model.glb', - dimensions: [0.85, 0.6, 0.46], - ...over, -}) - -// A 6 x 4 m kitchen; its south wall is along z = 0, the room on the +z side of it. -function kitchen(extra: AnyNode[], wallChildren: string[] = []): Nodes { - const nodes: AnyNode[] = [ - BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), - LevelNode.parse({ id: 'level_1', parentId: 'building_1', level: 0, children: [] }), - SlabNode.parse({ - id: 'slab_1', - parentId: 'level_1', - polygon: [ - [-0.3, -0.3], - [6.3, -0.3], - [6.3, 4.3], - [-0.3, 4.3], - ], - elevation: 0.05, - }), - WallNode.parse({ - id: 'wall_s', - parentId: 'level_1', - start: [0, 0], - end: [6, 0], - thickness: 0.1, - children: wallChildren, - }), - WallNode.parse({ - id: 'wall_e', - parentId: 'level_1', - start: [6, 0], - end: [6, 4], - thickness: 0.1, - }), - WallNode.parse({ - id: 'wall_n', - parentId: 'level_1', - start: [6, 4], - end: [0, 4], - thickness: 0.1, - }), - WallNode.parse({ - id: 'wall_w', - parentId: 'level_1', - start: [0, 4], - end: [0, 0], - thickness: 0.1, - }), - ZoneNode.parse({ - id: 'zone_k', - parentId: 'level_1', - name: 'Kitchen', - polygon: [ - [0.05, 0.05], - [5.95, 0.05], - [5.95, 3.95], - [0.05, 3.95], - ], - }), - ...extra, - ] - return Object.fromEntries(nodes.map((node) => [node.id, node])) as Nodes -} - -const found = (nodes: Nodes) => wallProtrusions(nodes, usageShapes(nodes)) - -describe('wall objects that stand out', () => { - test('a hung item stands out of the face it is on, from the face, by its depth', () => { - const screen = ItemNode.parse({ - id: 'item_1', - parentId: 'wall_s', - wallId: 'wall_s', - position: [3, 1.4, 0], - side: 'front', - asset: asset({ attachTo: 'wall-side' }), - }) - const [p] = found(kitchen([screen], ['item_1'])) - expect(p!.nodeId).toBe('item_1') - expect(p!.face).toBe('a') - // the library box is centred on its position: half of its 0.46 m is out of the 0.05 face - expect(p!.depth).toBeCloseTo(0.23 + 0, 1) - expect(p!.bottom).toBeCloseTo(1.4 - 0.0, 1) - expect(p!.roomName).toBe('Kitchen') - expect(usageIssues(kitchen([screen], ['item_1']))).toContainEqual( - expect.objectContaining({ - type: 'usage_wall_object_protrudes', - severity: 'warning', - approximate: true, - }), - ) - }) - - test('a wall cabinet run set off its wall protrudes from the face, not from its own back', () => { - const run = CabinetNode.parse({ - id: 'cabinet_1', - parentId: 'level_1', - position: [3, 1.4, 0.3], - runTier: 'wall', - children: ['cabinet-module_1'], - }) - const module = CabinetModuleNode.parse({ - id: 'cabinet-module_1', - parentId: run.id, - position: [0, 0, 0], - width: 0.85, - depth: 0.32, - }) - const [p] = found(kitchen([run, module])) - // its back is at 0.14 (0.09 off the 0.05 face) and its front at 0.46: 0.41 from the face - expect(p!.depth).toBeCloseTo(0.41, 3) - expect(p!.bottom).toBeCloseTo(1.4, 3) - expect(p!.approximate).toBe(true) - }) - - test('a base cabinet, whose lower edge is the floor, is not a hazard', () => { - const run = CabinetNode.parse({ - id: 'cabinet_1', - parentId: 'level_1', - position: [3, 0, 0.3], - children: ['cabinet-module_1'], - }) - const module = CabinetModuleNode.parse({ - id: 'cabinet-module_1', - parentId: run.id, - position: [0, 0, 0], - width: 0.85, - depth: 0.6, - }) - expect(found(kitchen([run, module]))).toHaveLength(0) - }) - - test('an object that stands out by less than 10 cm is not', () => { - const frame = ItemNode.parse({ - id: 'item_1', - parentId: 'wall_s', - wallId: 'wall_s', - position: [3, 1.4, 0], - side: 'front', - asset: asset({ attachTo: 'wall-side', dimensions: [0.6, 0.4, 0.04] }), - }) - expect(found(kitchen([frame], ['item_1']))).toHaveLength(0) - }) - - test('over furniture it is not in the way of anyone walking', () => { - const run = CabinetNode.parse({ - id: 'cabinet_1', - parentId: 'level_1', - position: [3, 1.4, 0.3], - runTier: 'wall', - children: ['cabinet-module_1'], - }) - const module = CabinetModuleNode.parse({ - id: 'cabinet-module_1', - parentId: run.id, - position: [0, 0, 0], - width: 0.85, - depth: 0.32, - }) - const counter = ItemNode.parse({ - id: 'item_2', - parentId: 'level_1', - position: [3, 0, 0.45], - asset: asset({ src: '/items/counter/model.glb', dimensions: [1.2, 0.9, 0.7] }), - }) - expect(found(kitchen([run, module, counter]))).toHaveLength(0) - }) -}) diff --git a/packages/core/src/spatial/usage-field/protrusion.ts b/packages/core/src/spatial/usage-field/protrusion.ts deleted file mode 100644 index 7b380a4a09..0000000000 --- a/packages/core/src/spatial/usage-field/protrusion.ts +++ /dev/null @@ -1,223 +0,0 @@ -import { floorsOf } from '../../agent-operations/circulation-spaces' -import { USAGE_INDICATORS } from '../../building/code-profile' -import type { WallNode } from '../../schema' -import { isCurvedWall } from '../../systems/wall/wall-curve' -import { getWallFaceLine } from '../../systems/wall/wall-frame' -import { type FloorGroup, floorGroups, inRegion } from './level-field' -import { obstacleOf, signedDistance } from './obstacles' -import type { Prism, PrismKind, UsageShapes } from './types' -import type { Nodes } from './walls' - -/** What a cane finds: a wall object whose lower edge is between 27 in and 80 in (ADA 307.2). */ -export const PROTRUSION_LOWER_EDGE_M = [ - USAGE_INDICATORS.protrusionLowest.value, - USAGE_INDICATORS.protrusionHighest.value, -] as const -/** 4 in (ADA 307.2): nearer than this to the wall, an object is not an obstacle. */ -export const PROTRUSION_LIMIT_M = USAGE_INDICATORS.protrusionLimit.value -const OBJECT_KINDS: PrismKind[] = ['item', 'cabinet', 'shelf'] -/** An object is "on" a wall if its back is this close to the face (it may stand off, or sink a little in). */ -const BACK_REACH = { standOff: 0.15, sunk: 0.12 } - -export type Protrusion = { - nodeId: string - wallId: string - face: 'a' | 'b' - /** How far the object stands out of the wall face, at most. */ - depth: number - /** Height of the lower edge of the part that protrudes, above the floor. */ - bottom: number - roomId: string - roomName: string - at: [number, number] - approximate: boolean -} - -type Face = { - wall: WallNode - face: 'a' | 'b' - ox: number - oz: number - nx: number - nz: number - tx: number - tz: number - length: number -} - -function faces(nodes: Nodes, levelId: string): Face[] { - const out: Face[] = [] - for (const node of Object.values(nodes)) { - if ( - node.type !== 'wall' || - node.parentId !== levelId || - node.visible === false || - isCurvedWall(node) - ) - continue - const dx = node.end[0] - node.start[0] - const dz = node.end[1] - node.start[1] - const length = Math.hypot(dx, dz) - if (length < 1e-6) continue - for (const face of ['a', 'b'] as const) { - const line = getWallFaceLine(node, face) - const nx = (face === 'a' ? -dz : dz) / length - const nz = (face === 'a' ? dx : -dx) / length - out.push({ - wall: node, - face, - ox: line.start.x, - oz: line.start.y, - nx, - nz, - tx: dx / length, - tz: dz / length, - length, - }) - } - } - return out -} - -/** Signed distance of a plan point beyond a wall face, outward (the room side) positive. */ -const beyond = (f: Face, x: number, z: number) => (x - f.ox) * f.nx + (z - f.oz) * f.nz -const along = (f: Face, x: number, z: number) => (x - f.ox) * f.tx + (z - f.oz) * f.tz - -/** - * Wall objects (hung cabinets, mounted shelves and screens) that stand out of a wall face by more - * than 0.10 m with their lower edge at the height a cane does not find, over a free floor in a room. - * An object is on a wall when it is hosted by it or its back is within reach of its face; the depth - * is measured from the face, whatever the object's own frame says. - */ -export function wallProtrusions(nodes: Nodes, shapes: UsageShapes): Protrusion[] { - const out: Protrusion[] = [] - const groups = floorGroups(shapes) - const zones = floorsOf(nodes).floors - const allPrisms = shapes.levels.flatMap((level) => level.prisms) - for (const level of shapes.levels) { - const levelGroups = groups.filter((g) => g.levelId === level.levelId) - if (levelGroups.length === 0) continue - const levelFaces = faces(nodes, level.levelId) - const byNode = new Map() - // wall objects only: what a wall hosts, and a run of wall cabinets; a table on legs is not one - const onWall = (prism: Prism) => { - if (!OBJECT_KINDS.includes(prism.kind)) return false - const node = nodes[prism.nodeId] - return !!prism.host || (node?.type === 'cabinet' && node.runTier === 'wall') - } - for (const prism of level.prisms) - if (onWall(prism)) byNode.set(prism.nodeId, [...(byNode.get(prism.nodeId) ?? []), prism]) - for (const [nodeId, prisms] of byNode) { - // the face it is on: the hosted one, else the face its back is nearest - let best: { face: Face; back: number } | null = null - for (const f of levelFaces) { - if ( - prisms.some((p) => p.host) && - !prisms.some((p) => p.host?.wallId === f.wall.id && p.host.face === f.face) - ) - continue - let back = Number.POSITIVE_INFINITY - let u0 = Number.POSITIVE_INFINITY - let u1 = Number.NEGATIVE_INFINITY - for (const p of prisms) - for (const [x, z] of p.outer) { - back = Math.min(back, beyond(f, x, z)) - u0 = Math.min(u0, along(f, x, z)) - u1 = Math.max(u1, along(f, x, z)) - } - const hosted = prisms.some((p) => p.host) - if (!hosted && (back < -BACK_REACH.sunk || back > BACK_REACH.standOff)) continue - if (Math.min(u1, f.length) - Math.max(u0, 0) < 0.1) continue - if (!best || Math.abs(back) < Math.abs(best.back)) best = { face: f, back } - } - if (!best) continue - const f = best.face - // each piece of the object (a module, a band) is judged where it stands: a hung cabinet run is - // over a counter at one end and over open floor at the other - let lowestBottom = Number.POSITIVE_INFINITY - let found: { - depth: number - at: [number, number] - roomId: string - roomName: string - } | null = null - for (const p of prisms) { - let reach = 0 - const out: [number, number][] = [] - for (const [x, z] of p.outer) { - const d = beyond(f, x, z) - reach = Math.max(reach, d) - if (d > PROTRUSION_LIMIT_M) out.push([x, z]) - } - if (reach <= PROTRUSION_LIMIT_M || out.length === 0) continue - const cx = out.reduce((sum, q) => sum + q[0], 0) / out.length - const cz = out.reduce((sum, q) => sum + q[1], 0) / out.length - const group = pick(levelGroups, cx, cz) - if (!group) continue - // the lower edge is the lowest the object goes over that spot: a bed's headboard stands on its frame - const lowest = Math.min(...prisms.filter((q) => pointIn(q, cx, cz)).map((q) => q.z0), p.z0) - const bottom = lowest - group.y - if (!(bottom >= PROTRUSION_LOWER_EDGE_M[0] - 1e-9 && bottom < PROTRUSION_LOWER_EDGE_M[1])) - continue - const room = zones - .find((floor) => floor.id === level.levelId) - ?.zones.find( - (zone) => !zone.outdoor && inRegion(cx, cz, { outer: zone.polygon, holes: zone.holes }), - ) - if (!room || overFurniture(allPrisms, nodeId, f.wall.id, group.y, lowest, cx, cz)) continue - lowestBottom = Math.min(lowestBottom, bottom) - if (!found || reach > found.depth) - found = { - depth: reach, - at: [cx, cz], - roomId: room.id, - roomName: String(nodes[room.id]?.name ?? room.id), - } - } - if (!found) continue - out.push({ - nodeId, - wallId: f.wall.id, - face: f.face, - depth: Math.round(found.depth * 1000) / 1000, - bottom: Math.round(lowestBottom * 1000) / 1000, - roomId: found.roomId, - roomName: found.roomName, - at: [Math.round(found.at[0] * 1000) / 1000, Math.round(found.at[1] * 1000) / 1000], - approximate: prisms.some((p) => p.shape === 'approx'), - }) - } - } - return out -} - -const pick = (groups: FloorGroup[], x: number, z: number): FloorGroup | undefined => - groups.find((g) => g.regions.some((region) => inRegion(x, z, region))) ?? groups[0] - -const pointIn = (p: Prism, x: number, z: number) => signedDistance(obstacleOf(p, 0).edges, x, z) < 0 - -const FURNITURE: PrismKind[] = ['item', 'cabinet', 'shelf', 'column', 'other'] - -/** - * Whether a piece of furniture stands under the point, below the object's lower edge: then the - * object is over it and nobody walks there. One point, the middle of the protruding part. - */ -function overFurniture( - all: Prism[], - nodeId: string, - wallId: string, - floor: number, - lower: number, - x: number, - z: number, -): boolean { - return all.some( - (p) => - FURNITURE.includes(p.kind) && - p.nodeId !== nodeId && - p.nodeId !== wallId && - p.z1 > floor + 0.03 && - p.z0 < lower - 0.01 && - signedDistance(obstacleOf(p, 0).edges, x, z) < 0, - ) -} diff --git a/packages/core/src/spatial/usage-field/types.ts b/packages/core/src/spatial/usage-field/types.ts index 442eebc69a..e2f150177c 100644 --- a/packages/core/src/spatial/usage-field/types.ts +++ b/packages/core/src/spatial/usage-field/types.ts @@ -45,7 +45,7 @@ export type Prism = { shape: 'exact' | 'approx' /** What made it approximate, for the finding's wording. */ why?: string - /** Set for what is mounted on a wall, which the protrusion check measures from the wall's face. */ + /** Set for what is mounted on a wall: the clash and opening-blocked checks leave it out against its own host. */ host?: { wallId: string; face: 'a' | 'b' } } From bfe2a5026337fd9dbadfba52e04e22204aed6e4b Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 19:49:00 +0100 Subject: [PATCH 35/40] Move the two wall-face checks out: walls_outside_finish_inside and room_wall_item_wrong_face Neither was raised in any stored run (43 projects). The checks, their tests and the helper only the first one used (finishWords) leave, with their two entries in ROOM_CHECK_CODES and their mention in verify_scene's description. The code stays on rd/editor-later-20261103. Co-Authored-By: Claude Sonnet 5.5 --- .../core/src/agent-operations/room-checks.ts | 32 ---- .../agent-operations/room-finishes.test.ts | 21 +-- .../src/agent-operations/room-finishes.ts | 7 - .../agent-operations/wall-item-faces.test.ts | 155 ------------------ .../src/agent-operations/wall-item-faces.ts | 73 --------- .../wall-outside-finish.test.ts | 136 --------------- .../agent-operations/wall-outside-finish.ts | 137 ---------------- packages/core/src/agent-tools/verify-scene.ts | 2 +- 8 files changed, 2 insertions(+), 561 deletions(-) delete mode 100644 packages/core/src/agent-operations/wall-item-faces.test.ts delete mode 100644 packages/core/src/agent-operations/wall-item-faces.ts delete mode 100644 packages/core/src/agent-operations/wall-outside-finish.test.ts delete mode 100644 packages/core/src/agent-operations/wall-outside-finish.ts diff --git a/packages/core/src/agent-operations/room-checks.ts b/packages/core/src/agent-operations/room-checks.ts index 77151fa967..03cac9c007 100644 --- a/packages/core/src/agent-operations/room-checks.ts +++ b/packages/core/src/agent-operations/room-checks.ts @@ -1,13 +1,10 @@ import { isSkirtedRoomUse, isWetRoomUse } from '../building/room-use' import type { SceneMaterial } from '../schema' -import { finishWords } from './room-finishes' import { type RoomReading, readRooms } from './room-readings' import { WET_TILED_TO_M } from './room-wet' import type { SceneNodes } from './types' import { registerSceneCheck } from './verify-scene' import { type DefaultWallFace, readWallFaces, type WallFaceReading } from './wall-face-defaults' -import { wallItemFaceIssues } from './wall-item-faces' -import { outsideFinishInside } from './wall-outside-finish' /** * What the rooms of a scene owe, checked at the end of a turn: a wet room with no tile, rooms with no @@ -25,8 +22,6 @@ export const ROOM_CHECK_CODES = [ 'wall_faces_default', 'rooms_floors_default', 'room_no_floor', - 'walls_outside_finish_inside', - 'room_wall_item_wrong_face', ] as const export type RoomCheckCode = (typeof ROOM_CHECK_CODES)[number] @@ -238,31 +233,6 @@ export function wallFaceDefaultIssue( } } -/** - * The finish of an outside face on the inside face of the same wall: the walls whose two faces show - * one finish, indoor rooms on one face and none on the other, where no partition of the scene shows - * that finish. One finding per finish, with the walls' total length and the rooms that look at them. - */ -export function outsideFinishInsideIssues( - nodes: SceneNodes, - materials?: Readonly>, -): RoomCheckIssue[] { - return outsideFinishInside(nodes, materials).map(({ finish, walls, partitions }) => { - const rooms = [...new Set(walls.flatMap((wall) => wall.rooms))] - const metres = walls.reduce((sum, wall) => sum + wall.lengthM, 0) - return { - type: 'walls_outside_finish_inside', - message: `${finishWords(finish)} shows on both faces of ${plural(walls.length, 'wall')} (${metres.toFixed(1)} m): the outside face and the inside face, which looks into ${listed(rooms)}${ - partitions.length - ? `; the partitions of the scene show ${partitions.map((other) => other.name).join(' and ')}` - : '' - }.`, - severity: 'warning', - nodeIds: walls.map((wall) => wall.id), - } - }) -} - /** Every room check on a scene. */ export function roomCheckIssues( nodes: SceneNodes, @@ -285,8 +255,6 @@ export function roomCheckIssues( ...(noFloor ? [noFloor] : []), ...(wallFaces ? [wallFaces] : []), ...(floors ? [floors] : []), - ...outsideFinishInsideIssues(nodes, options.materials), - ...wallItemFaceIssues(nodes), ] } diff --git a/packages/core/src/agent-operations/room-finishes.test.ts b/packages/core/src/agent-operations/room-finishes.test.ts index 941bfcc94b..24c6dc6f1e 100644 --- a/packages/core/src/agent-operations/room-finishes.test.ts +++ b/packages/core/src/agent-operations/room-finishes.test.ts @@ -1,13 +1,7 @@ import { describe, expect, test } from 'bun:test' import type { AnyNode, SceneMaterial, ZoneNode } from '../schema' import { paintedKitchenScene } from './__fixtures__/room-cases' -import { - changedFinishes, - describeFinish, - finishWords, - levelFinishes, - roomFinishes, -} from './room-finishes' +import { changedFinishes, describeFinish, levelFinishes, roomFinishes } from './room-finishes' import { nodesOnLevel } from './scene-queries' const scene = () => paintedKitchenScene().nodes as Record @@ -82,19 +76,6 @@ describe('describeFinish', () => { }) }) -describe('finishWords', () => { - test('a name, then the ref and colour it has', () => { - expect(finishWords(describeFinish('library:preset-softwhite'))).toBe( - 'Soft White (library:preset-softwhite, #ebe7df)', - ) - expect(finishWords(describeFinish('library:wood-floorplank1'))).toBe( - 'Floor Plank 1 (library:wood-floorplank1, #bf8552)', - ) - expect(finishWords(describeFinish(undefined))).toBe('default') - expect(finishWords(describeFinish('wood'))).toBe('wood') - }) -}) - describe('roomFinishes', () => { test('a room with no floor reads none, and one with no ceiling reads none', () => { const nodes = scene() diff --git a/packages/core/src/agent-operations/room-finishes.ts b/packages/core/src/agent-operations/room-finishes.ts index c682b9fcd0..54d0fb9c8d 100644 --- a/packages/core/src/agent-operations/room-finishes.ts +++ b/packages/core/src/agent-operations/room-finishes.ts @@ -88,13 +88,6 @@ export function describeFinish(finish: Finish, materials?: Materials): FinishFac return { ref: finish, name: finish } } -/** A finish in a phrase: its name, then its ref and colour where it has them. */ -export function finishWords(fact: FinishFact): string { - const facts = [fact.ref && fact.ref !== fact.name ? fact.ref : undefined, fact.color] - const rest = facts.filter(Boolean).join(', ') - return rest ? `${fact.name} (${rest})` : fact.name -} - /** One finish's identity, so rooms painted alike group together. */ const keyOf = (fact: FinishFact) => fact.ref ?? (fact.name === DEFAULT_FINISH.name ? 'default' : `inline:${fact.color ?? ''}`) diff --git a/packages/core/src/agent-operations/wall-item-faces.test.ts b/packages/core/src/agent-operations/wall-item-faces.test.ts deleted file mode 100644 index 27aca413db..0000000000 --- a/packages/core/src/agent-operations/wall-item-faces.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { BuildingNode, ItemNode, LevelNode, WallNode, ZoneNode } from '../schema' -import { roomCheckIssues } from './room-checks' -import type { SceneNodes } from './types' -import { wallItemFaceIssues } from './wall-item-faces' - -/** - * Bed 3 (z 0 to 3) and the Garage (z 3 to 6) share a wall on z = 3 that runs along +x: its face `a` - * (the item's `front`) looks into the Garage, its face `b` (`back`) into Bed 3. The south wall, on z = 0, - * has Bed 3 on its face `a` and the outside on its face `b`. Linen is a room elsewhere. - */ -const scene = (items: Record[]): SceneNodes => { - const asset = (name: string) => ({ - id: name, - name, - category: 'art', - thumbnail: '/t.webp', - src: 'asset://art', - dimensions: [0.6, 0.8, 0.03], - attachTo: 'wall-side', - }) - const hosted = items.map((item, index) => - ItemNode.parse({ - id: `item_${index}`, - parentId: item.wall ?? 'wall_mid', - wallId: item.wall ?? 'wall_mid', - position: [2, 1.5, 0], - side: item.side, - name: item.name, - metadata: item.metadata ?? {}, - asset: asset(String(item.name)), - }), - ) - const walls = [ - WallNode.parse({ - id: 'wall_mid', - parentId: 'level_1', - name: 'Party wall', - start: [0, 3], - end: [4, 3], - children: hosted.filter((h) => h.parentId === 'wall_mid').map((h) => h.id), - }), - WallNode.parse({ - id: 'wall_south', - parentId: 'level_1', - name: 'South wall', - start: [0, 0], - end: [4, 0], - children: hosted.filter((h) => h.parentId === 'wall_south').map((h) => h.id), - }), - ] - const zone = (id: string, name: string, polygon: [number, number][], walls: string[]) => - ZoneNode.parse({ - id, - parentId: 'level_1', - name, - polygon, - spaceRole: 'room', - boundaryWallIds: walls, - }) - const nodes = [ - BuildingNode.parse({ id: 'building_1', children: ['level_1'] }), - LevelNode.parse({ - id: 'level_1', - parentId: 'building_1', - level: 0, - children: ['wall_mid', 'wall_south', 'zone_bed', 'zone_garage', 'zone_linen'], - }), - ...walls, - zone( - 'zone_bed', - 'Bed 3', - [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - ['wall_mid', 'wall_south'], - ), - zone( - 'zone_garage', - 'Garage', - [ - [0, 3], - [4, 3], - [4, 6], - [0, 6], - ], - ['wall_mid'], - ), - zone( - 'zone_linen', - 'Linen', - [ - [6, 0], - [8, 0], - [8, 2], - [6, 2], - ], - [], - ), - ...hosted, - ] - return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes -} - -const found = (items: Record[]) => wallItemFaceIssues(scene(items)) - -describe('a piece hung on the face that looks into another room than the one it names', () => { - test('an art print named for Bed 3 on the face that looks into the Garage is a warning that names the item, the face and both rooms', () => { - const [issue] = found([{ name: 'Hot-air balloon art print (Bed 3)', side: 'front' }]) - expect(issue).toMatchObject({ type: 'room_wall_item_wrong_face', severity: 'warning' }) - expect(issue!.message).toBe( - '“Hot-air balloon art print (Bed 3)” hangs on the front face of “Party wall”, which looks into “Garage”, but it names “Bed 3”, the room on the other face.', - ) - expect(issue!.nodeIds).toEqual(['item_0', 'wall_mid', 'zone_garage', 'zone_bed']) - }) - - test('the same print on the other face, or one that names no room, says nothing', () => { - expect(found([{ name: 'Hot-air balloon art print (Bed 3)', side: 'back' }])).toHaveLength(0) - expect(found([{ name: 'Hot-air balloon art print', side: 'front' }])).toHaveLength(0) - }) - - test('the reason it was placed names the room as the name does', () => { - expect( - found([ - { name: 'Mirror', side: 'front', metadata: { reason: 'Mirror over the dresser in Bed 3' } }, - ]), - ).toHaveLength(1) - }) - - test('a word that is also a room elsewhere is no claim: linen curtains are not for the Linen room', () => { - expect(found([{ name: 'Sheer linen curtains', side: 'front' }])).toHaveLength(0) - }) - - test('cladding named for a room is the facade of its wall, whichever face it is on', () => { - expect(found([{ name: 'Bed 3 — vertical cedar cladding', side: 'front' }])).toHaveLength(0) - }) - - test('a curtain named for Bed 3 on the face of the south wall that looks outside is a warning that says outside', () => { - const [issue] = found([{ name: 'Bed 3 curtains', side: 'back', wall: 'wall_south' }]) - expect(issue!.message).toBe( - '“Bed 3 curtains” hangs on the back face of “South wall”, which looks into the outside, but it names “Bed 3”, the room on the other face.', - ) - expect(found([{ name: 'Bed 3 curtains', side: 'front', wall: 'wall_south' }])).toHaveLength(0) - }) - - test('it is one of the room checks', () => { - const types = roomCheckIssues(scene([{ name: 'Art print (Bed 3)', side: 'front' }])).map( - (issue) => issue.type, - ) - expect(types).toContain('room_wall_item_wrong_face') - }) -}) diff --git a/packages/core/src/agent-operations/wall-item-faces.ts b/packages/core/src/agent-operations/wall-item-faces.ts deleted file mode 100644 index 510497c343..0000000000 --- a/packages/core/src/agent-operations/wall-item-faces.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { resolveLevelId } from '../lib/node-ancestry' -import type { ItemNode, WallNode, ZoneNode } from '../schema' -import { isBuildingElementItem } from '../spatial/usage-field/pieces' -import { getWallZoneSpans } from '../systems/wall/wall-finish' -import type { RoomCheckIssue } from './room-checks' -import { queryNodes } from './scene-queries' -import type { SceneNodes } from './types' - -const quote = (name: string) => `“${name}”` -const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - -/** The words an item carries that can name its room: its name, its asset, and every text of its metadata (the reason it was placed, the feature it serves). */ -function textOf(item: ItemNode): string { - const metadata = Object.values(item.metadata ?? {}).filter( - (value): value is string => typeof value === 'string', - ) - return [item.name, item.asset?.name, ...metadata].filter(Boolean).join(' | ') -} - -const mentions = (text: string, name: string) => - new RegExp(`(^|[^\\p{L}\\p{N}])${escaped(name.trim())}($|[^\\p{L}\\p{N}])`, 'iu').test(text) - -/** - * A piece hung on a wall (art, a mirror, a shelf, a screen, a curtain) is on one face of it, and a face - * looks into one room, or the outside. When the item's name, asset or the reason it was placed names the - * room on the other face of its wall, and not the one its own face looks into (or the outside), it is on - * the wrong side: the finding names the item, the face, the room that face looks into and the room on - * the other face. An item that names no room on its wall (a "linen" curtain is not for the Linen room, - * a "kitchen" towel hook may hang in the bath), or whose face is not stored (no `side`), makes no claim, nor does a building element (cladding, trim). - */ -export function wallItemFaceIssues(nodes: SceneNodes): RoomCheckIssue[] { - const out: RoomCheckIssue[] = [] - const zonesOf = new Map() - for (const node of queryNodes(nodes, { type: 'zone' })) - if (node.parentId && String(node.name ?? '').trim()) - zonesOf.set(node.parentId, [...(zonesOf.get(node.parentId) ?? []), node]) - for (const node of queryNodes(nodes, { type: 'item' })) { - // cladding, trim and the like are the building's skin: a facade's is meant to face outside whichever room it is named for - if (!node.side || isBuildingElementItem(node)) continue - const wall = node.parentId ? nodes[node.parentId] : undefined - if (wall?.type !== 'wall') continue - const levelId = resolveLevelId(wall as WallNode, nodes as never) - const zones = zonesOf.get(levelId ?? '') ?? [] - const text = textOf(node) - const named = zones.filter((zone) => mentions(text, String(zone.name))) - if (named.length === 0) continue - const length = Math.hypot( - (wall as WallNode).end[0] - (wall as WallNode).start[0], - (wall as WallNode).end[1] - (wall as WallNode).start[1], - ) - if (!(length > 0)) continue - const station = (node.position[0] ?? 0) / length - const spans = getWallZoneSpans(wall as WallNode, zones).filter( - (span) => station >= span.t0 - 1e-6 && station <= span.t1 + 1e-6, - ) - const face = node.side === 'front' ? 'a' : 'b' - const zoneOn = (which: 'a' | 'b') => - zones.find((zone) => spans.some((span) => span.face === which && span.zoneId === zone.id)) - const here = zoneOn(face) - const across = zoneOn(face === 'a' ? 'b' : 'a') - const namedNames = new Set(named.map((zone) => String(zone.name).toLowerCase())) - if (!across || !namedNames.has(String(across.name).toLowerCase())) continue - if (here && namedNames.has(String(here.name).toLowerCase())) continue - const wall0 = wall as WallNode - out.push({ - type: 'room_wall_item_wrong_face', - message: `${quote(String(node.name ?? node.asset.name))} hangs on the ${node.side} face of ${quote(String(wall0.name ?? wall0.id))}, which looks into ${here ? quote(String(here.name)) : 'the outside'}, but it names ${quote(String(across.name))}, the room on the other face.`, - severity: 'warning', - nodeIds: [node.id, wall0.id, ...(here ? [here.id] : []), across.id], - }) - } - return out -} diff --git a/packages/core/src/agent-operations/wall-outside-finish.test.ts b/packages/core/src/agent-operations/wall-outside-finish.test.ts deleted file mode 100644 index ac53526a60..0000000000 --- a/packages/core/src/agent-operations/wall-outside-finish.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { type AnyNode, BuildingNode, LevelNode, SiteNode, WallNode, ZoneNode } from '../schema' -import { roomCheckIssues } from './room-checks' -import type { SceneNodes } from './types' -import { wallInsideFaces } from './wall-outside-finish' - -/** - * The finish of an outside face shown on the inside face of the same wall. Walls here run so that - * face a is on their left: the outer ring runs counter-clockwise, so a is in and b is out; the - * partitions run north, so a looks west. - */ - -const STUCCO = 'library:concrete-stucco' -const WHITE = 'library:preset-white' - -type Room = { name: string; x0: number; x1: number } -type Wall = { id: string; start: [number, number]; end: [number, number]; slots?: object } - -function scene(rooms: Room[], walls: Wall[]): SceneNodes { - const zones = rooms.map(({ name, x0, x1 }, index) => - ZoneNode.parse({ - id: `zone_${index}`, - parentId: 'level_0', - name, - polygon: [ - [x0, 0], - [x1, 0], - [x1, 4], - [x0, 4], - ], - spaceRole: 'room', - // The rooms list the walls the way the structure reconciler writes them; the spans are cut by geometry. - boundaryWallIds: walls.map((wall) => wall.id), - }), - ) - const parsed = walls.map(({ id, start, end, slots }) => - WallNode.parse({ id, parentId: 'level_0', start, end, ...(slots ? { slots } : {}) }), - ) - const nodes: AnyNode[] = [ - SiteNode.parse({ id: 'site_0', children: ['building_0'] }), - BuildingNode.parse({ id: 'building_0', parentId: 'site_0', children: ['level_0'] }), - LevelNode.parse({ - id: 'level_0', - parentId: 'building_0', - level: 0, - children: [...parsed.map((wall) => wall.id), ...zones.map((zone) => zone.id)], - }), - ...parsed, - ...zones, - ] - return Object.fromEntries(nodes.map((node) => [node.id, node])) as SceneNodes -} - -const BOTH = { a: STUCCO, b: STUCCO } -/** A house of two bedrooms, 0..3 and 3..6, a partition between them and four outer walls. */ -const house = (outer: object | undefined, mid: object | undefined, extra: Room[] = []) => - scene( - [{ name: 'Bed 1', x0: 0, x1: 3 }, { name: 'Bed 2', x0: 3, x1: 6 }, ...extra], - [ - { id: 'wall_s', start: [0, 0], end: [6, 0], slots: outer }, - { id: 'wall_e', start: [6, 0], end: [6, 4], slots: outer }, - { id: 'wall_n', start: [6, 4], end: [0, 4], slots: outer }, - { id: 'wall_w', start: [0, 4], end: [0, 0], slots: outer }, - { id: 'wall_mid', start: [3, 0], end: [3, 4], slots: mid }, - ], - ) -const found = (nodes: SceneNodes) => - roomCheckIssues(nodes).filter((issue) => issue.type === 'walls_outside_finish_inside') - -describe('the outside finish on the inside of a wall', () => { - test('both faces of the outer walls in one finish, the partition in another: one finding, the walls and rooms named', () => { - const [issue, ...rest] = found(house(BOTH, { a: WHITE, b: WHITE })) - expect(rest).toEqual([]) - expect(issue?.nodeIds.sort()).toEqual(['wall_e', 'wall_n', 'wall_s', 'wall_w']) - expect(issue?.message).toContain('White Stucco') - expect(issue?.message).toContain('shows on both faces of 4 walls (20.0 m)') - expect(issue?.message).toContain('looks into Bed 1, Bed 2') - expect(issue?.message).toContain('the partitions of the scene show White') - }) - - test('the finish on the outside face alone is the outside finish', () => { - expect(found(house({ b: STUCCO }, { a: WHITE, b: WHITE }))).toEqual([]) - }) - - test('the default on both faces writes nothing, so shows no finish twice', () => { - expect(found(house(undefined, undefined))).toEqual([]) - }) - - test('a finish a partition shows is the house’s inside finish', () => { - expect(found(house(BOTH, BOTH))).toEqual([]) - // Plain white inside and out is the same: white is on the partitions. - const white = { a: WHITE, b: WHITE } - expect(found(house(white, white))).toEqual([]) - }) - - test('with no partition there is nothing inside to tell it from', () => { - const studio = scene( - [{ name: 'Studio', x0: 0, x1: 6 }], - [ - { id: 'wall_s', start: [0, 0], end: [6, 0], slots: BOTH }, - { id: 'wall_e', start: [6, 0], end: [6, 4], slots: BOTH }, - { id: 'wall_n', start: [6, 4], end: [0, 4], slots: BOTH }, - { id: 'wall_w', start: [0, 4], end: [0, 0], slots: BOTH }, - ], - ) - expect(found(studio)).toEqual([]) - }) - - test('a wall toward a porch or an alfresco is an outside wall', () => { - const toPorch = scene( - [ - { name: 'Bed 1', x0: 0, x1: 2 }, - { name: 'Bed 2', x0: 2, x1: 4 }, - { name: 'Porch', x0: 4, x1: 6 }, - ], - [ - { id: 'wall_a', start: [2, 0], end: [2, 4], slots: { a: WHITE, b: WHITE } }, - { id: 'wall_b', start: [4, 0], end: [4, 4], slots: BOTH }, - ], - ) - const [issue] = found(toPorch) - expect(issue?.nodeIds).toEqual(['wall_b']) - expect(issue?.message).toContain('looks into Bed 2') - expect(issue?.message).not.toContain('Porch') - expect(wallInsideFaces(toPorch, toPorch.wall_b as WallNode)).toEqual(['a']) - }) - - test('a partition has rooms on both faces, and a wall no room stands on has none to read', () => { - expect(wallInsideFaces(house(BOTH, BOTH), house(BOTH, BOTH).wall_mid as WallNode)).toEqual([ - 'a', - 'b', - ]) - const lone = scene([], [{ id: 'wall_x', start: [0, 0], end: [4, 0], slots: BOTH }]) - expect(wallInsideFaces(lone, lone.wall_x as WallNode)).toBeNull() - }) -}) diff --git a/packages/core/src/agent-operations/wall-outside-finish.ts b/packages/core/src/agent-operations/wall-outside-finish.ts deleted file mode 100644 index 5b7e9cc2f4..0000000000 --- a/packages/core/src/agent-operations/wall-outside-finish.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { isOutdoorRoom } from '../building/room-use' -import type { SceneMaterial, WallFace, WallNode, ZoneNode } from '../schema' -import { - describeWallFaceFinishes, - getWallLevelZones, - getWallZoneSpans, - type WallFaceStretch, -} from '../systems/wall/wall-finish' -import { describeFinish, type FinishFact } from './room-finishes' -import { queryNodes } from './scene-queries' -import type { SceneNodes } from './types' - -/** - * Which walls show the finish of their outside face on their inside face too. A wall is read as - * outside when indoor rooms stand on half or more of one face and not of the other (a face toward a - * porch, an alfresco or open ground is outside); the finish of a face is the one that shows on at - * least half of its length by a ref somebody wrote (a wall left at the default shows none). The - * finish counts as the house's inside finish, and is left alone, when any partition (rooms on both - * faces) shows it: the walls inside are then dressed in it on purpose. - */ - -export type OutsideFinishInside = { - finish: FinishFact - walls: { id: string; levelId: string; lengthM: number; rooms: string[] }[] - /** The finishes the partitions of the scene show, longest first. */ - partitions: FinishFact[] -} - -type Materials = Readonly> | undefined - -/** The share of a face (0 to 1) that indoor rooms stand on. */ -function indoorShare(spans: readonly { t0: number; t1: number }[]): number { - let reach = 0 - let total = 0 - for (const span of [...spans].sort((p, q) => p.t0 - q.t0)) { - const from = Math.max(span.t0, reach) - if (span.t1 > from) total += span.t1 - from - reach = Math.max(reach, span.t1) - } - return total -} - -const lengthOf = (stretch: WallFaceStretch) => Math.max(0, stretch.u1 - stretch.u0) - -/** What a face shows by a ref somebody wrote, metres per ref; the default and a ref-less inline finish are none. */ -function writtenRefs(stretches: readonly WallFaceStretch[]): Map { - const refs = new Map() - for (const stretch of stretches) { - if (stretch.ref === null || (stretch.source === 'wall_face' && stretch.chain === 'default')) - continue - refs.set(stretch.ref, (refs.get(stretch.ref) ?? 0) + lengthOf(stretch)) - } - return refs -} - -/** The ref shown on at least half of the face's length, or null. */ -function dominantRef(stretches: readonly WallFaceStretch[]): string | null { - const total = stretches.reduce((sum, stretch) => sum + lengthOf(stretch), 0) - const [best] = [...writtenRefs(stretches)].sort((p, q) => q[1] - p[1]) - return best && total > 0 && best[1] >= total / 2 ? best[0] : null -} - -const FACES: readonly WallFace[] = ['a', 'b'] - -/** - * The faces of a wall that indoor rooms stand on for half of their length or more, or null when no - * room of the level stands on the wall at all (nothing to read it by: its stored sides are the - * only word on which way it faces). - */ -export function wallInsideFaces(nodes: SceneNodes, wall: WallNode): WallFace[] | null { - const rooms = getWallLevelZones(wall, nodes).filter( - (zone: ZoneNode) => zone.spaceRole === 'room' && zone.polygon.length >= 3, - ) - const spans = getWallZoneSpans(wall, rooms) - if (!spans.length) return null - return FACES.filter( - (face) => - indoorShare( - spans.filter( - (span) => span.face === face && !isOutdoorRoom(nodes[span.zoneId] as ZoneNode), - ), - ) >= 0.5, - ) -} - -export function outsideFinishInside( - nodes: SceneNodes, - materials?: Materials, -): OutsideFinishInside[] { - const groups = new Map() - const partitionRefs = new Map() - let partitions = 0 - for (const wall of queryNodes(nodes, { type: 'wall' })) { - if (wall.wallType === 'curtain' || wall.visible === false) continue - const inside = wallInsideFaces(nodes, wall) - if (!inside?.length) continue - const rooms = getWallLevelZones(wall, nodes).filter( - (zone: ZoneNode) => zone.spaceRole === 'room' && zone.polygon.length >= 3, - ) - const spans = getWallZoneSpans(wall, rooms) - const faces = describeWallFaceFinishes(wall, nodes) - if (inside.length === 2) { - partitions += 1 - for (const face of FACES) - for (const [ref, metres] of writtenRefs(faces[face].stretches)) - partitionRefs.set(ref, (partitionRefs.get(ref) ?? 0) + metres) - continue - } - const [innerFace] = inside as [WallFace] - const outerFace: WallFace = innerFace === 'a' ? 'b' : 'a' - const outer = dominantRef(faces[outerFace].stretches) - if (!outer || outer !== dominantRef(faces[innerFace].stretches)) continue - const lengthM = faces[innerFace].stretches.reduce((sum, s) => sum + lengthOf(s), 0) - const names = [ - ...new Set( - spans - .filter( - (span) => span.face === innerFace && !isOutdoorRoom(nodes[span.zoneId] as ZoneNode), - ) - .map((span) => (nodes[span.zoneId] as ZoneNode).name), - ), - ] - groups.set(outer, [ - ...(groups.get(outer) ?? []), - { id: wall.id, levelId: wall.parentId ?? '', lengthM, rooms: names }, - ]) - } - if (!partitions) return [] - const inPartitions = [...partitionRefs].sort((p, q) => q[1] - p[1]) - return [...groups] - .filter(([ref]) => !partitionRefs.has(ref)) - .map(([ref, walls]) => ({ - finish: describeFinish(ref, materials), - walls, - partitions: inPartitions.slice(0, 2).map(([other]) => describeFinish(other, materials)), - })) -} diff --git a/packages/core/src/agent-tools/verify-scene.ts b/packages/core/src/agent-tools/verify-scene.ts index b7e7d27a47..7d324c3863 100644 --- a/packages/core/src/agent-tools/verify-scene.ts +++ b/packages/core/src/agent-tools/verify-scene.ts @@ -29,7 +29,7 @@ export function extendVerifyScene(extension: { } const DESCRIPTION = - 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), two rooms on the same clear floor (zones_overlap) and floor inside a covered space that no zone or stair claims (floor_unclaimed), both warnings with their area, width and place and quiet under 0.1 m² (overlap), 0.3 m² (unclaimed) or 15 cm wide, wall bodies not counting as floor, an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). What the surfaces of a room say, each one an observation to keep when it is intended: a wet room whose walls are not tiled where its fixtures stand (room_wet_untiled), skirting in no room or on part of the wall faces of a room (rooms_no_skirting, rooms_skirting_partial), floors and wall faces left at the default finish (rooms_floors_default, wall_faces_default), an outside finish that also shows on the inside face of a wall (walls_outside_finish_inside), and an item hung on the face that looks into a different room than the one it names (room_wall_item_wrong_face). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' + 'Optional whole-scene evidence: per-level content, roles (storey, roof-only, support) and the spaces its walls enclose, then every problem found, each with a type: empty levels, walls with no room or door, a space the walls enclose with no room over it (space_no_room) or with several and no wall between them (space_many_rooms), a room the walls do not close (room_not_enclosed) or with no name (room_unnamed), two rooms on the same clear floor (zones_overlap) and floor inside a covered space that no zone or stair claims (floor_unclaimed), both warnings with their area, width and place and quiet under 0.1 m² (overlap), 0.3 m² (unclaimed) or 15 cm wide, wall bodies not counting as floor, an end that stops 3-25 cm short of another wall (wall_end_short, warning: the daylight in cm, both walls named; an end that touches a wall is a joint) and a wall 0.5-6 degrees off the line of the walls it carries on from or sits between, when that moves its far end 2 cm or more off the line (wall_nearly_aligned, warning: the angle, the offset, the neighbours; a larger turn is an angle drawn on purpose and is not named), rooms with no floor or ceiling, storeys with no stair, roof levels misused, walls intersecting a covering slab or ending coplanar with its walking surface (wall_covering_slab_contact, with wallId and slabId), openings off their wall, stairs off their slab or blocked, furniture blocking a door or overlapping, a house past its lot line or in its required yards, every node field its schema rejects (schema_invalid, with its nodeId and path; valid is then false, and the level holding the node lists it as unread and is measured once it is fixed), a node kind no schema here knows, once per kind (schema_unknown_kind, info: a plugin kind), a hidden site (site_hidden). What the surfaces of a room say, each one an observation to keep when it is intended: a wet room whose walls are not tiled where its fixtures stand (room_wet_untiled), skirting in no room or on part of the wall faces of a room (rooms_no_skirting, rooms_skirting_partial), and floors and wall faces left at the default finish (rooms_floors_default, wall_faces_default). Static authored ceiling objects report transformed bounds extending above their ceiling attachment and bounds overlapping solid covering slab bands, with node IDs and measured metres; stored and derived slab holes are subtracted. Wall-mounted objects report a front oriented toward their host; static authored wall bounds report wall-body overlap and extension through the opposite face. With settled editor meshes, catalog wall bounds and large competing coplanar faces against the host or another item on the same wall are also measured within 1 mm. Hidden back-to-wall contact is not competing face evidence. These are observations, not instructions to change the scene or proof of exact mesh intersection. Bounds are measured in the owning building frame, including stacked level elevations. Unknown catalog raw bounds without meshes, animated models, unsupported attachment frames, unresolved scripted wall cuts, roof collisions, recessed slab shells and foundation volumes are not assessed.' export const verifySceneTool = { name: 'verify_scene', From 673923efcdd479862092f095287fd2f15b32214a Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 19:56:53 +0100 Subject: [PATCH 36/40] Move the brief's end-of-turn findings out: form read-back, revisions and gaps The six finding types (form_simpler_than_brief, form_revised_simpler, facade_revised_simpler, room_dressing_revised_simpler, form_bounded_without_plan, rooms_not_listed) read what the scene holds against what the brief says. The first was raised twice in 19 stored runs and never acted on; the other five were never raised in any stored run. They leave as one block, with BRIEF_FINDING_CODES, the form, facade and dressing readers, the massing reader, the four session fields only they used (firstMassing, firstTreatment, firstDressing, briefMadeAt), their fixtures and tests, the metadata rows only the massing reader needed, and the sentences of design_brief's description and the wiki that described them. The generic readings store of the session record stays: the brief's refused pieces and run_batch use it. The code stays on rd/editor-later-20261103. Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/brief-gaps-cases.ts | 148 ------ .../agent-operations/__fixtures__/cases.ts | 8 - .../__fixtures__/design-facade-cases.ts | 87 ---- .../__fixtures__/design-form-cases.ts | 422 ------------------ .../__fixtures__/room-dressing-cases.ts | 78 ---- .../src/agent-operations/brief-findings.ts | 118 ----- .../src/agent-operations/brief-gaps.test.ts | 67 --- .../core/src/agent-operations/brief-gaps.ts | 50 --- .../core/src/agent-operations/design-brief.ts | 5 +- .../agent-operations/design-facade.test.ts | 9 - .../src/agent-operations/design-facade.ts | 84 ---- .../src/agent-operations/design-form.test.ts | 80 ---- .../core/src/agent-operations/design-form.ts | 341 -------------- packages/core/src/agent-operations/index.ts | 5 - .../core/src/agent-operations/massing-read.ts | 320 ------------- .../agent-operations/room-dressing.test.ts | 33 -- .../src/agent-operations/room-dressing.ts | 64 --- .../src/agent-operations/scene-checkpoint.ts | 45 +- packages/core/src/agent-tools/design-brief.ts | 16 +- .../core/src/contracts/reference-inventory.ts | 9 - wiki/architecture/agent-surfaces.md | 2 +- 21 files changed, 10 insertions(+), 1981 deletions(-) delete mode 100644 packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts delete mode 100644 packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts delete mode 100644 packages/core/src/agent-operations/__fixtures__/design-form-cases.ts delete mode 100644 packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts delete mode 100644 packages/core/src/agent-operations/brief-findings.ts delete mode 100644 packages/core/src/agent-operations/brief-gaps.test.ts delete mode 100644 packages/core/src/agent-operations/brief-gaps.ts delete mode 100644 packages/core/src/agent-operations/design-facade.test.ts delete mode 100644 packages/core/src/agent-operations/design-facade.ts delete mode 100644 packages/core/src/agent-operations/design-form.test.ts delete mode 100644 packages/core/src/agent-operations/design-form.ts delete mode 100644 packages/core/src/agent-operations/massing-read.ts delete mode 100644 packages/core/src/agent-operations/room-dressing.test.ts delete mode 100644 packages/core/src/agent-operations/room-dressing.ts diff --git a/packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts b/packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts deleted file mode 100644 index ad6a164f9d..0000000000 --- a/packages/core/src/agent-operations/__fixtures__/brief-gaps-cases.ts +++ /dev/null @@ -1,148 +0,0 @@ -import type { DesignBrief } from '../../agent-tools/design-brief' -import type { MadeEntry, SessionRecord } from '../scene-checkpoint' -import type { AgentToolCase } from './cases' -import { HOUSE_ROOMS, OPEN_AXES } from './design-brief-cases' -import { massedScene, rect } from './design-form-cases' - -/** - * What a brief leaves unstated while the turn built: a form bounded by words that fix no plan, and - * a brief that lists no rooms for a building of many. A finding at the - * end of the turn, for a turn that made zones or levels since the brief, never a refusal. - */ - -const house = () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) - -const bounded = (quote: string, reading: string) => ({ - kind: 'bounded' as const, - quote, - reading, -}) - -/** "Construis-moi une grande maison": the form and the facade bounded by words that state no plan and no treatment. */ -const GRANDE_MAISON: DesignBrief = { - axes: { - ...OPEN_AXES, - form: bounded('grande maison', 'a large house'), - facade: bounded('grande maison', 'a large house'), - }, - source: 'open', - vision: 'A large house.', - beyond: 'none: the test reads the brief.', -} - -export const zone = (id: string): MadeEntry => ({ id, type: 'zone', levelId: 'level_0' }) -const lamp: MadeEntry = { id: 'item_lamp', type: 'item', levelId: 'level_0' } - -/** The session of a turn: what the thread made before the brief, the brief, what was made under it. */ -export const underBrief = ( - designBrief: DesignBrief, - before: MadeEntry[], - under: MadeEntry[], -): SessionRecord => ({ - checkpoints: {}, - made: [...before, ...under], - designBrief, - briefMadeAt: before.length, -}) - -const keeping = (session: SessionRecord): AgentToolCase['context'] => ({ - designBrief: session.designBrief, - session: () => session, -}) - -const FORM = { type: 'form_bounded_without_plan', severity: 'warning' } -const ROOMS = { type: 'rooms_not_listed', severity: 'warning' } - -export const BRIEF_GAP_CASES: AgentToolCase[] = [ - { - name: 'a form bounded by "grande maison" while the turn built a rectangle: the finding names the words and what was built', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(underBrief(GRANDE_MAISON, [], [zone('zone_House_0')])), - expect: { - result: { hasIssues: true }, - contains: { - issues: [ - { - ...FORM, - message: - 'The brief bounds the form by "grande maison", words that fix no plan; the scene has 1 volume (rectangle).', - }, - ], - }, - }, - }, - { - name: 'a turn that made no zone or level, a lamp, says nothing of the form: the cheap statement holds', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(underBrief(GRANDE_MAISON, [], [lamp])), - expect: { result: {}, lacks: { issues: [FORM, ROOMS] } }, - }, - { - name: 'what the thread built before the brief is not the turn’s: no finding', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(underBrief(GRANDE_MAISON, [zone('zone_House_0'), zone('zone_Study_0')], [lamp])), - expect: { result: {}, lacks: { issues: [FORM, ROOMS] } }, - }, - { - name: 'a session record with no marker (before it existed) cannot tell the turn: no finding', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping({ - checkpoints: {}, - made: [zone('zone_House_0'), zone('zone_Study_0')], - designBrief: GRANDE_MAISON, - }), - expect: { result: {}, lacks: { issues: [FORM, ROOMS] } }, - }, - { - name: 'three rooms built under a brief that lists none: the finding counts them', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping( - underBrief(GRANDE_MAISON, [], [zone('zone_a'), zone('zone_b'), zone('zone_c')]), - ), - expect: { - result: {}, - contains: { issues: [ROOMS] }, - mentions: ['The brief lists no rooms; the turn built 3 rooms.'], - }, - }, - { - name: 'one room built, or the rooms listed: no rooms finding', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping( - underBrief({ ...GRANDE_MAISON, rooms: HOUSE_ROOMS }, [], [zone('zone_a'), zone('zone_b')]), - ), - expect: { result: {}, lacks: { issues: [ROOMS] } }, - }, - { - name: 'a form that states its plan is compared and not reported as unstated', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping( - underBrief( - { - ...GRANDE_MAISON, - axes: { - ...GRANDE_MAISON.axes, - form: { ...bounded('grande maison', 'a large house'), massing: { plan: 'rectangle' } }, - }, - }, - [], - [zone('zone_House_0')], - ), - ), - expect: { result: {}, lacks: { issues: [FORM] } }, - }, -] diff --git a/packages/core/src/agent-operations/__fixtures__/cases.ts b/packages/core/src/agent-operations/__fixtures__/cases.ts index a524beae46..2539db18e6 100644 --- a/packages/core/src/agent-operations/__fixtures__/cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/cases.ts @@ -31,11 +31,7 @@ import { OUTDOOR_ROOM_READ_CASES, ROOM_CASES } from './room-cases' import { CHECK_ROOMS_CASES, VALIDATE_SCENE_CASES } from './scene-check-cases' import { SEARCH_ASSETS_CASES } from './search-assets-cases' import { VIEW_ASSETS_CASES } from './view-assets-cases' -import { BRIEF_GAP_CASES } from './brief-gaps-cases' import { DESIGN_BRIEF_CASES } from './design-brief-cases' -import { DESIGN_FACADE_CASES } from './design-facade-cases' -import { DESIGN_FORM_CASES } from './design-form-cases' -import { DESIGN_DRESSING_CASES } from './room-dressing-cases' import { CORNER_WINDOW_CASES } from './corner-window-cases' import { MERGE_WINDOWS_CASES } from './merge-windows-cases' import { DESCRIBE_NODE_CASES, FIND_NODES_CASES } from './node-read-cases' @@ -978,10 +974,6 @@ export const AGENT_TOOL_CASES: readonly AgentToolCase[] = [ ...SEARCH_ASSETS_CASES, ...VIEW_ASSETS_CASES, ...DESIGN_BRIEF_CASES, - ...DESIGN_FORM_CASES, - ...DESIGN_FACADE_CASES, - ...DESIGN_DRESSING_CASES, - ...BRIEF_GAP_CASES, ...ADD_WALL_CASES, ...WALL_TYPE_CASES, ...FRAMING_POST_CASES, diff --git a/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts deleted file mode 100644 index 256f0fd335..0000000000 --- a/packages/core/src/agent-operations/__fixtures__/design-facade-cases.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { DesignBrief, Treatment } from '../../agent-tools/design-brief' -import type { SessionRecord } from '../scene-checkpoint' -import type { AgentToolCase } from './cases' -import { BEDROOM_AXES, openFacade } from './design-brief-cases' -import { massedScene, rect } from './design-form-cases' - -/** - * The facade a brief states, and a later brief of the turn against the first: a finding where a - * later brief states a plainer treatment (fewer cladding families, bands or elements, a free - * rhythm for a regular one), none where it states the same or more or states no treatment. - */ - -const house = () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) - -const brief = (treatment: Treatment | undefined): DesignBrief => ({ - axes: { - ...BEDROOM_AXES, - facade: treatment - ? openFacade('a stone manor, dressed, its windows shuttered', treatment) - : BEDROOM_AXES.facade, - }, - source: 'open', - vision: 'A manor in stone.', - beyond: 'none: the test reads the facade.', -}) -export const facadeBrief = brief - -export const MANOR: Treatment = { - cladding: ['stone'], - bands: ['base', 'cornice'], - elements: ['corners', 'shutters', 'entrance'], - rhythm: 'regular', -} - -const keeping = (designBrief: DesignBrief, firstTreatment?: Treatment): AgentToolCase['context'] => ({ - designBrief, - session: (): SessionRecord => ({ - checkpoints: {}, - made: [], - designBrief, - ...(firstTreatment ? { firstTreatment } : {}), - }), -}) - -const REVISED = { type: 'facade_revised_simpler', severity: 'info' } - -export const DESIGN_FACADE_CASES: AgentToolCase[] = [ - { - name: 'a facade revised to a plainer treatment within the turn: a finding says so', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(brief({ cladding: ['stone'], rhythm: 'free' }), MANOR), - expect: { - result: {}, - contains: { issues: [REVISED] }, - mentions: [ - 'The facade was revised during the turn: from stone cladding, base and cornice bands, corner chains, shutters, an entrance unit and a regular rhythm to stone cladding and a free rhythm.', - ], - }, - }, - { - name: 'a facade revised to a richer one, or left as it was: no revision finding', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(brief(MANOR), { cladding: ['stone'], rhythm: 'free' }), - expect: { result: {}, lacks: { issues: [REVISED] } }, - }, -] - -/** A first treatment, the one a later brief of the turn states, and whether the later one is plainer. */ -export const FACADE_REVISION_ROWS: { - name: string - first: Treatment | undefined - latest: Treatment | undefined - plainer: boolean -}[] = [ - { name: 'a manor revised to cladding and a free rhythm', first: MANOR, latest: { cladding: ['stone'], rhythm: 'free' }, plainer: true }, - { name: 'a regular rhythm revised to a free one', first: { cladding: ['stone'], rhythm: 'regular' }, latest: { cladding: ['stone'], rhythm: 'free' }, plainer: true }, - { name: 'a band dropped', first: { cladding: ['stone'], bands: ['base', 'cornice'], rhythm: 'free' }, latest: { cladding: ['stone'], bands: ['cornice'], rhythm: 'free' }, plainer: true }, - { name: 'a stone facade revised to brick: a swap asks as much', first: { cladding: ['stone'], rhythm: 'free' }, latest: { cladding: ['brick'], rhythm: 'free' }, plainer: false }, - { name: 'a facade revised to a richer one', first: { cladding: ['stone'], rhythm: 'free' }, latest: MANOR, plainer: false }, - { name: 'a facade restated as it was', first: MANOR, latest: MANOR, plainer: false }, - { name: 'a later brief that states no treatment has nothing to compare', first: MANOR, latest: undefined, plainer: false }, - { name: 'no first treatment', first: undefined, latest: MANOR, plainer: false }, -] diff --git a/packages/core/src/agent-operations/__fixtures__/design-form-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-form-cases.ts deleted file mode 100644 index b0a87eb8f7..0000000000 --- a/packages/core/src/agent-operations/__fixtures__/design-form-cases.ts +++ /dev/null @@ -1,422 +0,0 @@ -import type { DesignBrief, Massing } from '../../agent-tools/design-brief' -import { BuildingNode, LevelNode, SiteNode, ZoneNode } from '../../schema' -import type { SessionRecord } from '../scene-checkpoint' -import type { AgentToolCase, SceneGraph } from './cases' -import { BEDROOM_AXES, LAMP_AXES, openForm } from './design-brief-cases' - -/** - * The form a brief states, read back against the volumes the scene has: a finding where the scene - * is plainer than the brief, none where it holds up what is stated or the brief states no massing. - * Scenes are rooms tagged with the volume they belong to (or untagged, as create_room leaves them), one - * level per storey, each 3 m tall, on the editor's scaffold: a site and a building. - */ - -type Pt = [number, number] -type Part = { - name: string - polygon: Pt[] - /** Tagged with the volume the room belongs to; left out, the room is untagged and read as inferred. */ - shape?: string - /** Storeys counted from `from`, 1 by default. */ - storeys?: number - /** The first storey it stands on, 0 by default: -1 is a basement. */ - from?: number -} - -export const rect = (minX: number, minZ: number, maxX: number, maxZ: number): Pt[] => [ - [minX, minZ], - [maxX, minZ], - [maxX, maxZ], - [minX, maxZ], -] - -export function massedScene(...parts: Part[]): SceneGraph { - const storeys = parts.flatMap((part) => - Array.from({ length: part.storeys ?? 1 }, (_, s) => (part.from ?? 0) + s), - ) - const levelIds = Array.from(new Set(storeys)).sort((a, b) => a - b) - const levels = levelIds.map((index) => - LevelNode.parse({ - id: `level_${index}`, - parentId: 'building_a', - level: index, - height: 3, - children: [], - }), - ) - const zones = parts.flatMap((part) => - Array.from({ length: part.storeys ?? 1 }, (_, s) => { - const index = (part.from ?? 0) + s - return ZoneNode.parse({ - id: `zone_${part.name}_${index}`, - parentId: `level_${index}`, - name: part.name, - polygon: part.polygon, - ...(part.shape - ? { - metadata: { - volume: { - id: `volume_${part.name}`, - name: part.name, - shape: part.shape, - storeyIndex: s, - partIndex: 0, - }, - }, - } - : {}), - }) - }), - ) - const site = SiteNode.parse({ id: 'site_a', children: ['building_a'] }) - // Storeys below the ground floor push the stack down: the ground floor stands at the site's grade. - const building = BuildingNode.parse({ - id: 'building_a', - parentId: 'site_a', - position: [0, 3 * Math.min(0, ...levelIds), 0], - children: levels.map((level) => level.id), - }) - const nodes = Object.fromEntries( - [site, building, ...levels, ...zones].map((node) => [node.id, node]), - ) - for (const level of levels) - (nodes[level.id] as { children: string[] }).children = zones - .filter((zone) => zone.parentId === level.id) - .map((zone) => zone.id) - return { nodes, rootNodeIds: [building.id] } -} - -/** The brief of "Construis-moi un manoir", its form stated: a U of three volumes at two heights. */ -const brief = (massing: Massing | undefined): DesignBrief => ({ - axes: { - ...BEDROOM_AXES, - form: massing - ? openForm('a central body with two wings stepping forward, the wings lower', massing) - : BEDROOM_AXES.form, - }, - source: 'open', - vision: 'A manor around its forecourt.', - beyond: 'none: the test reads the form.', -}) - -const U_OF_THREE: Massing = { plan: 'u', volumes: 3, heights: 'several' } - -/** The U as the brief states it: a two-storey body across the back, a one-storey wing at each end. */ -export const U_BUILT = massedScene( - { name: 'Body', polygon: rect(0, 0, 12, 4), shape: 'rectangle', storeys: 2 }, - { name: 'West wing', polygon: rect(0, 4, 3, 9), shape: 'rectangle' }, - { name: 'East wing', polygon: rect(9, 4, 12, 9), shape: 'rectangle' }, -) - -/** The same house as two rectangles, an L at one height. */ -export const TWO_RECTANGLES = massedScene( - { name: 'Body', polygon: rect(0, 0, 12, 4), shape: 'rectangle' }, - { name: 'West wing', polygon: rect(0, 4, 3, 9), shape: 'rectangle' }, -) - -/** The brief in force on every surface: the session's, and the one the host passes where it gates. */ -const keeping = (designBrief: DesignBrief, firstMassing?: Massing): AgentToolCase['context'] => ({ - designBrief, - session: (): SessionRecord => ({ - checkpoints: {}, - made: [], - designBrief, - ...(firstMassing ? { firstMassing } : {}), - }), -}) - -const FINDING = { type: 'form_simpler_than_brief', severity: 'warning' } -const REVISED = { type: 'form_revised_simpler', severity: 'warning' } -const RECTANGLE: Massing = { plan: 'rectangle', volumes: 1, heights: 'one' } - -export const DESIGN_FORM_CASES: AgentToolCase[] = [ - { - name: 'two rectangle volumes against a U of three at different heights: one finding naming both sides', - tool: 'verify_scene', - scene: () => TWO_RECTANGLES, - input: {}, - context: keeping(brief(U_OF_THREE)), - expect: { - result: { hasIssues: true }, - contains: { issues: [FINDING] }, - mentions: [ - 'The brief states a form of a U, 3 volumes, at different heights; the scene has 2 volumes (rectangle, rectangle), a plan with 1 re-entrant corner, one height (3.0 m).', - ], - }, - }, - { - name: 'the finding says what is missing, on which building, and which read lists it', - tool: 'verify_scene', - scene: () => TWO_RECTANGLES, - input: {}, - context: keeping(brief(U_OF_THREE)), - expect: { - result: { hasIssues: true }, - mentions: [ - 'Compared on building building_a: volumes: 3 stated, 2 built (Body (rectangle, top 3.0 m), West wing (rectangle, top 3.0 m)), 1 missing; plan: a U needs 2 re-entrant corners or a court, the footprints have 1 re-entrant corner; heights: several stated, every volume tops out at 3.0 m.', - ], - }, - }, - { - name: 'a U of three volumes at two heights, as the brief states it: no finding', - tool: 'verify_scene', - scene: () => U_BUILT, - input: {}, - context: keeping(brief(U_OF_THREE)), - expect: { result: {}, lacks: { issues: [FINDING] } }, - }, - { - name: 'a form stated with no massing (a focused edit bounds it by its words): no finding on any scene', - tool: 'verify_scene', - scene: () => TWO_RECTANGLES, - input: {}, - context: keeping({ - axes: LAMP_AXES, - source: 'open', - vision: 'One lamp.', - beyond: 'none: one lamp.', - }), - expect: { result: {}, lacks: { issues: [FINDING] } }, - }, - { - name: 'a U of three revised to a rectangle within the turn: a finding says so, though the scene matches the later brief', - tool: 'verify_scene', - scene: () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }), - input: {}, - context: keeping(brief(RECTANGLE), U_OF_THREE), - expect: { - result: { hasIssues: true }, - contains: { issues: [REVISED] }, - lacks: { issues: [FINDING] }, - mentions: [ - 'The form was revised during the turn: from a U, 3 volumes, at different heights to a rectangle, 1 volume.', - ], - }, - }, - { - name: 'a form revised to a richer one, or left as it was: no revision finding', - tool: 'verify_scene', - scene: () => U_BUILT, - input: {}, - context: keeping(brief(U_OF_THREE), RECTANGLE), - expect: { result: {}, lacks: { issues: [REVISED] } }, - }, - { - name: 'a form stated once and not revised: no revision finding', - tool: 'verify_scene', - scene: () => U_BUILT, - input: {}, - context: keeping(brief(U_OF_THREE), U_OF_THREE), - expect: { result: {}, lacks: { issues: [REVISED] } }, - }, - { - name: 'a brief stored before the form axis existed: no finding, no throw', - tool: 'verify_scene', - scene: () => TWO_RECTANGLES, - input: {}, - context: keeping({ - axes: { ...BEDROOM_AXES, form: undefined }, - source: 'open', - vision: 'A bedroom.', - beyond: 'none: older brief.', - }), - expect: { result: {}, lacks: { issues: [FINDING] } }, - }, -] - -/** A scene, the massing the brief states, and what differs (none: no finding). */ -export const FORM_ROWS: { - name: string - scene: SceneGraph - massing: Massing | undefined - differs: string[] -}[] = [ - { - name: 'one box against a U of one volume', - scene: massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }), - massing: { plan: 'u', volumes: 1, heights: 'one' }, - differs: ['plan'], - }, - { - name: 'an L built as one letter volume against an L', - scene: massedScene({ - name: 'House', - shape: 'l', - polygon: [ - [0, 0], - [12, 0], - [12, 4], - [3, 4], - [3, 9], - [0, 9], - ], - }), - massing: { plan: 'l', volumes: 1, heights: 'one' }, - differs: [], - }, - { - name: 'an L of untagged rooms against an L: the outline is read, not the tags', - scene: massedScene( - { name: 'Hall', polygon: rect(0, 0, 12, 4) }, - { name: 'Study', polygon: rect(0, 4, 3, 9) }, - ), - massing: { plan: 'l', volumes: 1, heights: 'one' }, - differs: [], - }, - { - name: 'a U built as a U against a courtyard', - scene: U_BUILT, - massing: { plan: 'courtyard', volumes: 3, heights: 'several' }, - differs: ['plan'], - }, - { - name: 'a court closed on four sides against a U: the court holds up what the U leaves open', - scene: massedScene( - { name: 'North', polygon: rect(0, 0, 12, 3), shape: 'courtyard' }, - { name: 'South', polygon: rect(0, 9, 12, 12), shape: 'courtyard' }, - { name: 'West', polygon: rect(0, 3, 3, 9), shape: 'courtyard' }, - { name: 'East', polygon: rect(9, 3, 12, 9), shape: 'courtyard' }, - ), - massing: { plan: 'u', volumes: 4, heights: 'one' }, - differs: [], - }, - { - name: 'volumes that touch against detached volumes', - scene: TWO_RECTANGLES, - massing: { plan: 'detached', volumes: 2, heights: 'one' }, - differs: ['plan'], - }, - { - name: 'volumes that stand apart against detached volumes', - scene: massedScene( - { name: 'House', polygon: rect(0, 0, 10, 6), shape: 'rectangle' }, - { name: 'Pavilion', polygon: rect(14, 0, 18, 6), shape: 'rectangle' }, - ), - massing: { plan: 'detached', volumes: 2, heights: 'one' }, - differs: [], - }, - { - name: 'one height against several', - scene: massedScene( - { name: 'Body', polygon: rect(0, 0, 10, 6), shape: 'rectangle' }, - { name: 'Wing', polygon: rect(10, 0, 14, 6), shape: 'rectangle' }, - ), - massing: { plan: 'rectangle', volumes: 2, heights: 'several' }, - differs: ['heights'], - }, - { - name: 'a taller body and a lower wing against several heights', - scene: massedScene( - { name: 'Body', polygon: rect(0, 0, 10, 6), shape: 'rectangle', storeys: 2 }, - { name: 'Wing', polygon: rect(10, 0, 14, 6), shape: 'rectangle' }, - ), - massing: { plan: 'rectangle', volumes: 2, heights: 'several' }, - differs: [], - }, - { - name: 'more volumes than the brief states are not simpler', - scene: U_BUILT, - massing: { plan: 'rectangle', volumes: 1, heights: 'one' }, - differs: [], - }, - { - name: 'a basement under the whole plan does not fill the notch of a U or count as a volume', - scene: massedScene( - { name: 'Body', polygon: rect(0, 0, 12, 4), shape: 'rectangle' }, - { name: 'West wing', polygon: rect(0, 4, 3, 9), shape: 'rectangle' }, - { name: 'East wing', polygon: rect(9, 4, 12, 9), shape: 'rectangle' }, - { name: 'Cellar', polygon: rect(0, 0, 12, 9), shape: 'rectangle', from: -1 }, - ), - massing: { plan: 'u', volumes: 3, heights: 'one' }, - differs: [], - }, - { - name: 'a scene with no building above grade has nothing to compare', - scene: massedScene({ name: 'Cellar', polygon: rect(0, 0, 12, 9), shape: 'rectangle', from: -1 }), - massing: { plan: 'u', volumes: 3, heights: 'several' }, - differs: [], - }, - { - name: 'a form that states only the plan its words fix, "an L-shaped house", built as a box', - scene: massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }), - massing: { plan: 'l' }, - differs: ['plan'], - }, - { - name: 'no massing stated', - scene: TWO_RECTANGLES, - massing: undefined, - differs: [], - }, -] - -export const formBrief = brief - -/** A form stated first, the one a later brief of the turn states, and what the later one asks less of. */ -export const REVISION_ROWS: { - name: string - first: Massing | undefined - latest: Massing | undefined - differs: string[] -}[] = [ - { - name: 'a U of three at different heights revised to a rectangle of one', - first: U_OF_THREE, - latest: RECTANGLE, - differs: ['volumes', 'plan', 'heights'], - }, - { - name: 'three volumes revised to two', - first: { plan: 'u', volumes: 3, heights: 'one' }, - latest: { plan: 'u', volumes: 2, heights: 'one' }, - differs: ['volumes'], - }, - { - name: 'a letter plan revised to a plainer one', - first: { plan: 'h', volumes: 3, heights: 'one' }, - latest: { plan: 'l', volumes: 3, heights: 'one' }, - differs: ['plan'], - }, - { - name: 'a court revised to a letter', - first: { plan: 'courtyard', volumes: 4, heights: 'one' }, - latest: { plan: 'u', volumes: 4, heights: 'one' }, - differs: ['plan'], - }, - { - name: 'several heights revised to one', - first: U_OF_THREE, - latest: { ...U_OF_THREE, heights: 'one' }, - differs: ['heights'], - }, - { - name: 'a form revised to a richer one', - first: RECTANGLE, - latest: U_OF_THREE, - differs: [], - }, - { - name: 'a form restated as it was', - first: U_OF_THREE, - latest: U_OF_THREE, - differs: [], - }, - { - name: 'a plan of the same rank, a U for a T', - first: { plan: 'u', volumes: 3, heights: 'one' }, - latest: { plan: 't', volumes: 3, heights: 'one' }, - differs: [], - }, - { - name: 'a later brief that states no massing has nothing to compare', - first: U_OF_THREE, - latest: undefined, - differs: [], - }, - { - name: 'no first massing', - first: undefined, - latest: RECTANGLE, - differs: [], - }, -] diff --git a/packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts b/packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts deleted file mode 100644 index 556dd519ab..0000000000 --- a/packages/core/src/agent-operations/__fixtures__/room-dressing-cases.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type { BriefRoom, DesignBrief, RoomDressing } from '../../agent-tools/design-brief' -import type { SessionRecord } from '../scene-checkpoint' -import type { AgentToolCase } from './cases' -import { BEDROOM_AXES } from './design-brief-cases' -import { massedScene, rect } from './design-form-cases' - -/** - * The dressing a brief announces for a room, and a later brief of the turn against the first: a - * finding where a later brief announces a kind of wall dressing the first announced for that room - * and no longer does, none where it announces the same or more. - */ - -const house = () => massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) - -const SALON = (dressing?: RoomDressing[]): BriefRoom => ({ - name: 'Salon', - use: 'living', - distinct: 'The family room, warm and panelled.', - finishes: { - floor: 'oak', - walls: 'white paint', - tiled: false, - skirting: false, - ...(dressing ? { dressing } : {}), - }, - pieces: ['sofa'], -}) - -export const dressingBrief = (...rooms: BriefRoom[]): DesignBrief => ({ - axes: BEDROOM_AXES, - source: 'open', - vision: 'A house.', - beyond: 'none: the test reads the walls.', - rooms, -}) -export const salonBrief = (dressing?: RoomDressing[]) => dressingBrief(SALON(dressing)) - -const keeping = ( - designBrief: DesignBrief, - firstDressing?: SessionRecord['firstDressing'], -): AgentToolCase['context'] => ({ - designBrief, - session: (): SessionRecord => ({ - checkpoints: {}, - made: [], - designBrief, - ...(firstDressing ? { firstDressing } : {}), - }), -}) - -const REVISED = { type: 'room_dressing_revised_simpler', severity: 'warning' } - -export const DESIGN_DRESSING_CASES: AgentToolCase[] = [ - { - name: 'the dressing revised to less within the turn: a finding says what the brief no longer announces', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(salonBrief(['wainscot']), { salon: ['wainscot', 'chairRail', 'crown'] }), - expect: { - result: {}, - contains: { issues: [REVISED] }, - mentions: [ - "The rooms' dressing was revised during the turn; the brief no longer announces Salon: a chair rail and a crown moulding.", - ], - }, - }, - { - name: 'the dressing revised to the same or to more: no revision finding', - tool: 'verify_scene', - scene: house, - input: {}, - context: keeping(salonBrief(['wainscot', 'chairRail', 'crown', 'splashback']), { - salon: ['wainscot', 'chairRail'], - }), - expect: { result: {}, lacks: { issues: [REVISED] } }, - }, -] diff --git a/packages/core/src/agent-operations/brief-findings.ts b/packages/core/src/agent-operations/brief-findings.ts deleted file mode 100644 index 17d5c2a48d..0000000000 --- a/packages/core/src/agent-operations/brief-findings.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { briefGaps } from './brief-gaps' -import { facadeRevision } from './design-facade' -import { formFinding, formRevision } from './design-form' -import { dressingRevision } from './room-dressing' -import type { SessionRecord } from './scene-checkpoint' -import type { SceneNodes } from './types' -import { CHECKPOINT_ORDER, registerSceneCheck } from './verify-scene' - -/** - * What the design brief in force says against the scene, for the one place each surface reads it: - * the form the brief states, read back against the building (a finding where the scene is - * plainer), a later brief of the turn that states the form, the facade or a room's dressing plainer - * than the first (a revision), and what the brief leaves unstated while the turn built. None of - * them refuses a write. - */ - -export type BriefFinding = { - code: string - message: string - /** Absent means warning, as a verify_scene issue's. */ - severity?: 'info' | 'warning' -} - -/** Every code the brief's findings carry: how a reader picks them out of a verify_scene result or a program's diagnostics. */ -export const BRIEF_FINDING_CODES: readonly string[] = [ - 'form_simpler_than_brief', - 'form_revised_simpler', - 'facade_revised_simpler', - 'room_dressing_revised_simpler', - 'form_bounded_without_plan', - 'rooms_not_listed', -] - -/** The scene against the brief: what a program's close reports, the revisions being the turn's and not the scene's. */ -export function briefSceneFindings( - brief: SessionRecord['designBrief'] | null | undefined, - nodes: SceneNodes, -): BriefFinding[] { - const form = formFinding(brief, nodes) - return form ? [form] : [] -} - -/** The phase a program declares: what it is for, which says what of the brief it is too early to ask. */ -export type BriefPhase = 'structure' | 'furnish' | 'finish' | 'edit' - -/** How a reader reads the brief: `phase` is a program's own, which leaves out what the program is too early for (see `briefFindingsForPhase`). */ -export type BriefReadOptions = { phase?: BriefPhase } - -/** What a structure or furnish program can be asked of the brief: the form, a later brief's revision of it and of the facade, and what the brief leaves unstated. */ -const FROM_STRUCTURE: ReadonlySet = new Set([ - 'form_simpler_than_brief', - 'form_revised_simpler', - 'facade_revised_simpler', - 'form_bounded_without_plan', - 'rooms_not_listed', -]) - -/** - * The findings a program's close reports, by the program's own phase: a structure or furnish - * program is asked of the form, the revisions and what the brief leaves unstated, a finish or edit - * program (or one with no phase) of everything, the room dressing included. A program is not - * asked, mid-build, for what it has not finished yet; the end of the turn is asked everything. - */ -export function briefFindingsForPhase( - findings: readonly BriefFinding[], - phase: BriefPhase | undefined, -): BriefFinding[] { - return phase === 'structure' || phase === 'furnish' - ? findings.filter((finding) => FROM_STRUCTURE.has(finding.code)) - : [...findings] -} - -/** Where a later brief of the turn states a plainer form or facade than the first did. */ -export function briefRevisions( - session: Pick, -): BriefFinding[] { - return [ - formRevision(session.firstMassing, session.designBrief), - facadeRevision(session.firstTreatment, session.designBrief), - dressingRevision(session.firstDressing, session.designBrief), - ].filter((finding): finding is NonNullable => finding !== null) -} - -/** Everything the brief in force says of the scene and of the turn. */ -export function briefFindings( - session: Pick< - SessionRecord, - 'designBrief' | 'firstMassing' | 'firstTreatment' | 'firstDressing' | 'made' | 'briefMadeAt' - >, - nodes: SceneNodes, - options: BriefReadOptions = {}, -): BriefFinding[] { - return briefFindingsForPhase( - [ - ...briefSceneFindings(session.designBrief, nodes), - ...briefRevisions(session), - ...briefGaps(session, nodes), - ], - options.phase, - ) -} - -/** - * verify_scene's copy of the brief's findings, as a check it runs after the checkpoint's comparison: - * a warning each unless the finding says it informs. - */ -registerSceneCheck({ - name: 'brief findings', - order: CHECKPOINT_ORDER, - run: (nodes, _input, context) => - context.session - ? briefFindings(context.session, nodes).map((finding) => ({ - type: finding.code, - message: finding.message, - severity: finding.severity ?? 'warning', - })) - : [], -}) diff --git a/packages/core/src/agent-operations/brief-gaps.test.ts b/packages/core/src/agent-operations/brief-gaps.test.ts deleted file mode 100644 index b26056e22c..0000000000 --- a/packages/core/src/agent-operations/brief-gaps.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { underBrief, zone } from './__fixtures__/brief-gaps-cases' -import { formBrief, massedScene, rect } from './__fixtures__/design-form-cases' -import { briefGaps } from './brief-gaps' -import { EMPTY_SESSION, keepInSession, parseSessionRecord } from './scene-checkpoint' -import type { SceneNodes } from './types' - -describe('the turn’s marker in the session', () => { - const brief = formBrief(undefined) - - test('the first brief marks how much the thread had made; later briefs keep it', () => { - const session = { ...EMPTY_SESSION, made: [zone('zone_a'), zone('zone_b')] } - const first = keepInSession(session, { designBrief: brief }) - expect(first.briefMadeAt).toBe(2) - const grown = keepInSession(first, { made: [zone('zone_c')] }) - const revised = keepInSession(grown, { designBrief: brief }) - expect(revised.briefMadeAt).toBe(2) - expect(revised.made).toHaveLength(3) - }) - - test('it goes with the brief, and the next turn marks anew', () => { - const first = keepInSession( - { ...EMPTY_SESSION, made: [zone('zone_a')] }, - { designBrief: brief }, - ) - const cleared = keepInSession(first, { designBrief: null }) - expect(cleared.briefMadeAt).toBeUndefined() - const next = keepInSession( - { ...cleared, made: [zone('zone_a'), zone('zone_b')] }, - { designBrief: brief }, - ) - expect(next.briefMadeAt).toBe(2) - }) - - test('it is kept with the session record, and a record without it reads', () => { - const kept = keepInSession({ ...EMPTY_SESSION, made: [zone('zone_a')] }, { designBrief: brief }) - expect(parseSessionRecord(JSON.parse(JSON.stringify(kept))).briefMadeAt).toBe(1) - const { briefMadeAt: _marker, ...older } = kept - expect(parseSessionRecord(older).designBrief).toBeDefined() - }) -}) - -describe('what a brief leaves unstated, read for the turn that built', () => { - const nodes = massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) - .nodes as SceneNodes - - test('nothing to read without a brief, or without a marker', () => { - expect(briefGaps({ made: [zone('zone_a')], designBrief: undefined }, nodes)).toEqual([]) - expect( - briefGaps( - { made: [zone('zone_a'), zone('zone_b')], designBrief: formBrief(undefined) }, - nodes, - ), - ).toEqual([]) - }) - - test('two rooms built under a brief that bounds the form by words and lists no rooms: the two are said, in order', () => { - const findings = briefGaps( - underBrief(formBrief(undefined), [], [zone('zone_a'), zone('zone_b')]), - nodes, - ) - expect(findings.map((finding) => finding.code)).toEqual([ - 'form_bounded_without_plan', - 'rooms_not_listed', - ]) - }) -}) diff --git a/packages/core/src/agent-operations/brief-gaps.ts b/packages/core/src/agent-operations/brief-gaps.ts deleted file mode 100644 index eb2140cafc..0000000000 --- a/packages/core/src/agent-operations/brief-gaps.ts +++ /dev/null @@ -1,50 +0,0 @@ -import type { BriefAxes, DesignBrief } from '../agent-tools/design-brief' -import type { BriefFinding } from './brief-findings' -import { builtForm } from './design-form' -import type { SessionRecord } from './scene-checkpoint' -import type { SceneNodes } from './types' - -/** - * What a brief leaves unstated while the turn built: a form bounded by words that fix no plan is - * compared with nothing, and a brief that lists no rooms owes none to a - * building of many. A finding says so at the end of the turn, never a refusal: the brief is free to - * bound what the person's words bound, and the person sees what was then built without a statement - * to hold it to. Read only for a turn that built (the entries `made` since the brief). - */ - -const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}` - -type Bounded = Extract, { kind: 'bounded' }> - -const boundedWithout = ( - axis: Axis, - states: (axis: Bounded) => boolean, -): Bounded | null => - axis?.kind === 'bounded' && !states(axis as Bounded) ? (axis as Bounded) : null - -export function briefGaps( - session: Pick, - nodes: SceneNodes, -): BriefFinding[] { - const brief: DesignBrief | undefined = session.designBrief - if (!brief || session.briefMadeAt === undefined) return [] - const built = session.made.slice(session.briefMadeAt) - const structure = built.some((entry) => entry.type === 'zone' || entry.type === 'level') - const rooms = built.filter((entry) => entry.type === 'zone').length - const found: BriefFinding[] = [] - if (structure) { - const form = boundedWithout(brief.axes?.form, (axis) => Boolean(axis.massing?.plan)) - const volumes = form ? builtForm(nodes) : null - if (form && volumes) - found.push({ - code: 'form_bounded_without_plan', - message: `The brief bounds the form by "${form.quote}", words that fix no plan; the scene has ${plural(volumes.volumes, 'volume')} (${volumes.shapes.join(', ')}).`, - }) - } - if (rooms >= 2 && !brief.rooms?.length) - found.push({ - code: 'rooms_not_listed', - message: `The brief lists no rooms; the turn built ${rooms} rooms.`, - }) - return found -} diff --git a/packages/core/src/agent-operations/design-brief.ts b/packages/core/src/agent-operations/design-brief.ts index ab964f6f6b..b8601cc4f3 100644 --- a/packages/core/src/agent-operations/design-brief.ts +++ b/packages/core/src/agent-operations/design-brief.ts @@ -173,7 +173,7 @@ function requireTreatment(facade: NonNullable): void { /** * An open form states its massing in full, and a form of one volume is neither detached nor at - * several heights: what the scene is read back against is a commitment it can keep or break. + * several heights. */ function requireMassing(form: NonNullable): void { const massing = form.massing ?? {} @@ -232,8 +232,7 @@ function requireDressing(input: DesignBriefInput, axes: BriefAxes): void { /** * The rooms of a building the brief designs: an open form owes one entry per room, each with its - * own distinct line, and rooms of one use are not copies of one another. Anything subtler than a - * word-for-word copy is a finding at the end of the turn, not a refusal here. + * own distinct line, and rooms of one use are not copies of one another. */ function requireRooms(input: DesignBriefInput, axes: BriefAxes): void { const rooms = input.rooms ?? [] diff --git a/packages/core/src/agent-operations/design-facade.test.ts b/packages/core/src/agent-operations/design-facade.test.ts deleted file mode 100644 index 30837faead..0000000000 --- a/packages/core/src/agent-operations/design-facade.test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { FACADE_REVISION_ROWS, facadeBrief } from './__fixtures__/design-facade-cases' -import { facadeRevision } from './design-facade' - -describe('a facade revised within the turn', () => { - test.each(FACADE_REVISION_ROWS)('$name', ({ first, latest, plainer }) => { - expect(facadeRevision(first, facadeBrief(latest)) !== null).toBe(plainer) - }) -}) diff --git a/packages/core/src/agent-operations/design-facade.ts b/packages/core/src/agent-operations/design-facade.ts deleted file mode 100644 index 580c6f233f..0000000000 --- a/packages/core/src/agent-operations/design-facade.ts +++ /dev/null @@ -1,84 +0,0 @@ -import type { DesignBrief, Treatment } from '../agent-tools/design-brief' - -/** - * The facade a brief states, in words, and a later brief of the turn against the first. The brief's - * `facade` axis states a treatment (the material families it is clad in, its bands, what else it - * carries, the rhythm of its openings); a later brief that states a plainer one is a fact to show. - * Reading what the building has against it is the facade tools' own, and not here. It never - * refuses a write. - */ - -type Cladding = NonNullable[number] -type Element = NonNullable[number] - -const CLADDING_WORDS: Record = { - brick: 'brick', - stone: 'stone', - render: 'render', - siding: 'siding', - wood: 'wood', - metal: 'metal', -} - -const ELEMENT_WORDS: Record = { - corners: 'corner chains', - surrounds: 'opening surrounds', - shutters: 'shutters', - balconies: 'balconies', - entrance: 'an entrance unit', - 'curtain-wall': 'curtain-wall glazing', - porch: 'a porch', - guard: 'guards', - posts: 'posts', -} - -const list = (words: string[]) => - words.length > 1 ? `${words.slice(0, -1).join(', ')} and ${words.at(-1)}` : (words[0] ?? '') - -/** A treatment in words: "brick cladding, base and cornice bands, shutters and a regular rhythm". */ -function treatmentWords(treatment: Treatment): string { - return list( - [ - treatment.cladding?.length - ? `${list(treatment.cladding.map((family) => CLADDING_WORDS[family]))} cladding` - : null, - treatment.bands?.length - ? `${list(treatment.bands)} ${treatment.bands.length === 1 ? 'band' : 'bands'}` - : null, - ...(treatment.elements ?? []).map((element) => ELEMENT_WORDS[element]), - treatment.rhythm ? `a ${treatment.rhythm} rhythm` : null, - ].filter((part): part is string => part !== null), - ) -} - -/** What a treatment asks of a facade: one for each family, band and element, one for a regular rhythm. */ -const demands = (treatment: Treatment) => - (treatment.cladding?.length ?? 0) + - (treatment.bands?.length ?? 0) + - (treatment.elements?.length ?? 0) + - (treatment.rhythm === 'regular' ? 1 : 0) - -export type FacadeRevision = { - code: 'facade_revised_simpler' - message: string - /** A facade finding informs: the brief is free to revise, and what the building has is the facade tools' to say. */ - severity: 'info' -} - -/** - * The finding where a later brief of the turn states a plainer treatment than the first one did: - * it asks for fewer families, bands, elements, or a free rhythm for a regular one. A brief is free - * to revise, so this is a fact to show. Null when either brief states no treatment. - */ -export function facadeRevision( - first: Treatment | undefined, - brief: Pick | null | undefined, -): FacadeRevision | null { - const latest = brief?.axes?.facade?.treatment - if (!(first && latest) || demands(latest) >= demands(first)) return null - return { - code: 'facade_revised_simpler', - severity: 'info', - message: `The facade was revised during the turn: from ${treatmentWords(first)} to ${treatmentWords(latest) || 'no stated treatment'}.`, - } -} diff --git a/packages/core/src/agent-operations/design-form.test.ts b/packages/core/src/agent-operations/design-form.test.ts deleted file mode 100644 index 05ce02eae3..0000000000 --- a/packages/core/src/agent-operations/design-form.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { - FORM_ROWS, - formBrief, - massedScene, - REVISION_ROWS, - rect, - U_BUILT, -} from './__fixtures__/design-form-cases' -import { formFinding, formRevision } from './design-form' -import { EMPTY_SESSION, keepInSession, parseSessionRecord } from './scene-checkpoint' -import type { SceneNodes } from './types' - -describe('the form a brief states against the volumes built', () => { - test.each(FORM_ROWS)('$name', ({ scene, massing, differs }) => { - const finding = formFinding(formBrief(massing), scene.nodes as SceneNodes) - expect(finding?.differs ?? []).toEqual(differs) - expect(finding?.code ?? 'form_simpler_than_brief').toBe('form_simpler_than_brief') - }) - - test('no brief, and a brief stored before the form axis, have nothing to compare', () => { - const nodes = U_BUILT.nodes as SceneNodes - expect(formFinding(null, nodes)).toBeNull() - expect(formFinding(undefined, nodes)).toBeNull() - expect(formFinding({ axes: {} }, nodes)).toBeNull() - }) - - test('a scene the massing cannot be read from has no finding, and no throw', () => { - const scene = massedScene({ name: 'House', polygon: rect(0, 0, 12, 9), shape: 'rectangle' }) - const broken = { - ...scene.nodes, - zone_House_0: { ...(scene.nodes.zone_House_0 as object), polygon: undefined }, - } - expect( - formFinding(formBrief({ plan: 'u', volumes: 3, heights: 'several' }), broken as SceneNodes), - ).toBeNull() - }) -}) - -describe('a form revised within the turn', () => { - test.each(REVISION_ROWS)('$name', ({ first, latest, differs }) => { - const revision = formRevision(first, formBrief(latest)) - expect(revision?.differs ?? []).toEqual(differs) - }) - - test('the first massing the turn stated stays while later briefs replace the brief', () => { - const U = { plan: 'u', volumes: 3, heights: 'several' } as const - const box = { plan: 'rectangle', volumes: 1, heights: 'one' } as const - const first = keepInSession(EMPTY_SESSION, { designBrief: formBrief(U) }) - expect(first.firstMassing).toEqual(U) - const revised = keepInSession(first, { designBrief: formBrief(box) }) - expect(revised.firstMassing).toEqual(U) - expect(revised.designBrief?.axes?.form?.massing).toEqual(box) - expect(keepInSession(revised, { made: [] }).firstMassing).toEqual(U) - }) - - test('it goes with the brief: taking the brief away clears it, and the next turn starts anew', () => { - const U = { plan: 'u', volumes: 3, heights: 'several' } as const - const box = { plan: 'rectangle', volumes: 1, heights: 'one' } as const - const kept = keepInSession(EMPTY_SESSION, { designBrief: formBrief(U) }) - const cleared = keepInSession(kept, { designBrief: null }) - expect(cleared.firstMassing).toBeUndefined() - expect(keepInSession(cleared, { designBrief: formBrief(box) }).firstMassing).toEqual(box) - }) - - test('a first brief that states no massing sets none; the first one that states one does', () => { - const none = keepInSession(EMPTY_SESSION, { designBrief: formBrief(undefined) }) - expect(none.firstMassing).toBeUndefined() - const box = { plan: 'rectangle', volumes: 1, heights: 'one' } as const - expect(keepInSession(none, { designBrief: formBrief(box) }).firstMassing).toEqual(box) - }) - - test('it is kept with the session record, and a record without it still reads', () => { - const U = { plan: 'u', volumes: 3, heights: 'several' } as const - const kept = keepInSession(EMPTY_SESSION, { designBrief: formBrief(U) }) - expect(parseSessionRecord(JSON.parse(JSON.stringify(kept))).firstMassing).toEqual(U) - const { firstMassing: _first, ...older } = kept - expect(parseSessionRecord(older).designBrief).toBeDefined() - }) -}) diff --git a/packages/core/src/agent-operations/design-form.ts b/packages/core/src/agent-operations/design-form.ts deleted file mode 100644 index af8573209f..0000000000 --- a/packages/core/src/agent-operations/design-form.ts +++ /dev/null @@ -1,341 +0,0 @@ -import type { DesignBrief, FormPlan, Massing } from '../agent-tools/design-brief' -import { type Ring, union } from '../lib/polygon-boolean' -import type { AnyNode, AnyNodeId } from '../schema' -import { isLevelBelowGrade } from '../services/storey' -import { type MassingBuilding, readMassing } from './massing-read' -import { queryNodes } from './scene-queries' -import type { SceneNodes } from './types' - -/** - * The form a brief states against the volumes the scene has. The brief's `form` axis states a - * massing (a plan shape, a number of volumes, one height or several); this reads the building - * back through the volumes its rooms form and their footprints, and reports a finding only - * where the scene is plainer than the brief says. It never refuses a write, and a form that - * states no massing is not compared. - */ - -/** Tops of volumes within this (m) stand at one height. */ -const SAME_HEIGHT = 0.3 -/** A turn of less than this (sine of the angle) is a straight run, not a corner. */ -const STRAIGHT = 0.0175 -/** An edge within this many degrees of the building's own axes is not angled. */ -const ANGLED_DEGREES = 1 - -/** What the footprints of the above-grade rooms, seen from above, make of the plan. */ -type PlanFacts = { - /** Separate masses: footprints that share no edge. */ - components: number - /** Corners of the outlines, straight runs not counted. */ - corners: number - /** Re-entrant corners of the outlines: 1 for an L, 2 for a U or a T, 4 for an H. */ - reflex: number - /** Open courts: holes in the footprints' union. */ - holes: number - /** An outline edge that runs at an angle to the others. */ - angled: boolean -} - -const PLAN_WORDS: Record = { - rectangle: 'a rectangle', - l: 'an L', - u: 'a U', - t: 'a T', - h: 'an H', - courtyard: 'rooms around an open court', - wing: 'a wing at an angle', - bay: 'a bay with corners cut at 45°', - polygon: 'a free outline', - detached: 'volumes standing apart', -} - -/** - * What each plan needs of the built footprints at least: a rectangle nothing; the letters their - * re-entrant corners (or a court, which closes what they leave open); a court its hole; a wing or - * a bay an edge at an angle; a free outline anything but one plain rectangle; detached two masses. - */ -const PLAN_MET: Record boolean> = { - rectangle: () => true, - l: (plan) => plan.reflex >= 1 || plan.holes >= 1, - t: (plan) => plan.reflex >= 2 || plan.holes >= 1, - u: (plan) => plan.reflex >= 2 || plan.holes >= 1, - h: (plan) => plan.reflex >= 4 || plan.holes >= 1, - courtyard: (plan) => plan.holes >= 1, - wing: (plan) => plan.angled, - bay: (plan) => plan.angled, - polygon: (plan) => plan.corners > 4 || plan.angled || plan.components > 1, - detached: (plan) => plan.components >= 2, -} - -/** What `PLAN_MET` asks of the footprints, in words: how a finding says what the built plan lacks. */ -const PLAN_NEEDS: Record = { - rectangle: 'nothing', - l: 'a re-entrant corner or a court', - t: '2 re-entrant corners or a court', - u: '2 re-entrant corners or a court', - h: '4 re-entrant corners or a court', - courtyard: 'an open court', - wing: 'an edge at an angle', - bay: 'an edge at an angle', - polygon: 'more than 4 corners, an angled edge or separate masses', - detached: '2 separate masses', -} - -const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}` - -/** A stated massing in words: "a U, 3 volumes, at different heights". */ -const statedWords = (massing: Massing) => - [ - massing.plan ? PLAN_WORDS[massing.plan] : null, - massing.volumes !== undefined ? plural(massing.volumes, 'volume') : null, - massing.heights === 'several' ? 'at different heights' : null, - ] - .filter(Boolean) - .join(', ') - -/** How much a plan asks of the scene, for telling a revised form plainer: the letters by their notches, a court the most. */ -const PLAN_RANK: Record = { - rectangle: 0, - bay: 1, - wing: 1, - polygon: 1, - detached: 1, - l: 2, - t: 3, - u: 3, - h: 4, - courtyard: 4, -} - -const unit = ([x, z]: readonly [number, number], [nx, nz]: readonly [number, number]) => { - const length = Math.hypot(nx - x, nz - z) || 1 - return [(nx - x) / length, (nz - z) / length] as const -} - -/** The shoelace sum: positive when the ring runs one way round, negative the other. */ -const winding = (ring: Ring) => - ring.reduce((sum, [x, z], i) => { - const [nx, nz] = ring[(i + 1) % ring.length]! - return sum + (x * nz - nx * z) - }, 0) - -function planFacts(footprints: Ring[]): PlanFacts { - const shapes = union(footprints) - const rings = shapes.map((shape) => shape.outer) - let corners = 0 - let reflex = 0 - let longest = { length: 0, angle: 0 } - const angles: number[] = [] - for (const ring of rings) { - const sign = Math.sign(winding(ring)) - ring.forEach((point, i) => { - const before = ring[(i + ring.length - 1) % ring.length]! - const after = ring[(i + 1) % ring.length]! - const [ax, az] = unit(before, point) - const [bx, bz] = unit(point, after) - const turn = ax * bz - az * bx - if (Math.abs(turn) <= STRAIGHT) return - corners++ - if (Math.sign(turn) !== sign) reflex++ - }) - ring.forEach(([x, z], i) => { - const [nx, nz] = ring[(i + 1) % ring.length]! - const length = Math.hypot(nx - x, nz - z) - const angle = (Math.atan2(nz - z, nx - x) * 180) / Math.PI - angles.push(angle) - if (length > longest.length) longest = { length, angle } - }) - } - const angled = angles.some((angle) => { - const off = (((angle - longest.angle) % 90) + 90) % 90 - return Math.min(off, 90 - off) > ANGLED_DEGREES - }) - return { - components: rings.length, - corners, - reflex, - holes: shapes.reduce((sum, shape) => sum + shape.holes.length, 0), - angled, - } -} - -export type BuiltForm = { - /** The building read: the one with the most floor above grade. */ - buildingId: string - volumes: number - shapes: string[] - /** The volumes the building's rooms form, each with its shape and top. */ - named: { name: string; shape: string; topM: number }[] - plan: PlanFacts - /** Highest and lowest top of a volume in the building's stack (m). */ - tops: [number, number] -} - -/** The building the brief is read against: the one with the most floor above grade, its above-grade volumes. */ -export function builtForm(nodes: SceneNodes): BuiltForm | null { - const above = (building: MassingBuilding) => - building.volumes.flatMap((volume) => { - const storeys = volume.storeyFootprints.filter( - (storey) => !isLevelBelowGrade(nodes as Record, storey.levelId), - ) - return storeys.length ? [{ volume, storeys }] : [] - }) - const footprint = (volumes: ReturnType) => - volumes.flatMap(({ storeys }) => - storeys.flatMap((storey) => - storey.zoneIds.flatMap((id) => { - const zone = nodes[id] - return zone?.type === 'zone' ? [zone.polygon as Ring] : [] - }), - ), - ) - const [main] = readMassing(nodes) - .map((building) => { - const volumes = above(building) - return { - buildingId: building.buildingId, - volumes, - footprints: footprint(volumes), - ground: volumes.reduce( - (sum, { storeys }) => - sum + storeys.reduce((total, storey) => total + storey.areaSqMeters, 0), - 0, - ), - } - }) - .filter(({ footprints }) => footprints.length > 0) - .sort((a, b) => b.ground - a.ground) - if (!main) return null - const tops = main.volumes.map(({ volume }) => volume.topElevationMeters) - return { - buildingId: main.buildingId, - volumes: main.volumes.length, - shapes: main.volumes.map(({ volume }) => volume.shape ?? 'inferred'), - named: main.volumes.map(({ volume }) => ({ - name: String(volume.name), - shape: volume.shape ?? 'inferred', - topM: volume.topElevationMeters, - })), - plan: planFacts(main.footprints), - tops: [Math.max(...tops), Math.min(...tops)], - } -} - -const planWords = (plan: PlanFacts) => - [ - plan.reflex ? plural(plan.reflex, 're-entrant corner') : 'no re-entrant corner', - ...(plan.holes ? [plural(plan.holes, 'court')] : []), - ...(plan.angled ? ['edges at an angle'] : []), - ...(plan.components > 1 ? [`${plan.components} separate masses`] : []), - ].join(', ') - -/** A scene the massing cannot be read from (a room stored without its polygon) says nothing here: verify_scene lists what is wrong with it. */ -function readable(read: () => T): T | null { - try { - return read() - } catch { - return null - } -} - -/** - * The building the brief is read against: the one with the most floor above grade, else the first - * building the scene has. The facade is read on it as the form is. - */ -export function mainBuildingId(nodes: SceneNodes): string | undefined { - return ( - readable(() => builtForm(nodes))?.buildingId ?? queryNodes(nodes, { type: 'building' })[0]?.id - ) -} - -export type FormFinding = { - code: 'form_simpler_than_brief' - message: string - /** What differs: volumes, plan, heights. */ - differs: ('volumes' | 'plan' | 'heights')[] -} - -/** - * The finding where the built form is plainer than the brief's stated massing: fewer volumes, - * a plan that lacks what the stated plan needs, one height where several are stated. Null when - * the brief states no massing, nothing above grade is built, or the scene holds up what is stated. - */ -export function formFinding( - brief: Pick | null | undefined, - nodes: SceneNodes, -): FormFinding | null { - const stated: Massing | undefined = brief?.axes?.form?.massing - if (!stated) return null - const built = readable(() => builtForm(nodes)) - if (!built) return null - const differs: FormFinding['differs'] = [] - if (stated.volumes !== undefined && built.volumes < stated.volumes) differs.push('volumes') - if (stated.plan !== undefined && !PLAN_MET[stated.plan](built.plan)) differs.push('plan') - const spread = built.tops[0] - built.tops[1] - if (stated.heights === 'several' && spread <= SAME_HEIGHT) differs.push('heights') - if (!differs.length) return null - const has = [ - `${plural(built.volumes, 'volume')} (${built.shapes.join(', ')})`, - `a plan with ${planWords(built.plan)}`, - spread <= SAME_HEIGHT - ? `one height (${built.tops[0].toFixed(1)} m)` - : `heights from ${built.tops[1].toFixed(1)} to ${built.tops[0].toFixed(1)} m`, - ].join(', ') - const lacking = differs.map((axis) => lackWords(axis, stated, built)).join('; ') - return { - code: 'form_simpler_than_brief', - message: `The brief states a form of ${statedWords(stated)}; the scene has ${has}. Compared on building ${built.buildingId}: ${lacking}. Either the scene or the brief's form changes: a new design_brief replaces the form.`, - differs, - } -} - -/** One differing axis as stated against built, with the numbers and the volumes that stand. */ -function lackWords( - axis: FormFinding['differs'][number], - stated: Massing, - built: BuiltForm, -): string { - if (axis === 'volumes') { - const standing = built.named - .map(({ name, shape, topM }) => `${name} (${shape}, top ${topM.toFixed(1)} m)`) - .join(', ') - const missing = (stated.volumes ?? 0) - built.volumes - return `volumes: ${stated.volumes} stated, ${built.volumes} built (${standing}), ${missing} missing` - } - if (axis === 'plan' && stated.plan) - return `plan: ${PLAN_WORDS[stated.plan]} needs ${PLAN_NEEDS[stated.plan]}, the footprints have ${planWords(built.plan)}` - return `heights: several stated, every volume tops out at ${built.tops[0].toFixed(1)} m` -} - -export type FormRevision = { - code: 'form_revised_simpler' - message: string - /** What the later form asks less of: volumes, plan, heights. */ - differs: ('volumes' | 'plan' | 'heights')[] -} - -/** - * The finding where a later brief of the turn states a plainer massing than the first one did: - * fewer volumes, a plan lower on the ladder (a letter, a court or an angle for a rectangle), one - * height for several. A brief is free to revise, so this is a fact to show, not a refusal. Null - * when either brief states no massing (a form bounded by the person's words has none to compare), - * or the later one asks as much. - */ -export function formRevision( - first: Massing | undefined, - brief: Pick | null | undefined, -): FormRevision | null { - const latest: Massing | undefined = brief?.axes?.form?.massing - if (!(first && latest)) return null - const differs: FormRevision['differs'] = [] - if (first.volumes !== undefined && latest.volumes !== undefined && latest.volumes < first.volumes) - differs.push('volumes') - if (first.plan && latest.plan && PLAN_RANK[latest.plan] < PLAN_RANK[first.plan]) - differs.push('plan') - if (first.heights === 'several' && latest.heights === 'one') differs.push('heights') - if (!differs.length) return null - return { - code: 'form_revised_simpler', - message: `The form was revised during the turn: from ${statedWords(first)} to ${statedWords(latest)}.`, - differs, - } -} diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index ec36515f6b..d0de29b6d4 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -11,7 +11,6 @@ import { createRoof } from './create-roof' import { createRoom } from './create-room' import { createStair } from './create-stair' import { deleteNode } from './delete-node' -import './brief-findings' import { designBrief, gatedByBrief } from './design-brief' import { placeDesign, validateDesignOperation } from './designs' import { duplicateLevel } from './duplicate-level' @@ -54,8 +53,6 @@ export * from './apply-outcome' export * from './author-scene' export * from './author-scene-checks' export * from './authored-scene-merge' -export * from './brief-findings' -export * from './brief-gaps' export * from './collections' export * from './corner-window' export * from './create-roof' @@ -63,8 +60,6 @@ export * from './create-room' export * from './create-stair' export * from './delete-node' export * from './design-brief' -export * from './design-facade' -export * from './design-form' export * from './designs' export * from './door-clearance' export * from './duplicate-level' diff --git a/packages/core/src/agent-operations/massing-read.ts b/packages/core/src/agent-operations/massing-read.ts deleted file mode 100644 index 88a5d35197..0000000000 --- a/packages/core/src/agent-operations/massing-read.ts +++ /dev/null @@ -1,320 +0,0 @@ -import type { VOLUME_SHAPES } from '../agent-tools/design-brief' -import { refuse } from '../agent-tools/refusal' -import { type AnyNode, getActiveRoofHeight, type RoofNode } from '../schema' -import { DEFAULT_LEVEL_HEIGHT } from '../services/level-height' -import { getLevelElevations } from '../services/storey' -import { pointInPolygon, polygonArea, polygonBounds, type Vec2 } from './plan-geometry' -import { levelRole, levelsOf, queryNodes } from './scene-queries' -import type { SceneNodes } from './types' - -type Pt = [number, number] - -type Shape = (typeof VOLUME_SHAPES)[number] - -const round2 = (value: number) => Math.round(value * 100) / 100 - -const boundsOf = (polygons: readonly (readonly Pt[])[]) => { - const all = polygons.flatMap((polygon) => polygon.map((point) => point as Vec2)) - const { width: _w, depth: _d, centerX: _x, centerZ: _z, ...bounds } = polygonBounds(all) - return { - minX: round2(bounds.minX), - maxX: round2(bounds.maxX), - minZ: round2(bounds.minZ), - maxZ: round2(bounds.maxZ), - } -} - -function segmentsMeet(a: Pt, b: Pt, c: Pt, d: Pt, proper: boolean): boolean { - const cross = (p: Pt, q: Pt, r: Pt) => - (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) - const d1 = cross(c, d, a) - const d2 = cross(c, d, b) - const d3 = cross(a, b, c) - const d4 = cross(a, b, d) - if (proper) - return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0)) - const on = (p: Pt, q: Pt, r: Pt) => - Math.abs(cross(p, q, r)) < 1e-9 && - r[0] >= Math.min(p[0], q[0]) - 1e-9 && - r[0] <= Math.max(p[0], q[0]) + 1e-9 && - r[1] >= Math.min(p[1], q[1]) - 1e-9 && - r[1] <= Math.max(p[1], q[1]) + 1e-9 - if ( - ((d1 >= 0 && d2 <= 0) || (d1 <= 0 && d2 >= 0)) && - ((d3 >= 0 && d4 <= 0) || (d3 <= 0 && d4 >= 0)) - ) - return true - return on(c, d, a) || on(c, d, b) || on(a, b, c) || on(a, b, d) -} - -function eachEdge(polygon: readonly Pt[], fn: (a: Pt, b: Pt) => boolean): boolean { - for (let i = 0; i < polygon.length; i++) - if (fn(polygon[i]!, polygon[(i + 1) % polygon.length]!)) return true - return false -} - -/** Area overlap: a corner strictly inside the other, or edges crossing. A shared edge is not overlap. */ - -/** Area overlap: a corner strictly inside the other, or edges crossing. A shared edge is not overlap. */ -export function polygonsOverlap(a: readonly Pt[], b: readonly Pt[]): boolean { - const ab = polygonBounds(a as Vec2[]) - const bb = polygonBounds(b as Vec2[]) - if (ab.maxX <= bb.minX || bb.maxX <= ab.minX || ab.maxZ <= bb.minZ || bb.maxZ <= ab.minZ) - return false - if (a.some((point) => pointInPolygon(point as Vec2, b as Vec2[], false))) return true - if (b.some((point) => pointInPolygon(point as Vec2, a as Vec2[], false))) return true - return eachEdge(a, (a1, a2) => eachEdge(b, (b1, b2) => segmentsMeet(a1, a2, b1, b2, true))) -} - -/** Overlap, or contact: a corner on the other's boundary, or edges meeting at all. */ - -/** Overlap, or contact: a corner on the other's boundary, or edges meeting at all. */ -export function polygonsTouch(a: readonly Pt[], b: readonly Pt[]): boolean { - if (polygonsOverlap(a, b)) return true - const ab = polygonBounds(a as Vec2[]) - const bb = polygonBounds(b as Vec2[]) - if ( - ab.maxX < bb.minX - 1e-9 || - bb.maxX < ab.minX - 1e-9 || - ab.maxZ < bb.minZ - 1e-9 || - bb.maxZ < ab.minZ - 1e-9 - ) - return false - if (a.some((point) => pointInPolygon(point as Vec2, b as Vec2[], true))) return true - if (b.some((point) => pointInPolygon(point as Vec2, a as Vec2[], true))) return true - return eachEdge(a, (a1, a2) => eachEdge(b, (b1, b2) => segmentsMeet(a1, a2, b1, b2, false))) -} - -const buildingLevelsOf = (nodes: SceneNodes, buildingId: string) => - levelsOf(nodes).filter((level) => level.parentId === buildingId) - -const occupiedOf = (nodes: SceneNodes, buildingId: string) => - buildingLevelsOf(nodes, buildingId).filter((level) => levelRole(nodes, level).role === 'occupied') - -type VolumeMeta = { - id: string - name: string - shape: Shape - storeyIndex: number - partIndex: number - court?: boolean - setbackMeters?: number - cantileverMeters?: number - cantileverSupport?: string - courtPolygon?: Pt[] -} - -type ZoneLike = AnyNode & { type: 'zone'; polygon: Pt[] } - -const volumeMetaOf = (node: AnyNode): VolumeMeta | null => { - const meta = (node as { metadata?: Record }).metadata?.volume - if (!meta || typeof meta !== 'object') return null - const volume = meta as VolumeMeta - return typeof volume.id === 'string' ? volume : null -} - -function roofFacts(nodes: SceneNodes, roof: AnyNode) { - const childIds = (roof as { children?: string[] }).children ?? [] - const segs = childIds - .map((id: string) => nodes[id]) - .filter((node: AnyNode | undefined) => node?.type === 'roof-segment') as (AnyNode & { - roofType?: string - pitch?: number - })[] - return { - roofIds: [roof.id], - types: [...new Set(segs.map((segment) => segment.roofType ?? 'gable'))], - pitches: [...new Set(segs.map((segment) => segment.pitch ?? 40))], - segmentIds: segs.map((segment) => segment.id), - heightMeters: segs.length - ? round2(Math.max(...segs.map((segment) => getActiveRoofHeight(segment as never)))) - : 0, - } -} - -/** - * The building as volumes. Tagged rooms report their recorded volume; the rest are grouped by - * touching footprints on a level and overlapping footprints between levels, and marked inferred. - */ -export function readMassing(nodes: SceneNodes, buildingId?: string) { - const buildings = queryNodes(nodes, { type: 'building' }).filter( - (node) => !buildingId || node.id === buildingId, - ) - if (buildingId && !buildings.length) - refuse('building_not_found', `Building not found: ${buildingId}.`, { buildingId }) - const elevations = getLevelElevations(nodes as Record) as Map< - string, - { baseY: number; height: number } - > - - const describeBuilding = (building: AnyNode) => { - const occupied = occupiedOf(nodes, building.id) - const levelIndex = new Map( - occupied.map((level, index) => [level.id as string, index]), - ) - const zones = queryNodes(nodes, { type: 'zone' }).filter( - (node) => !!node.parentId && levelIndex.has(node.parentId), - ) - const roofs = queryNodes(nodes, { type: 'roof' }) - - type Group = { zones: ZoneLike[]; meta: VolumeMeta | null } - const groups: Group[] = [] - const tagged = new Map() - const untagged: ZoneLike[] = [] - for (const zone of zones) { - const meta = volumeMetaOf(zone) - if (!meta) { - untagged.push(zone) - continue - } - const group = tagged.get(meta.id) ?? { zones: [], meta } - group.zones.push(zone) - tagged.set(meta.id, group) - } - groups.push(...tagged.values()) - const parent = untagged.map((_, i) => i) - const find = (i: number): number => { - let root = i - while (parent[root] !== root) root = parent[root]! - return root - } - for (let i = 0; i < untagged.length; i++) - for (let j = i + 1; j < untagged.length; j++) { - const a = untagged[i]! - const b = untagged[j]! - const la = levelIndex.get(a.parentId!)! - const lb = levelIndex.get(b.parentId!)! - const linked = - la === lb - ? polygonsTouch(a.polygon, b.polygon) - : Math.abs(la - lb) === 1 && polygonsOverlap(a.polygon, b.polygon) - if (linked) parent[find(i)] = find(j) - } - const inferred = new Map() - untagged.forEach((zone, i) => { - const root = find(i) - inferred.set(root, [...(inferred.get(root) ?? []), zone]) - }) - for (const groupZones of inferred.values()) groups.push({ zones: groupZones, meta: null }) - - const volumes = groups.map((group, groupOrder) => { - const byLevel = new Map() - for (const zone of group.zones) { - if (volumeMetaOf(zone)?.court) continue - byLevel.set(zone.parentId!, [...(byLevel.get(zone.parentId!) ?? []), zone]) - } - const levelIds = [...byLevel.keys()].sort((a, b) => levelIndex.get(a)! - levelIndex.get(b)!) - const storeyFootprints = levelIds.map((levelId) => { - const levelZones = byLevel.get(levelId)! - return { - levelId, - levelIndex: levelIndex.get(levelId)!, - heightMeters: round2(elevations.get(levelId)?.height ?? DEFAULT_LEVEL_HEIGHT), - baseElevationMeters: round2(elevations.get(levelId)?.baseY ?? 0), - areaSqMeters: round2( - levelZones.reduce((sum, zone) => sum + polygonArea(zone.polygon as Vec2[]), 0), - ), - bounds: boundsOf(levelZones.map((zone) => zone.polygon)), - zoneIds: levelZones.map((zone) => zone.id), - } - }) - const topLevelId = levelIds.at(-1)! - const topPolygons = byLevel.get(topLevelId)!.map((zone) => zone.polygon) - const volumeId = group.meta?.id ?? `inferred_${building.id}_${groupOrder}` - const ownRoof = - roofs.find( - (roof) => - (roof as { metadata?: Record }).metadata?.volumeId === volumeId, - ) ?? - roofs.find((roof) => { - const [x, , z] = (roof.position as number[]) ?? [] - if (x === undefined || z === undefined) return false - const reference = (roof as { metadata?: Record }).metadata - ?.referenceLevelId - const levelMatch = roof.parentId === topLevelId || reference === topLevelId - return ( - levelMatch && - topPolygons.some((polygon) => pointInPolygon([x, z], polygon as Vec2[], true)) - ) - }) - const courtPolygon = group.zones - .map(volumeMetaOf) - .find((meta) => meta?.courtPolygon)?.courtPolygon - let setbackMeters = group.meta?.setbackMeters ?? null - let cantilever = group.meta?.cantileverMeters - ? { meters: group.meta.cantileverMeters, support: group.meta.cantileverSupport ?? null } - : null - if (!group.meta && storeyFootprints.length > 1) { - const ground = storeyFootprints[0]!.bounds - const upper = storeyFootprints.at(-1)!.bounds - const insets = [ - upper.minX - ground.minX, - ground.maxX - upper.maxX, - upper.minZ - ground.minZ, - ground.maxZ - upper.maxZ, - ] - if (insets.every((inset) => inset > 0.05)) setbackMeters = round2(Math.min(...insets)) - else if (insets.some((inset) => inset < -0.05)) - cantilever = { meters: round2(-Math.min(...insets)), support: null } - } - return { - volumeId, - name: group.meta?.name ?? group.zones[0]?.name ?? volumeId, - shape: group.meta?.shape ?? null, - source: group.meta ? ('tagged' as const) : ('inferred' as const), - storeys: levelIds.length, - baseLevelIndex: levelIndex.get(levelIds[0]!)!, - totalHeightMeters: round2( - storeyFootprints.reduce((sum, storey) => sum + storey.heightMeters, 0), - ), - topElevationMeters: round2( - (elevations.get(topLevelId)?.baseY ?? 0) + - (elevations.get(topLevelId)?.height ?? DEFAULT_LEVEL_HEIGHT), - ), - storeyFootprints, - roof: ownRoof ? roofFacts(nodes, ownRoof) : null, - court: courtPolygon - ? { - polygon: courtPolygon, - areaSqMeters: round2(polygonArea(courtPolygon as Vec2[])), - bounds: boundsOf([courtPolygon]), - } - : null, - setbackMeters, - cantilever, - attachedTo: [] as string[], - } - }) - const groundPolygons = volumes.map((volume) => { - const first = volume.storeyFootprints[0]! - return first.zoneIds.map((id) => (nodes[id] as ZoneLike).polygon) - }) - volumes.forEach((volume, i) => { - volume.attachedTo = volumes - .filter( - (other, j) => - i !== j && - other.baseLevelIndex === volume.baseLevelIndex && - groundPolygons[i]!.some((a) => groundPolygons[j]!.some((b) => polygonsTouch(a, b))), - ) - .map((other) => other.volumeId) - }) - volumes.sort( - (a, b) => - b.storeys - a.storeys || - b.storeyFootprints[0]!.areaSqMeters - a.storeyFootprints[0]!.areaSqMeters || - a.storeyFootprints[0]!.bounds.minX - b.storeyFootprints[0]!.bounds.minX || - a.storeyFootprints[0]!.bounds.minZ - b.storeyFootprints[0]!.bounds.minZ || - String(a.name).localeCompare(String(b.name)), - ) - return { - buildingId: building.id, - buildingName: building.name ?? null, - volumes, - } - } - - return buildings.map(describeBuilding) -} - -export type MassingBuilding = ReturnType[number] diff --git a/packages/core/src/agent-operations/room-dressing.test.ts b/packages/core/src/agent-operations/room-dressing.test.ts deleted file mode 100644 index 45c2ab0bf3..0000000000 --- a/packages/core/src/agent-operations/room-dressing.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { dressingBrief, salonBrief } from './__fixtures__/room-dressing-cases' -import { briefRevisions } from './brief-findings' -import { announcedDressing, dressingRevision } from './room-dressing' - -describe('the dressing announced for each room, and revised within the turn', () => { - const first = announcedDressing(salonBrief(['wainscot', 'chairRail', 'crown'])) - test('is kept by the room’s folded name, and only for rooms that announce one', () => { - expect(first).toEqual({ salon: ['wainscot', 'chairRail', 'crown'] }) - expect(announcedDressing(salonBrief())).toEqual({}) - }) - - test.each([ - ['fewer kinds', salonBrief(['wainscot']), true], - ['the same', salonBrief(['wainscot', 'chairRail', 'crown']), false], - ['more', salonBrief(['wainscot', 'chairRail', 'crown', 'accent']), false], - ['a different set of the same size', salonBrief(['wainscot', 'chairRail', 'accent']), true], - ['none stated for the room', salonBrief(), true], - ['the room taken out of the brief', dressingBrief(), false], - ])('%s', (_, latest, plainer) => { - expect(dressingRevision(first, latest) !== null).toBe(plainer) - }) - - test('a first brief that announced none has nothing to revise, and the revision joins the others', () => { - expect(dressingRevision(undefined, salonBrief(['wainscot']))).toBeNull() - expect( - briefRevisions({ - designBrief: salonBrief(['wainscot']), - firstDressing: first, - }).map((finding) => finding.code), - ).toEqual(['room_dressing_revised_simpler']) - }) -}) diff --git a/packages/core/src/agent-operations/room-dressing.ts b/packages/core/src/agent-operations/room-dressing.ts deleted file mode 100644 index 40ac48bc5d..0000000000 --- a/packages/core/src/agent-operations/room-dressing.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { DesignBrief, RoomDressing } from '../agent-tools/design-brief' -import { foldRoomName } from '../building/room-use' - -/** - * The dressing each room of a brief announces, and a later brief of the turn against the first: the - * kinds of wall dressing (wainscot, chair rail, tiles to height...) a room is announced with, and - * the finding where a later brief announces less. A brief is free to revise, so it is a fact to - * show. It never refuses a write. - */ - -/** A kind as the brief's words say it, with the article. */ -const NOUNS: Record = { - wainscot: 'a wainscot', - chairRail: 'a chair rail', - crown: 'a crown moulding', - 'tiles-to-height': 'tile part way up the walls', - 'tiles-full': 'tile to the ceiling', - splashback: 'a splashback', - accent: 'an accent wall', -} - -const sentence = (words: readonly string[]) => - words.length < 2 ? words.join('') : `${words.slice(0, -1).join(', ')} and ${words.at(-1)}` - -/** The dressing each room of a brief announces, by the room's folded name. */ -export type AnnouncedDressing = Record - -export function announcedDressing( - brief: Pick | null | undefined, -): AnnouncedDressing { - return Object.fromEntries( - (brief?.rooms ?? []).flatMap((room) => - room.finishes?.dressing?.length - ? [[foldRoomName(room.name), [...room.finishes.dressing]]] - : [], - ), - ) -} - -export type DressingRevision = { code: 'room_dressing_revised_simpler'; message: string } - -/** - * The finding where a later brief of the turn announces less dressing for a room than the first - * did: a kind the first announced for it and the latest no longer does. A brief is free to revise, - * so this is a fact to show. Null when nothing was dropped or the first announced none. - */ -export function dressingRevision( - first: AnnouncedDressing | undefined, - brief: Pick | null | undefined, -): DressingRevision | null { - if (!first) return null - const latest = announcedDressing(brief) - const named = new Map((brief?.rooms ?? []).map((room) => [foldRoomName(room.name), room.name])) - const dropped = Object.entries(first).flatMap(([room, kinds]) => { - if (!named.has(room)) return [] - const lost = kinds.filter((kind) => !latest[room]?.includes(kind)) - return lost.length ? [`${named.get(room)}: ${sentence(lost.map((kind) => NOUNS[kind]))}`] : [] - }) - if (!dropped.length) return null - return { - code: 'room_dressing_revised_simpler', - message: `The rooms' dressing was revised during the turn; the brief no longer announces ${dropped.join('; ')}.`, - } -} diff --git a/packages/core/src/agent-operations/scene-checkpoint.ts b/packages/core/src/agent-operations/scene-checkpoint.ts index c29e08d70d..38a4cbed41 100644 --- a/packages/core/src/agent-operations/scene-checkpoint.ts +++ b/packages/core/src/agent-operations/scene-checkpoint.ts @@ -1,16 +1,7 @@ import { z } from 'zod' -import { - type DesignBrief, - DesignBriefRecord, - type Massing, - massingSchema, - ROOM_DRESSINGS, - type Treatment, - treatmentSchema, -} from '../agent-tools/design-brief' +import { type DesignBrief, DesignBriefRecord } from '../agent-tools/design-brief' import { type AnyNode, isDefaultGutterNode } from '../schema' import { isDerivedNode } from '../store/derived-node-guard' -import { type AnnouncedDressing, announcedDressing } from './room-dressing' import { measureScene, type SceneMeasure } from './scene-measure' import { levelIdOf } from './scene-queries' import type { SceneChanges, SceneNodes } from './types' @@ -45,21 +36,6 @@ export type SessionRecord = { designBrief?: DesignBrief /** The catalog ids view_assets showed: a brief keeps a catalog piece as it is only after one. */ viewed?: string[] - /** - * The first massing a brief stated since the brief was last taken away: a later brief may - * revise the form, and this is what it is read against. Goes with the brief. - */ - firstMassing?: Massing - /** The first facade treatment a brief stated since the brief was last taken away, as the massing is kept. */ - firstTreatment?: Treatment - /** The dressing the first brief announced for each room (by folded name) since the brief was last taken away, as the treatment is kept. */ - firstDressing?: AnnouncedDressing - /** - * How many entries `made` held when the first brief since the brief was last taken away was - * written: what follows was made under it, which is how "the turn built" is told from what the - * thread built before. Goes with the brief. - */ - briefMadeAt?: number /** * What a module read about the scene or the turn when its tool last ran, by the module's own key: * plain JSON, small, opaque here. The module that wrote a key reads it back from @@ -109,17 +85,6 @@ export function keepInSession(session: SessionRecord, keep: SessionKeep): Sessio return true }) const designBrief = 'designBrief' in keep ? keep.designBrief : session.designBrief - const firstMassing = designBrief - ? (session.firstMassing ?? designBrief.axes?.form?.massing) - : undefined - const firstTreatment = designBrief - ? (session.firstTreatment ?? designBrief.axes?.facade?.treatment) - : undefined - const announced = designBrief ? announcedDressing(designBrief) : undefined - const firstDressing = - designBrief && - (session.firstDressing ?? (Object.keys(announced ?? {}).length ? announced : undefined)) - const briefMadeAt = designBrief ? (session.briefMadeAt ?? session.made.length) : undefined const incomingViewed = new Set(keep.viewed ?? []) const viewed = keep.viewed === null @@ -135,10 +100,6 @@ export function keepInSession(session: SessionRecord, keep: SessionKeep): Sessio : session.checkpoints, made: fresh.length ? [...session.made, ...fresh].slice(0, MAX_MADE) : session.made, ...(designBrief ? { designBrief } : {}), - ...(firstMassing ? { firstMassing } : {}), - ...(firstTreatment ? { firstTreatment } : {}), - ...(firstDressing ? { firstDressing } : {}), - ...(briefMadeAt === undefined ? {} : { briefMadeAt }), ...(viewed.length ? { viewed } : {}), ...(readings ? { readings } : {}), } @@ -304,10 +265,6 @@ const Record_ = z.object({ made: z.array(Made).max(MAX_MADE), designBrief: DesignBriefRecord.optional(), viewed: z.array(z.string()).max(MAX_VIEWED).optional(), - firstMassing: massingSchema.optional(), - firstTreatment: treatmentSchema.optional(), - firstDressing: z.record(z.string(), z.array(z.enum(ROOM_DRESSINGS))).optional(), - briefMadeAt: z.number().int().min(0).optional(), // a bag that does not read back costs the session its readings, never its brief or its moments readings: z .record(z.string(), z.unknown()) diff --git a/packages/core/src/agent-tools/design-brief.ts b/packages/core/src/agent-tools/design-brief.ts index ed129dd0b3..47bc440fa8 100644 --- a/packages/core/src/agent-tools/design-brief.ts +++ b/packages/core/src/agent-tools/design-brief.ts @@ -178,7 +178,7 @@ export const FORM_PLANS = [...VOLUME_SHAPES, 'detached'] as const export type FormPlan = (typeof FORM_PLANS)[number] -/** The massing an open form states, field by field: what a scene can be read back against. */ +/** The massing an open form states, field by field. */ export const MASSING_FIELDS = ['plan', 'volumes', 'heights'] as const export const massingSchema = z.object({ @@ -288,9 +288,7 @@ const facadeAxis = z ), treatment: treatmentSchema .optional() - .describe( - `Required: the treatment the design states (${TREATMENT_TERMS}). The building's facade set is read back against it.`, - ), + .describe(`Required: the treatment the design states (${TREATMENT_TERMS}).`), }), ]) .describe( @@ -318,9 +316,7 @@ const formAxis = z .describe(`How the form is designed, at least ${AXIS_DESIGN_MIN_WORDS} words.`), massing: massingSchema .optional() - .describe( - `Required: the massing the design states (${MASSING_TERMS}). The built volumes are read back against it.`, - ), + .describe(`Required: the massing the design states (${MASSING_TERMS}).`), }), ]) .describe( @@ -363,9 +359,9 @@ export const designBriefTool = { Furnishings are placed or made after a brief: ${CATALOG_PLACEMENT_TOOLS.join(', ')} (the catalog's) and ${FURNISHING_CREATION_TOOLS.join(', ')} (the agent's own), also inside run_batch. Before one, search_assets and view_assets read the catalog and every other tool works as usual; rooms, walls, openings and finishes are not furnishings. Bounded and open, in four readings. "a 4 by 5 m bedroom with a double bed, two nightstands, a wardrobe, one window, one door": action, size, form, facade, pieces (as a minimum: those pieces must be there, more may come) and openings bounded, the form and the facade by "a 4 by 5 m bedroom" (one room, no building designed); style, materials, source and dressing open. "add a lamp next to the sofa": action, form, facade and dressing bounded by "add a lamp" (one object in a room that exists, the building and its exterior stand as they are); style open, its design statement saying how this lamp is designed. "a bedroom with only a bed and a lamp": form and facade bounded by "a bedroom", pieces exact and dressing bounded by "only a bed and a lamp"; style and materials open, the bed and the lamp designed, not defaulted. "Build a house": the action bounded only by "a house"; every other axis open, the form, the facade and the dressing included, and rooms with an entry for each room. source open: technical equipment (sanitaryware, kitchen, laundry and climate appliances) and plants are placed from the catalog (place_items, place_in_room), every other catalog piece is made (add_object, place_design), and furnish_room, which places a whole stock set, stays closed. source catalog, brand or existing: place_items, furnish_room and place_in_room are open, and the creation tools stay open for what the catalog lacks. -The form is the building's massing: a plan shape, a number of volumes, and whether the volumes stand at different heights. Open, its design statement says how the building is composed and massing states it: plan (${FORM_PLANS.join(', ')}), volumes (a count) and heights (one or several). Bounded, the person's own words fix the form ("an L-shaped house", "a single-storey bungalow") and massing may state what they fix; a request that builds or changes no building bounds it by its own words, the building standing as it is. Once volumes are built, verify_scene compares them with the massing the brief states and report form_simpler_than_brief where the scene has fewer volumes, a plainer plan or one height where the brief states several; the form is the brief's, so a new design_brief replaces it, and verify_scene reports form_revised_simpler where the replacing form is plainer than the first one the turn stated. -The facade is the exterior identity of the building: its materials, the bands and elements it carries, the rhythm of its openings. Open, its design statement says how the exterior is designed and treatment states it: cladding (${FACADE_CLADDINGS.join(', ')}), bands (${FACADE_BANDS.join(', ')}), elements (${FACADE_ELEMENTS.join(', ')}) and rhythm (${FACADE_RHYTHMS.join(' or ')}: openings stacked storey over storey, or placed one by one). Bounded, the person's own words fix the facade ("une façade en pierre avec volets", "a black timber-clad house") and treatment may state what they fix; a request that builds or changes no building exterior bounds it by its own words, the exterior standing as it is. verify_scene reports facade_revised_simpler where a replacing design_brief states a plainer treatment than the first one of the turn. -rooms lists the rooms the request builds or refits, when it builds or refits more than one (a single-room request or a focused edit carries none; an open form owes them): for each, name (as the scene names the room), use (${ROOM_USES.join(', ')}), distinct (one line: what sets the room apart from the other rooms of its use, who it is for and its character), finishes (floor and walls as short phrases, tiled and skirting as true or false, and dressing when its walls are dressed) and pieces (its main pieces: furniture, fixtures, equipment). Rooms of the same use are distinct rooms, each with its own distinct line. A form bounded by words that fix no plan is compared with nothing: where a turn built under such a brief, verify_scene reports form_bounded_without_plan, naming the words and what was built, and rooms_not_listed where it built two or more rooms under a brief that lists none. +The form is the building's massing: a plan shape, a number of volumes, and whether the volumes stand at different heights. Open, its design statement says how the building is composed and massing states it: plan (${FORM_PLANS.join(', ')}), volumes (a count) and heights (one or several). Bounded, the person's own words fix the form ("an L-shaped house", "a single-storey bungalow") and massing may state what they fix; a request that builds or changes no building bounds it by its own words, the building standing as it is. +The facade is the exterior identity of the building: its materials, the bands and elements it carries, the rhythm of its openings. Open, its design statement says how the exterior is designed and treatment states it: cladding (${FACADE_CLADDINGS.join(', ')}), bands (${FACADE_BANDS.join(', ')}), elements (${FACADE_ELEMENTS.join(', ')}) and rhythm (${FACADE_RHYTHMS.join(' or ')}: openings stacked storey over storey, or placed one by one). Bounded, the person's own words fix the facade ("une façade en pierre avec volets", "a black timber-clad house") and treatment may state what they fix; a request that builds or changes no building exterior bounds it by its own words, the exterior standing as it is. +rooms lists the rooms the request builds or refits, when it builds or refits more than one (a single-room request or a focused edit carries none; an open form owes them): for each, name (as the scene names the room), use (${ROOM_USES.join(', ')}), distinct (one line: what sets the room apart from the other rooms of its use, who it is for and its character), finishes (floor and walls as short phrases, tiled and skirting as true or false, and dressing when its walls are dressed) and pieces (its main pieces: furniture, fixtures, equipment). Rooms of the same use are distinct rooms, each with its own distinct line. Naming a piece (a double bed) states its function; its form, size within reason and finish are open unless the request fixes them. The pieces a request names are what the room must contain, not all it may contain: where the dressing axis is open, beyond states that design layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each a list of pieces or { none: why }, at least ${BEYOND_MIN_LAYERS} of the 8 layers naming pieces; where the dressing is bounded (words that limit the pieces or the action, such as "only", "nothing else", "just"), none in every layer is accepted. The pieces the request names, read as a minimum, do not bound the dressing. The answer hands the pieces back as dressing. A source other than open is set by the request, not chosen: sourceQuote holds the person's own words that name it, at least two words naming a brand (the brief's brand), the catalog or what is already there ("IKEA furniture only", "que du catalogue", "use my existing furniture"); a request that names no source is open. The chat checks the quote against the person's message of the turn, as it checks every bounded axis's quote; over MCP, where there is no message, a source quote must still name the source and is not compared with a request, and an axis quote is not compared either. In the chat a brief lasts for the turn; over MCP it lasts for the session. The next design_brief replaces it. Refused: axis_missing (an axis is absent), axis_quote_not_in_request (a bounded axis's quote is not in the person's message), axis_open_without_design (an open axis without a design statement of at least ${AXIS_DESIGN_MIN_WORDS} words), form_massing_missing (an open form without its massing: plan, volumes, heights), form_massing_inconsistent (one volume stated as detached or at several heights), facade_treatment_missing (an open facade without its treatment: cladding or elements, and rhythm), rooms_missing (an open form with no rooms), room_distinct_missing (a room without its distinct line), rooms_identical (two rooms of one use with the same distinct and the same pieces), dressing_bounded_by_minimum (the dressing bounded by words inside a pieces quote read as a minimum), brand_required (source brand without a brand name), source_quote_required (a source other than open without sourceQuote), source_not_named (the quote names no brand, catalog or existing source), source_not_in_request (the quote is not in the person's message), beyond_too_thin (dressing open, fewer than ${BEYOND_MIN_LAYERS} layers naming pieces).`, diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 477ceb15af..2e4fd0b123 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -1004,11 +1004,6 @@ export const METADATA_REFERENCES: readonly ExistingReference[] = [ dependents: ['metadata.porchPart', 'metadata.porchSeed'], note: "The porch room a post or beam was made for by the structure kernel (lib/porch-framing-sync), which part of its framing and its shape as made; a porch gone takes its parts with it, one edited by hand stays the user's own.", }), - meta('referenceLevelId', { - ...policy('node', 'membership', 'drop', 'strip'), - targetKinds: ['level'], - note: 'The level a roof or roof level was measured from, a level id as the roof writers record it. Read to find the roof a massing volume carries.', - }), ] const described = (reason: string, paths: readonly string[]) => @@ -1091,10 +1086,6 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'Which building code the project follows (`irc-2021`, `au-ncc`, `fr`): a profile name, never a node id. Read by the code-specific usage checks; a scene that does not name one has no jurisdiction.', ['codeProfile'], ), - ...described( - "The massing volume a room or roof belongs to, as a volume tool wrote it: the volume's own id (it names no node), its name, shape and place in the stack. Read to group rooms into the volumes a form is compared on; nothing follows or remaps it.", - ['volume', 'volumeId'], - ), ...described('Read as a truthy flag only; no editor writer.', [ 'arrayModifier', 'curvedWindowMaster', diff --git a/wiki/architecture/agent-surfaces.md b/wiki/architecture/agent-surfaces.md index 2c855c7a95..6a6d57e441 100644 --- a/wiki/architecture/agent-surfaces.md +++ b/wiki/architecture/agent-surfaces.md @@ -127,7 +127,7 @@ One check for every surface: `verify_scene` (`verifyScene` in core) reports per ## Furnishing follows a brief: `design_brief` -`design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing` (a `plan`, a number of `volumes` and one height or several, `heights`), refused `form_massing_missing`, and `verify_scene` reports `form_simpler_than_brief` where the built volumes are plainer than it states and `form_revised_simpler` where a later brief of the turn states a plainer form than the first; an open `facade` states its `treatment` (`cladding`, `bands`, `elements`, `rhythm`), refused `facade_treatment_missing`, and `verify_scene` reports `facade_revised_simpler` for a plainer revision within the turn; an open form also owes `rooms`, one entry per room (`name`, `use`, `distinct`, `finishes` with an optional `dressing` (wainscot, chairRail, crown, tiles-to-height, tiles-full, splashback, accent), `pieces`), refused `rooms_missing`, `room_distinct_missing` and, for two rooms of one use with the same line and pieces, `rooms_identical`, and `verify_scene` reports `room_dressing_revised_simpler` where a later brief of the turn announces less dressing than the first; a form bounded by words that fix no plan, and a brief with no `rooms`, are reported once the turn built under them (`form_bounded_without_plan`, `rooms_not_listed`); over MCP an axis quote is required and not compared, there being no message), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and `asIs`, which an open source once kept for technical equipment and which a stored brief may still hold (ignored). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. +`design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing` (a `plan`, a number of `volumes` and one height or several, `heights`), refused `form_massing_missing`; an open `facade` states its `treatment` (`cladding`, `bands`, `elements`, `rhythm`), refused `facade_treatment_missing`; an open form also owes `rooms`, one entry per room (`name`, `use`, `distinct`, `finishes` with an optional `dressing` (wainscot, chairRail, crown, tiles-to-height, tiles-full, splashback, accent), `pieces`), refused `rooms_missing`, `room_distinct_missing` and, for two rooms of one use with the same line and pieces, `rooms_identical`; over MCP an axis quote is required and not compared, there being no message), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and `asIs`, which an open source once kept for technical equipment and which a stored brief may still hold (ignored). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. The gate is a fact of the furnishing tools, in core: `furnishingRefusal(tool, input, brief, { session, catalog })` refuses `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` before a brief (`design_brief_required`); under an open brief it places technical equipment and plants from the catalog (the catalog's function tags and tags decide, not a list the model declares), refuses every other catalog piece naming the tools that make it, and refuses all of `furnish_room`, which places a whole stock set (`brief_source_open`); a piece refused once is answered briefly the second time, through the session's `brief.refusedPieces` reading; a catalog, brand or existing source opens everything. `run_batch` checks the gate per call under its usual refusal policy, not as a whole-batch host pre-check. Refused objects are not compiled and refused catalog placements do not read the library. Reading the catalog (`search_assets`, `view_assets`), rooms, walls, openings and finishes are never gated, and neither is an `add_object` that edits a standing object (`nodeId`). The operations of the gated tools refuse when the host lends `AgentContext.designBrief` (`null` while there is none, left out where the host does not gate); a host with an async step in front (the compile of an object) asks `furnishingRefusal` first. From eed3cdfdfe09c4fc4c59c6d78b069a9715b91dce Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 19:59:10 +0100 Subject: [PATCH 37/40] design_brief: form and facade are optional, and their absence is no longer refused axis_missing refused a brief without the form or the facade axis. With the brief's end-of-turn findings gone, nothing in this package reads those two axes back, so the refusal forced fields no check reads. They stay in the contract and keep their shape checks when given (an open form still states its massing, an open facade its treatment); a brief may leave them out. The refusal comes back with the findings that read them. The tool description, the wiki and the MCP README follow. Co-Authored-By: Claude Sonnet 5.5 --- .../__fixtures__/design-brief-cases.ts | 8 ++++---- packages/core/src/agent-operations/design-brief.ts | 14 +++++++++----- packages/core/src/agent-tools/design-brief.ts | 4 ++-- packages/mcp/README.md | 2 +- wiki/architecture/agent-surfaces.md | 2 +- 5 files changed, 17 insertions(+), 13 deletions(-) diff --git a/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts b/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts index 5947d75173..7cc4deb750 100644 --- a/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/design-brief-cases.ts @@ -820,7 +820,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ }, }, { - name: 'a brief with no form axis is refused, the absent axis named', + name: 'a brief with no form axis is recorded: form is optional', tool: 'design_brief', scene: storeysScene, input: { @@ -829,7 +829,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ vision: 'A calm room of oak and linen.', beyond: DRESSED, }, - expect: { refusal: 'axis_missing', mentions: ['form is absent'] }, + expect: { result: { status: 'recorded' } }, }, { name: 'an open form with no massing is refused, the fields named', @@ -1055,7 +1055,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ }, }, { - name: 'a brief with no facade axis is refused, the absent axis named', + name: 'a brief with no facade axis is recorded: facade is optional', tool: 'design_brief', scene: storeysScene, input: { @@ -1064,7 +1064,7 @@ export const DESIGN_BRIEF_CASES: AgentToolCase[] = [ vision: 'A calm room of oak and linen.', beyond: DRESSED, }, - expect: { refusal: 'axis_missing', mentions: ['facade is absent'] }, + expect: { result: { status: 'recorded' } }, }, { name: 'an open facade with no treatment is refused, the fields named', diff --git a/packages/core/src/agent-operations/design-brief.ts b/packages/core/src/agent-operations/design-brief.ts index b8601cc4f3..44775d5876 100644 --- a/packages/core/src/agent-operations/design-brief.ts +++ b/packages/core/src/agent-operations/design-brief.ts @@ -118,8 +118,11 @@ function quoteNamesSource(source: string, brand: string | undefined, quote: stri return (source === 'catalog' ? CATALOG_WORD : EXISTING_WORD).test(folded) } +/** The building's form and facade are the brief's own record: nothing reads them back yet, so a brief may leave them out. */ +const OPTIONAL_AXES: readonly string[] = ['form', 'facade'] + /** - * Every axis is stated, bounded or open. A bounded axis quotes the person's own words: where + * Every axis but form and facade is stated, bounded or open. A bounded axis quotes the person's own words: where * the host lends the message (the chat, `requestText`) the quote is in it, folded as the * source quote is; over MCP there is no message, so the quote is required by the contract and * not compared with anything. An open axis carries a design statement of at least @@ -127,7 +130,7 @@ function quoteNamesSource(source: string, brand: string | undefined, quote: stri */ function requireAxes(input: DesignBriefInput, context: AgentContext): BriefAxes { const axes = input.axes ?? {} - const missing = BRIEF_AXES.filter((axis) => !axes[axis]) + const missing = BRIEF_AXES.filter((axis) => !(axes[axis] || OPTIONAL_AXES.includes(axis))) if (missing.length) refuse( 'axis_missing', @@ -135,7 +138,8 @@ function requireAxes(input: DesignBriefInput, context: AgentContext): BriefAxes { axes: missing }, ) for (const axis of BRIEF_AXES) { - const reading = axes[axis]! + const reading = axes[axis] + if (!reading) continue if (reading.kind === 'bounded') { const quote = fold(reading.quote) if ( @@ -150,8 +154,8 @@ function requireAxes(input: DesignBriefInput, context: AgentContext): BriefAxes } else if (fold(reading.design).split(' ').filter(Boolean).length < AXIS_DESIGN_MIN_WORDS) refuse('axis_open_without_design', `The ${axis} is open: say how it is designed.`, { axis }) } - requireMassing(axes.form!) - requireTreatment(axes.facade!) + if (axes.form) requireMassing(axes.form) + if (axes.facade) requireTreatment(axes.facade) return axes } diff --git a/packages/core/src/agent-tools/design-brief.ts b/packages/core/src/agent-tools/design-brief.ts index 47bc440fa8..bf5f4d0ebc 100644 --- a/packages/core/src/agent-tools/design-brief.ts +++ b/packages/core/src/agent-tools/design-brief.ts @@ -346,7 +346,7 @@ export const axesSchema = z ).optional(), }) .describe( - "The request read axis by axis: action, size, form, facade, pieces, openings, style, materials, dressing, each bounded (the person's words as quote, the reading in a short line) or open (a design statement saying how it is designed; the form also states its massing, the facade its treatment). The tenth axis, the source, is the source fields: open, or bounded by sourceQuote. Every axis is stated; an axis the request does not touch is open.", + "The request read axis by axis: action, size, form, facade, pieces, openings, style, materials, dressing, each bounded (the person's words as quote, the reading in a short line) or open (a design statement saying how it is designed; the form also states its massing, the facade its treatment). The tenth axis, the source, is the source fields: open, or bounded by sourceQuote. Every axis but form and facade is stated (those two may be left out); an axis the request does not touch is open.", ) export type BriefAxes = z.infer @@ -364,7 +364,7 @@ The facade is the exterior identity of the building: its materials, the bands an rooms lists the rooms the request builds or refits, when it builds or refits more than one (a single-room request or a focused edit carries none; an open form owes them): for each, name (as the scene names the room), use (${ROOM_USES.join(', ')}), distinct (one line: what sets the room apart from the other rooms of its use, who it is for and its character), finishes (floor and walls as short phrases, tiled and skirting as true or false, and dressing when its walls are dressed) and pieces (its main pieces: furniture, fixtures, equipment). Rooms of the same use are distinct rooms, each with its own distinct line. Naming a piece (a double bed) states its function; its form, size within reason and finish are open unless the request fixes them. The pieces a request names are what the room must contain, not all it may contain: where the dressing axis is open, beyond states that design layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each a list of pieces or { none: why }, at least ${BEYOND_MIN_LAYERS} of the 8 layers naming pieces; where the dressing is bounded (words that limit the pieces or the action, such as "only", "nothing else", "just"), none in every layer is accepted. The pieces the request names, read as a minimum, do not bound the dressing. The answer hands the pieces back as dressing. A source other than open is set by the request, not chosen: sourceQuote holds the person's own words that name it, at least two words naming a brand (the brief's brand), the catalog or what is already there ("IKEA furniture only", "que du catalogue", "use my existing furniture"); a request that names no source is open. The chat checks the quote against the person's message of the turn, as it checks every bounded axis's quote; over MCP, where there is no message, a source quote must still name the source and is not compared with a request, and an axis quote is not compared either. -In the chat a brief lasts for the turn; over MCP it lasts for the session. The next design_brief replaces it. Refused: axis_missing (an axis is absent), axis_quote_not_in_request (a bounded axis's quote is not in the person's message), axis_open_without_design (an open axis without a design statement of at least ${AXIS_DESIGN_MIN_WORDS} words), form_massing_missing (an open form without its massing: plan, volumes, heights), form_massing_inconsistent (one volume stated as detached or at several heights), facade_treatment_missing (an open facade without its treatment: cladding or elements, and rhythm), rooms_missing (an open form with no rooms), room_distinct_missing (a room without its distinct line), rooms_identical (two rooms of one use with the same distinct and the same pieces), dressing_bounded_by_minimum (the dressing bounded by words inside a pieces quote read as a minimum), brand_required (source brand without a brand name), source_quote_required (a source other than open without sourceQuote), source_not_named (the quote names no brand, catalog or existing source), source_not_in_request (the quote is not in the person's message), beyond_too_thin (dressing open, fewer than ${BEYOND_MIN_LAYERS} layers naming pieces).`, +In the chat a brief lasts for the turn; over MCP it lasts for the session. The next design_brief replaces it. Refused: axis_missing (an axis other than form and facade is absent), axis_quote_not_in_request (a bounded axis's quote is not in the person's message), axis_open_without_design (an open axis without a design statement of at least ${AXIS_DESIGN_MIN_WORDS} words), form_massing_missing (an open form without its massing: plan, volumes, heights), form_massing_inconsistent (one volume stated as detached or at several heights), facade_treatment_missing (an open facade without its treatment: cladding or elements, and rhythm), rooms_missing (an open form with no rooms), room_distinct_missing (a room without its distinct line), rooms_identical (two rooms of one use with the same distinct and the same pieces), dressing_bounded_by_minimum (the dressing bounded by words inside a pieces quote read as a minimum), brand_required (source brand without a brand name), source_quote_required (a source other than open without sourceQuote), source_not_named (the quote names no brand, catalog or existing source), source_not_in_request (the quote is not in the person's message), beyond_too_thin (dressing open, fewer than ${BEYOND_MIN_LAYERS} layers naming pieces).`, input: { // Optional in the schema so an absent axis is refused by the operation, with the list, // on every surface, rather than by each surface's own validation error. diff --git a/packages/mcp/README.md b/packages/mcp/README.md index d85a94bb7d..5443b598c3 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -415,7 +415,7 @@ is a "pitch" fraction like `"1/4 pitch"`, which is rise over span. | `measure` | Distance between two nodes' world-space reference points (hosted doors, windows and items resolved through their host; every node kind); area when applicable. | `{ fromId, toId }` | `{ distanceMeters, fromPoint?, toPoint?, areaSqMeters?, units: 'meters' }` | | `view_scene` | Look at the finished building, every storey and the roof, from a viewpoint the agent picks (a compass side, a side as seen from the house's street, a street-height eye, a photo's camera, square-on, from above), in the scene's own light or a photo's, and get the picture back, with the photo's crop beside it when a region is given. `interior: { zoneId }` stands inside a room at eye height (1.6 m by default), a step in from a corner and looking across it; `interior: { levelId }` looks inside one floor: the other floors and its roofs and ceilings left out, everything on it (walls, openings, furniture) cut at 0.65 of the storey's height, for the picture only. Pictures are 1920 × 1200 unless `maxPx` (64 to 1920) asks for a smaller longest side. The server has no renderer: the host's `sceneViews` renders it (the hosted app, through the user's open editor tab). Read-only. | `{ target?, interior?, from?, elevation?, eyeHeight?, position?, fov?, projection?, camera?, lighting?, maxPx?, photo? }` | image content plus `{ status, camera, size, tab, capturedAt }`; refusals `view_unavailable`, `no_project`, `which_building` (a street side, no target, buildings on several sites), `no_current_camera` (`camera: 'current'`: the server has no view of the person's), `camera_and_viewpoint` (a camera with a viewpoint of the agent's own), `photo_crop_unavailable`, `interior_level_invalid`, `interior_hidden`, `interior_transform_unsupported`, `interior_target_elsewhere`; on the hosted server `editor_tab_required`, `editor_tab_hidden`, `editor_tab_busy` (a tab open but busy or still loading, no link: wait a few seconds and call again, do not ask the user), `editor_tab_timeout` (a tab claimed the view and then stopped answering); what the refusal says about opening the editor follows the person's "Agents may open the editor for me" setting (ask first, allow, never) | | `search_assets` | Search the host's item library (the built-in list on a standalone server), several queries in one call; a query matches name, id, category or tags. A query that finds nothing gets a hint to build the item with `add_object`. | `{ queries: [{ query, category? }] }` | `{ groups: [{ query, total, results[] }], total, hint? }`; refusal `no_catalog` | -| `design_brief` | The request read as a brief, once: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing`, an open `facade` its `treatment`, an open form owes `rooms`, all read back by `verify_scene` (see the wiki); over MCP an axis quote is required and not compared), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open, the dressing of the rooms layer by layer (`beyond`: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the named pieces read as a minimum do not bound it, `dressing_bounded_by_minimum`; handed back as `dressing`), the person's words that set a source other than `open` (`sourceQuote`, required, naming the brand, the catalog or what is already there; not compared here) and, with an open source, technical equipment and plants placed from the catalog by its tags (furniture is made). Furnishing follows a brief: `place_items`, `furnish_room`, `place_in_room` (the catalog's) and `add_object`, `place_design` (made), inside `run_batch` too, are refused before one with `design_brief_required`.`search_assets` and `view_assets` stay open too. Source `open` opens the made pieces, places technical equipment and plants from the catalog and keeps `furnish_room` closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. A batch checks each call under its own `onRefusal` policy. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. Changes nothing in the scene. | +| `design_brief` | The request read as a brief, once: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, except `form` and `facade`, which are optional, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing`, an open `facade` its `treatment`, an open form owes `rooms`; over MCP an axis quote is required and not compared), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` for what is open, the dressing of the rooms layer by layer (`beyond`: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the named pieces read as a minimum do not bound it, `dressing_bounded_by_minimum`; handed back as `dressing`), the person's words that set a source other than `open` (`sourceQuote`, required, naming the brand, the catalog or what is already there; not compared here) and, with an open source, technical equipment and plants placed from the catalog by its tags (furniture is made). Furnishing follows a brief: `place_items`, `furnish_room`, `place_in_room` (the catalog's) and `add_object`, `place_design` (made), inside `run_batch` too, are refused before one with `design_brief_required`.`search_assets` and `view_assets` stay open too. Source `open` opens the made pieces, places technical equipment and plants from the catalog and keeps `furnish_room` closed (`brief_source_open`); `catalog`, `brand` and `existing` open the catalog's tools, and creation for what it lacks. A batch checks each call under its own `onRefusal` policy. The brief is the session's: a scene load or clear starts another, and the next `design_brief` replaces it. Changes nothing in the scene. | | `view_assets` | Pictures of 1 to 6 catalog items by id, each labelled with its size, category and the names of its paintable surfaces (its model's `slot_` materials; `paint` takes one as `role`), returned as image content. The picture and surfaces are read before the call (a hosted server fetches and resizes the thumbnail to at most 512 px; a standalone server's built-in list has no host to fetch from, so it answers sizes and says it has no picture). Opt-in: nothing changes when it is not called. | `{ ids: string[] (1 to 6) }` | `{ items: [{ id, name, category, dimensions, surfaces, picture, unavailable? }], shown, note? }` plus one labelled image per item shown; refusals `unknown_asset`, `no_catalog` | | `search_materials` | Search or browse the material library, several queries in one call: words match as the library writes them (timber is wood, render is stucco), shades and surfaces; a query without words lists a kind, a surface or the whole library by name. A search lists 12 at a time and a browse 150, a long one saying how many more (`more`) and the offset that lists them (`next`). Reads Pascal's library and the materials the host registered (the editor registers its library; this server registers none). Read-only. | `{ queries: [{ query?, kind?, surface?, offset? }] }` | `{ groups: [{ query?, kind?, surface?, offset?, results: [{ ref, label, kind, surfaces, color? }], missing?, more?, next? }] }` | | `paint` | Give walls, slabs, ceilings, roofs and every other part with surfaces (columns, fences, doors, windows, stairs, blocks, cabinets, shelves…) a finish in one call, as the editor's Paint does: a colour (the nearest library colour), a `library:` or `scene:` ref, a native material kept as a scene material (reused when an equal one exists), or erase. `role` picks the surface (a wall's `exterior`/`interior` faces, by its rooms or else its stored sides, refused when rooms stand on only part of a face, a slot by name, a roof's `top`/`edge`/`wall`, or its `fascia`, the fascia and rake boards, held by every segment; a glazed roof's `glazing-frame`, `glazing-glass` or `glazing-solid`, and without a role its frame and solid panels, the glass kept); a roof shows one finish per surface, so a segment's finish goes on its roof and a roof's clears its segments' own; a wall face is painted whole, over its room's wall finish, its painted parts keeping theirs (named in `note`). | `{ targets[], role?, color?, material?, materialName?, erase? }` (one finish) | `{ ok, painted[], finish, materialId?, material?, createdMaterial?, note?, achieved }`; refusals `target_not_found`, `unknown_role`, `side_unknown`, `unknown_material`, `materials_unavailable`, `not_paintable` | diff --git a/wiki/architecture/agent-surfaces.md b/wiki/architecture/agent-surfaces.md index 6a6d57e441..5413bcece7 100644 --- a/wiki/architecture/agent-surfaces.md +++ b/wiki/architecture/agent-surfaces.md @@ -127,7 +127,7 @@ One check for every surface: `verify_scene` (`verifyScene` in core) reports per ## Furnishing follows a brief: `design_brief` -`design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing` (a `plan`, a number of `volumes` and one height or several, `heights`), refused `form_massing_missing`; an open `facade` states its `treatment` (`cladding`, `bands`, `elements`, `rhythm`), refused `facade_treatment_missing`; an open form also owes `rooms`, one entry per room (`name`, `use`, `distinct`, `finishes` with an optional `dressing` (wainscot, chairRail, crown, tiles-to-height, tiles-full, splashback, accent), `pieces`), refused `rooms_missing`, `room_distinct_missing` and, for two rooms of one use with the same line and pieces, `rooms_identical`; over MCP an axis quote is required and not compared, there being no message), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and `asIs`, which an open source once kept for technical equipment and which a stored brief may still hold (ignored). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. +`design_brief` records the request as a brief: `axes` (the request read axis by axis: `action`, `size`, `form`, `facade`, `pieces`, `openings`, `style`, `materials`, `dressing`, each bounded — the person's own words as `quote`, the reading in a short line, `pieces` as a `minimum` or `exact` — or open with a design statement of at least three words; an absent axis is refused `axis_missing`, except `form` and `facade`, which are optional, a quote not in the person's message in the chat `axis_quote_not_in_request`, an open axis without its design `axis_open_without_design`; an open `form` states its `massing` (a `plan`, a number of `volumes` and one height or several, `heights`), refused `form_massing_missing`; an open `facade` states its `treatment` (`cladding`, `bands`, `elements`, `rhythm`), refused `facade_treatment_missing`; an open form also owes `rooms`, one entry per room (`name`, `use`, `distinct`, `finishes` with an optional `dressing` (wainscot, chairRail, crown, tiles-to-height, tiles-full, splashback, accent), `pieces`), refused `rooms_missing`, `room_distinct_missing` and, for two rooms of one use with the same line and pieces, `rooms_identical`; over MCP an axis quote is required and not compared, there being no message), the tenth axis `source` (`open`, `catalog`, `brand` with its `brand`, `existing`), a `vision` a `beyond` (the dressing, layer by layer: textiles, light, windows, walls, floor, plants, objects, small furniture, each pieces or `{ none: why }`; an open `dressing` axis owes pieces for 6 of the 8, `beyond_too_thin`, a bounded one owes none, and the dressing cannot be bounded by a quote inside a `pieces` quote read as a minimum, `dressing_bounded_by_minimum`; the result hands the pieces back as `dressing`, nothing checks them later; a brief stored as `fixed`/`open` lists, or with a string `beyond`, still reads), a `sourceQuote` for any source but `open` (the person's own words that set it: at least two words naming the brief's brand, the catalog or what is already there, from explicit English and French lists in `design-brief.ts`, `source_not_named`; the chat also checks it against the turn's message through `AgentContext.requestText`, `source_not_in_request`; over MCP only that second check is skipped). The stored brief reads without `beyond` (reading is tolerant, the tool's input is strict) and `asIs`, which an open source once kept for technical equipment and which a stored brief may still hold (ignored). Core's `designBrief` echoes it with what it unlocks and hands it to the host as a session keep (`SessionKeep.designBrief`, replaced by the next brief, `null` takes it away); it changes nothing in the scene. The gate is a fact of the furnishing tools, in core: `furnishingRefusal(tool, input, brief, { session, catalog })` refuses `place_items`, `furnish_room`, `place_in_room`, `add_object` and `place_design` before a brief (`design_brief_required`); under an open brief it places technical equipment and plants from the catalog (the catalog's function tags and tags decide, not a list the model declares), refuses every other catalog piece naming the tools that make it, and refuses all of `furnish_room`, which places a whole stock set (`brief_source_open`); a piece refused once is answered briefly the second time, through the session's `brief.refusedPieces` reading; a catalog, brand or existing source opens everything. `run_batch` checks the gate per call under its usual refusal policy, not as a whole-batch host pre-check. Refused objects are not compiled and refused catalog placements do not read the library. Reading the catalog (`search_assets`, `view_assets`), rooms, walls, openings and finishes are never gated, and neither is an `add_object` that edits a standing object (`nodeId`). The operations of the gated tools refuse when the host lends `AgentContext.designBrief` (`null` while there is none, left out where the host does not gate); a host with an async step in front (the compile of an object) asks `furnishingRefusal` first. From 622ee8df313dbf804d375b3a6e38b008340354a0 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 20:12:58 +0100 Subject: [PATCH 38/40] Move set_code_profile out, with the Australian and French rows only it selected The tool had no call in 43 stored projects, no panel in this repository, and the private side no longer lists it. A project's profile is still read from site.metadata.codeProfile, and the IRC rows the usage checks read stay. Out: the operation, the tool, its output schema, its place in the MCP package (README row, agent-guide line, annotation justification, OpenAI policy row, its cases in the shared table), the NCC 2022 and French 2015 rows and their tests, and one usage test that set the profile through the operation (the profile test beside it sets it on the site). The package lists 89 tools. The code stays on rd/editor-later-20261103. Co-Authored-By: Claude Sonnet 5.5 --- .../agent-operations/__fixtures__/cases.ts | 2 - .../__fixtures__/site-cases.ts | 46 -------- packages/core/src/agent-operations/index.ts | 3 - .../agent-operations/set-code-profile.test.ts | 43 ------- .../src/agent-operations/set-code-profile.ts | 52 --------- packages/core/src/agent-tools/index.ts | 3 - .../core/src/agent-tools/set-code-profile.ts | 25 ---- .../core/src/building/code-profile.test.ts | 45 +------- packages/core/src/building/code-profile.ts | 107 +----------------- .../core/src/contracts/reference-inventory.ts | 2 +- .../spatial/usage-field/findings-more.test.ts | 21 ---- packages/mcp/README.md | 1 - packages/mcp/src/resources/agent-guide.ts | 1 - .../src/tools/read-tool-annotations.test.ts | 1 - packages/mcp/src/tools/shared-tools.ts | 8 -- .../tool-annotation-justifications.json | 13 --- scripts/openai-tool-annotation-policy.ts | 1 - 17 files changed, 5 insertions(+), 369 deletions(-) delete mode 100644 packages/core/src/agent-operations/set-code-profile.test.ts delete mode 100644 packages/core/src/agent-operations/set-code-profile.ts delete mode 100644 packages/core/src/agent-tools/set-code-profile.ts diff --git a/packages/core/src/agent-operations/__fixtures__/cases.ts b/packages/core/src/agent-operations/__fixtures__/cases.ts index 2539db18e6..1ea366fe3a 100644 --- a/packages/core/src/agent-operations/__fixtures__/cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/cases.ts @@ -39,7 +39,6 @@ import { GET_SITE_CASES, PLACE_BUILDING_CASES, SITE_LINE_CASES, - SET_CODE_PROFILE_CASES, SITE_VERIFY_CASES, } from './site-cases' import { @@ -996,7 +995,6 @@ export const AGENT_TOOL_CASES: readonly AgentToolCase[] = [ ...PLACE_BUILDING_CASES, ...SITE_LINE_CASES, ...SITE_VERIFY_CASES, - ...SET_CODE_PROFILE_CASES, ...FINISH_CASES, ...UNIT_CASES, ] diff --git a/packages/core/src/agent-operations/__fixtures__/site-cases.ts b/packages/core/src/agent-operations/__fixtures__/site-cases.ts index 79c31b0401..7832a3b9cc 100644 --- a/packages/core/src/agent-operations/__fixtures__/site-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/site-cases.ts @@ -937,49 +937,3 @@ export const SITE_VERIFY_CASES: AgentToolCase[] = [ }, }, ] - -export const SET_CODE_PROFILE_CASES: AgentToolCase[] = [ - { - name: 'a project that names a code gets it on the site, the rest of the site metadata kept', - tool: 'set_code_profile', - scene: () => scene(site({ metadata: { codeOverrides: { state: 'FL' } } })), - input: { profile: 'irc-2021' }, - expect: { - result: { siteId: 'site_lot', profile: 'irc-2021', previous: null, unchanged: false }, - after: { site_lot: { metadata: { codeProfile: 'irc-2021', codeOverrides: { state: 'FL' } } } }, - mentions: ['US IRC 2021'], - }, - }, - { - name: 'null clears it: the key goes, the rest stays', - tool: 'set_code_profile', - scene: () => scene(site({ metadata: { codeProfile: 'irc-2021', codeOverrides: { state: 'FL' } } })), - input: { profile: null }, - expect: { - result: { profile: null, previous: 'irc-2021', unchanged: false }, - after: { site_lot: { metadata: { codeOverrides: { state: 'FL' } } } }, - mentions: ['names no code'], - }, - }, - { - name: 'saying what is already said changes nothing', - tool: 'set_code_profile', - scene: () => scene(site({ metadata: { codeProfile: 'au-ncc' } })), - input: { profile: 'au-ncc' }, - expect: { result: { profile: 'au-ncc', unchanged: true }, mentions: ['only the values read in its own texts'] }, - }, - { - name: 'a scene with no site has nowhere to put it', - tool: 'set_code_profile', - scene: () => ({ nodes: {}, rootNodeIds: [] }), - input: { profile: 'irc-2021' }, - expect: { refusal: 'no_site' }, - }, - { - name: 'two sites leave it ambiguous', - tool: 'set_code_profile', - scene: () => scene(site(), SiteNode.parse({ id: 'site_other', children: [] })), - input: { profile: 'irc-2021' }, - expect: { refusal: 'ambiguous_site' }, - }, -] diff --git a/packages/core/src/agent-operations/index.ts b/packages/core/src/agent-operations/index.ts index d0de29b6d4..19627865e0 100644 --- a/packages/core/src/agent-operations/index.ts +++ b/packages/core/src/agent-operations/index.ts @@ -30,7 +30,6 @@ import { ROOM_OPERATIONS } from './room-structure' import { searchAssets } from './search-assets' import { searchMaterials } from './search-materials' import { setCheckpoint } from './set-checkpoint' -import { setCodeProfile } from './set-code-profile' import { setGroundLevel } from './set-ground-level' import { getSite, placeBuilding } from './site' import { fitStair, measureStairOperation } from './stairs' @@ -98,7 +97,6 @@ export * from './scene-queries' export * from './scene-view' export * from './search-assets' export * from './search-materials' -export * from './set-code-profile' export * from './site' export * from './slab-surface-script' export * from './stairs' @@ -125,7 +123,6 @@ const SINGLE_OPERATIONS = { validate_design: validateDesignOperation, place_design: gatedByBrief('place_design', placeDesign), set_checkpoint: setCheckpoint, - set_code_profile: setCodeProfile, design_brief: designBrief, add_wall: addWall, set_wall_type: setWallType, diff --git a/packages/core/src/agent-operations/set-code-profile.test.ts b/packages/core/src/agent-operations/set-code-profile.test.ts deleted file mode 100644 index 300a3333dd..0000000000 --- a/packages/core/src/agent-operations/set-code-profile.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, test } from 'bun:test' -import { AgentRefusal } from '../agent-tools/refusal' -import { codeProfileOf } from '../building/code-profile' -import { SiteNode } from '../schema' -import { setCodeProfile } from './set-code-profile' - -const ctx = { activeLevelId: null } -const sites = (metadata?: Record) => - ({ - site_1: SiteNode.parse({ id: 'site_1', children: [], ...(metadata ? { metadata } : {}) }), - }) as never - -describe('set_code_profile', () => { - test('a profile that is not one is refused when it bypasses the contract', () => { - try { - setCodeProfile(sites(), { profile: 'ncc' } as never, ctx) - throw new Error('not refused') - } catch (error) { - expect(error).toBeInstanceOf(AgentRefusal) - expect((error as AgentRefusal).code).toBe('invalid_input') - } - }) - - test('set, read back by the checks, and cleared', () => { - const nodes = sites({ keep: 1 }) - const set = setCodeProfile(nodes, { profile: 'irc-2021' }, ctx) - const written = { site_1: { ...nodes.site_1, ...set.changes!.update![0]!.data } } as never - expect(codeProfileOf(written)?.id).toBe('irc-2021') - expect((written as Record).site_1!.metadata).toEqual({ - keep: 1, - codeProfile: 'irc-2021', - }) - const cleared = setCodeProfile(written, { profile: null }, ctx) - const after = { - site_1: { - ...(written as Record).site_1, - ...cleared.changes!.update![0]!.data, - }, - } as never - expect(codeProfileOf(after)).toBeNull() - expect((after as Record).site_1!.metadata).toEqual({ keep: 1 }) - }) -}) diff --git a/packages/core/src/agent-operations/set-code-profile.ts b/packages/core/src/agent-operations/set-code-profile.ts deleted file mode 100644 index 6fb8ad03ef..0000000000 --- a/packages/core/src/agent-operations/set-code-profile.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { z } from 'zod' -import { refuse } from '../agent-tools/refusal' -import { setCodeProfileTool } from '../agent-tools/set-code-profile' -import { - CODE_PROFILE_KEY, - CODE_PROFILES, - type CodeProfileId, - codeProfileOf, -} from '../building/code-profile' -import type { SiteNode } from '../schema' -import { queryNodes } from './scene-queries' -import type { AgentOperation } from './types' - -const inputSchema = z.strictObject(setCodeProfileTool.input) - -function siteOf(nodes: Parameters>[0]): SiteNode { - const sites = queryNodes(nodes, { type: 'site' }) - if (!sites.length) refuse('no_site', 'The scene has no site to hold the code profile.') - if (sites.length > 1) - refuse( - 'ambiguous_site', - 'The scene has more than one site; which one names the code is ambiguous.', - ) - return sites[0]! -} - -const effect = (profile: CodeProfileId | null) => - profile === null - ? 'The project names no code: the checks that apply a code report information that names the US IRC they used.' - : CODE_PROFILES[profile].id === 'irc-2021' - ? 'The project follows the US IRC 2021: the checks that apply a code report warnings.' - : `The project follows ${CODE_PROFILES[profile].label}, which holds only the values read in its own texts: a check that has no value for it reports nothing.` - -/** - * `set_code_profile`: the one place `site.metadata.codeProfile` is written (the agent tool, the MCP - * tool, the site panel and Architect Pro's `code_basis_set` all call it). The rest of the site's - * metadata is kept; clearing removes the key. - */ -export const setCodeProfile: AgentOperation> = (nodes, input) => { - const parsed = inputSchema.safeParse(input) - if (!parsed.success) refuse('invalid_input', parsed.error.message) - const site = siteOf(nodes) - const profile = parsed.data.profile - const previous = codeProfileOf({ [site.id]: site })?.id ?? null - const message = effect(profile) - const result = { siteId: site.id, profile, previous, unchanged: previous === profile, message } - if (previous === profile) return { result } - const metadata: Record = { ...site.metadata } - if (profile === null) delete metadata[CODE_PROFILE_KEY] - else metadata[CODE_PROFILE_KEY] = profile - return { result, changes: { update: [{ id: site.id, data: { metadata } }] } } -} diff --git a/packages/core/src/agent-tools/index.ts b/packages/core/src/agent-tools/index.ts index 7bb8773186..2f00b7c297 100644 --- a/packages/core/src/agent-tools/index.ts +++ b/packages/core/src/agent-tools/index.ts @@ -32,7 +32,6 @@ import { placeItemsTool } from './place-items' import { createRoofTool, moveRoofsToRoofLevelTool } from './roofs' import { ROOM_TOOL_CONTRACTS } from './room-structure' import { searchMaterialsTool } from './search-materials' -import { setCodeProfileTool } from './set-code-profile' import { getSiteTool, placeBuildingTool } from './site' import { createStairTool, fitStairTool, measureStairTool } from './stairs' import { UNIT_TOOL_CONTRACTS } from './units' @@ -70,7 +69,6 @@ export * from './retired' export * from './roofs' export * from './room-structure' export * from './search-materials' -export * from './set-code-profile' export * from './site' export { CATALOG_SOURCE, OTHER_SOURCES, OUTSIDE_SOURCES } from './sources' export * from './stairs' @@ -104,7 +102,6 @@ export const AGENT_TOOL_CONTRACTS = [ designBriefTool, placeDesignTool, validateDesignTool, - setCodeProfileTool, addWallTool, setWallTypeTool, addFenceTool, diff --git a/packages/core/src/agent-tools/set-code-profile.ts b/packages/core/src/agent-tools/set-code-profile.ts deleted file mode 100644 index 8764ddcddf..0000000000 --- a/packages/core/src/agent-tools/set-code-profile.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { z } from 'zod' -import { CODE_PROFILE_IDS } from '../building/code-profile' - -export const setCodeProfileTool = { - name: 'set_code_profile', - title: 'Set code profile', - description: - 'Say which building code the project follows: irc-2021 (the US IRC 2021), au-ncc (the Australian NCC) or fr (the French regulations); null clears it. A project that names no code has none: nothing is guessed from an address. ' + - 'The checks that apply a code (bathroom clearances) read it: with irc-2021 they are warnings, with no code they are information that names the US IRC they used, and au-ncc and fr hold only the values read in their own texts (stairs, ceiling heights), none of which those checks use yet, so they report nothing. ' + - 'Stored as site.metadata.codeProfile. Refusals: no_site, ambiguous_site, invalid_input. One undo step.', - input: { - profile: z - .enum(CODE_PROFILE_IDS) - .nullable() - .describe('The code: irc-2021, au-ncc or fr. null: the project names no code.'), - }, -} - -export const codeProfileOutput = { - siteId: z.string(), - profile: z.enum(CODE_PROFILE_IDS).nullable(), - previous: z.enum(CODE_PROFILE_IDS).nullable(), - unchanged: z.boolean(), - message: z.string(), -} diff --git a/packages/core/src/building/code-profile.test.ts b/packages/core/src/building/code-profile.test.ts index 25d5a8f08f..e4c5452597 100644 --- a/packages/core/src/building/code-profile.test.ts +++ b/packages/core/src/building/code-profile.test.ts @@ -1,14 +1,5 @@ import { describe, expect, test } from 'bun:test' -import { - CODE_PROFILE_IDS, - CODE_PROFILES, - codeProfileOf, - FR_2015, - IRC_2021, - ircValue, - NCC_2022, - thresholdOf, -} from './code-profile' +import { CODE_PROFILES, codeProfileOf, IRC_2021, ircValue, thresholdOf } from './code-profile' describe('the code profile table', () => { test('every IRC row says its section, its citation and whether its text was read', () => { @@ -32,37 +23,7 @@ describe('the code profile table', () => { expect(IRC_2021.stairHeadroom).toMatchObject({ source: 'code text', value: 80 * 0.0254 }) }) - test('the Australian and French profiles hold only the rows read in their own texts, each cited', () => { - expect(CODE_PROFILE_IDS).toEqual(['irc-2021', 'au-ncc', 'fr']) - expect(CODE_PROFILES['au-ncc'].thresholds).toBe(NCC_2022) - expect(CODE_PROFILES.fr.thresholds).toBe(FR_2015) - for (const [rows, section] of [ - [NCC_2022, /^NCC 2022 HP /], - [FR_2015, /^arrêté du 24 décembre 2015 art\. 1\d/], - ] as const) - for (const [id, row] of Object.entries(rows)) { - expect([id, row.section]).toEqual([id, expect.stringMatching(section)]) - expect(row.cite.length).toBeGreaterThan(40) - expect(row.source).toBe('code text') - expect(row.value).toBeGreaterThan(0) - } - // what their texts do not set has no row: a check that needs one reports nothing - for (const id of ['toiletFrontClear', 'doorThresholdDrop', 'habitableRoomArea'] as const) { - expect(thresholdOf(CODE_PROFILES['au-ncc'], id)).toBeUndefined() - expect(thresholdOf(CODE_PROFILES.fr, id)).toBeUndefined() - } - // the same id, a different applicability: the IRC landing is at every exterior door, the NCC's only over a drop - expect(IRC_2021.exteriorDoorLanding.appliesWhen).toBe('every-exterior-door') - expect(NCC_2022.exteriorDoorLanding.appliesWhen).toEqual({ dropOverM: 0.57, risersOver: 3 }) - expect( - Object.entries({ ...IRC_2021, ...NCC_2022, ...FR_2015 }) - .filter(([, row]) => 'appliesWhen' in row) - .map(([id]) => id), - ).toEqual(['exteriorDoorLanding']) - expect(NCC_2022.riserMax.value).toBe(0.19) - expect(NCC_2022.stairLanding.value).toBe(0.75) - expect(FR_2015.stairWidth.value).toBe(0.8) - expect(FR_2015.riserMax.value).toBe(0.18) + test('a profile hands back the row of an id', () => { expect(thresholdOf(CODE_PROFILES['irc-2021'], 'toiletFrontClear')?.value).toBe( ircValue('toiletFrontClear'), ) @@ -82,7 +43,5 @@ describe('the jurisdiction of a scene', () => { test('site.metadata.codeProfile names it', () => { expect(codeProfileOf(site({ codeProfile: 'irc-2021' }))?.id).toBe('irc-2021') - expect(codeProfileOf(site({ codeProfile: 'au-ncc' }))?.id).toBe('au-ncc') - expect(codeProfileOf(site({ codeProfile: 'fr' }))?.id).toBe('fr') }) }) diff --git a/packages/core/src/building/code-profile.ts b/packages/core/src/building/code-profile.ts index 83e2df03c0..6e7363651f 100644 --- a/packages/core/src/building/code-profile.ts +++ b/packages/core/src/building/code-profile.ts @@ -4,13 +4,10 @@ * * Which code applies is the project's to say: `site.metadata.codeProfile`. A scene that does not say has * no jurisdiction, and a code-specific check then reports information that names the code it used, never - * a warning (the listing houses are Australian designs; the US IRC is not what they were drawn to). The - * profiles for Australia (NCC, ABCB Housing Provisions) and France hold only the rows read in their own - * texts (below); a check that has no row for the code reports nothing. These are usage indicators, not a - * compliance check. + * a warning (the listing houses are Australian designs; the US IRC is not what they were drawn to). These are usage indicators, not a compliance check. */ -export const CODE_PROFILE_IDS = ['irc-2021', 'au-ncc', 'fr'] as const +export const CODE_PROFILE_IDS = ['irc-2021'] as const export type CodeProfileId = (typeof CODE_PROFILE_IDS)[number] /** The text the number was read in (a state's adoption of the model code, or UpCodes), or only a guide, a forum or another checker's constant. */ @@ -186,100 +183,6 @@ export const IRC_2021 = { }, } as const satisfies Record -const NCC_READ = 'read on ncc.abcb.gov.au, NCC 2022 ABCB Housing Provisions, 27 October 2026' - -/** - * The Australian National Construction Code, ABCB Housing Provisions (NCC 2022), the rows whose text was - * read there. The same ids as the IRC rows, where the rule is the same kind of rule; what the Housing - * Provisions do not set (a stair width, a hall width, a room area, an egress opening, the clearances at - * a toilet, a door that must not swing over stairs) has no row, and a check that needs one reports nothing. - */ -export const NCC_2022 = { - riserMax: { - value: 0.19, - unit: 'm', - section: 'NCC 2022 HP Table 11.2.2a', - cite: `NCC 2022 Housing Provisions Table 11.2.2a, riser at most 190 mm for a stair other than a spiral (115 mm at least; 225 mm for stairs serving rarely used non-habitable rooms, Table 11.2.2b); ${NCC_READ}`, - source: 'code text', - }, - treadMin: { - value: 0.24, - unit: 'm', - section: 'NCC 2022 HP Table 11.2.2a', - cite: `NCC 2022 Housing Provisions Table 11.2.2a, going at least 240 mm (355 mm at most; 2R+G between 550 and 700 mm; 215 mm for stairs serving rarely used non-habitable rooms, Table 11.2.2b); ${NCC_READ}`, - source: 'code text', - }, - stairLanding: { - value: 0.75, - unit: 'm', - section: 'NCC 2022 HP 11.2.5(1)(a)', - cite: `NCC 2022 Housing Provisions 11.2.5(1)(a), a landing at least 750 mm long (500 mm from the inside edge where it turns; 600 mm for a stair serving only rarely used non-habitable rooms, 11.2.5(2)); ${NCC_READ}`, - source: 'code text', - }, - exteriorDoorLanding: { - value: 0.75, - unit: 'm', - section: 'NCC 2022 HP 11.2.5(1)(a), (c), (d)', - cite: `NCC 2022 Housing Provisions 11.2.5(1)(a), (c), (d), a landing at least 750 mm long across the full width of a doorway whose sill opens onto a stairway or ramp with a change in level of more than 3 risers or 570 mm (a threshold more than 230 mm above the adjoining surface incorporates steps, 11.2.6); ${NCC_READ}`, - appliesWhen: { dropOverM: 0.57, risersOver: 3 }, - source: 'code text', - }, - stairHeadroom: { - value: 2, - unit: 'm', - section: 'NCC 2022 HP 10.3.1(1)(f)', - cite: `NCC 2022 Housing Provisions 10.3.1(1)(f), 2.0 m measured vertically above the nosing line of a stairway, ramp or landing; ${NCC_READ}`, - source: 'code text', - }, - ceilingHeight: { - value: 2.4, - unit: 'm', - section: 'NCC 2022 HP 10.3.1(1)(a)', - cite: `NCC 2022 Housing Provisions 10.3.1(1)(a), 2.4 m in a habitable room other than a kitchen (a kitchen, corridor, bathroom or laundry 2.1 m; a sloping ceiling over two thirds of the floor); ${NCC_READ}`, - source: 'code text', - }, -} as const satisfies Partial> - -const FR_READ = - "read on legifrance.gouv.fr (JORFTEXT000031692481), consolidated text in force on 27 October 2026, articles 11 and 12 unmodified since publication: the accessibility rules for new collective housing and individual houses; whom they bind is the decree's, not read here" - -/** - * France: the rows whose text was read in the arrêté du 24 décembre 2015 on the accessibility of new - * dwellings. Nothing here comes from a construction text that sets a room area or a ceiling height for a - * new dwelling (none was found in the national texts opened); the clear space beside a WC (0,80 x 1,30 m) - * is a space for a wheelchair in the unité de vie, not the IRC's centre-to-obstruction figure, so it has no row. - */ -export const FR_2015 = { - hallWidth: { - value: 0.9, - unit: 'm', - section: 'arrêté du 24 décembre 2015 art. 11 II', - cite: `arrêté du 24 décembre 2015 art. 11, II: la largeur minimale des circulations intérieures est de 0,90 m (porte d'entrée 0,90 m nominal, 0,83 m de passage utile; portes intérieures 0,80 m nominal, 0,77 m utile); ${FR_READ}`, - source: 'code text', - }, - stairWidth: { - value: 0.8, - unit: 'm', - section: 'arrêté du 24 décembre 2015 art. 12', - cite: `arrêté du 24 décembre 2015 art. 12: l'escalier d'un logement sur plusieurs niveaux a une largeur minimale de 0,80 m (mesurée à l'aplomb de la main courante si elle empiète de plus de 10 cm); ${FR_READ}`, - source: 'code text', - }, - riserMax: { - value: 0.18, - unit: 'm', - section: 'arrêté du 24 décembre 2015 art. 12', - cite: `arrêté du 24 décembre 2015 art. 12: hauteur de marche inférieure ou égale à 18 cm; ${FR_READ}`, - source: 'code text', - }, - treadMin: { - value: 0.24, - unit: 'm', - section: 'arrêté du 24 décembre 2015 art. 12', - cite: `arrêté du 24 décembre 2015 art. 12: largeur du giron supérieure ou égale à 24 cm; ${FR_READ}`, - source: 'code text', - }, -} as const satisfies Partial> - /** * Numbers the usage checks borrow for what a person can do in a house: a clear passage, a door, a turning * space, the edge a cane finds. They are not a code row and apply to every project whatever its jurisdiction @@ -321,12 +224,6 @@ export type CodeProfile = { export const CODE_PROFILES: Readonly> = { 'irc-2021': { id: 'irc-2021', label: 'the US IRC 2021', thresholds: IRC_2021 }, - 'au-ncc': { - id: 'au-ncc', - label: 'the Australian NCC (ABCB Housing Provisions)', - thresholds: NCC_2022, - }, - fr: { id: 'fr', label: 'the French regulations', thresholds: FR_2015 }, } /** Where a project says which code applies: `site.metadata.codeProfile`. */ diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 2e4fd0b123..8fec01c12e 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -1083,7 +1083,7 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ ['codeOverrides'], ), ...described( - 'Which building code the project follows (`irc-2021`, `au-ncc`, `fr`): a profile name, never a node id. Read by the code-specific usage checks; a scene that does not name one has no jurisdiction.', + 'Which building code the project follows (`irc-2021`): a profile name, never a node id. Read by the code-specific usage checks; a scene that does not name one has no jurisdiction.', ['codeProfile'], ), ...described('Read as a truthy flag only; no editor writer.', [ diff --git a/packages/core/src/spatial/usage-field/findings-more.test.ts b/packages/core/src/spatial/usage-field/findings-more.test.ts index bd3d661e0d..9610c27eca 100644 --- a/packages/core/src/spatial/usage-field/findings-more.test.ts +++ b/packages/core/src/spatial/usage-field/findings-more.test.ts @@ -1,5 +1,4 @@ import { describe, expect, test } from 'bun:test' -import { setCodeProfile } from '../../agent-operations/set-code-profile' import { type AnyNode, BuildingNode, @@ -568,24 +567,6 @@ describe('usage_fixture_clearance', () => { ) } }) - - test('set_code_profile on a US project turns the finding into a warning, and clearing it turns it back', () => { - const apply = (nodes: Nodes, profile: 'irc-2021' | null) => { - const out = setCodeProfile(nodes, { profile }, { activeLevelId: null }) - const update = out.changes?.update?.[0] - return update - ? ({ ...nodes, [update.id]: { ...nodes[update.id]!, ...update.data } } as Nodes) - : nodes - } - const bare = toiletRoom(0.4, [site()]) - expect(clear(bare)[0]).toMatchObject({ severity: 'info', code: { byDefault: true } }) - const us = apply(bare, 'irc-2021') - expect(clear(us)[0]).toMatchObject({ - severity: 'warning', - code: { profile: 'irc-2021', byDefault: false }, - }) - expect(clear(apply(us, null))[0]).toMatchObject({ severity: 'info' }) - }) }) describe('usage_door_over_stair', () => { @@ -672,8 +653,6 @@ describe('usage_door_over_stair', () => { severity: 'warning', code: { byDefault: false }, }) - expect(over(headOfStair('outward', [site('au-ncc')]))).toHaveLength(0) - expect(over(headOfStair('outward', [site('fr')]))).toHaveLength(0) }) test('the same door swinging into the room, away from the stair, says nothing', () => { diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 5443b598c3..1d3b976f19 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -433,7 +433,6 @@ is a "pitch" fraction like `"1/4 pitch"`, which is rise over span. | `merge_windows` | Make two windows that exist one window, as the editor's Merge windows button does; nothing is recreated. On two walls that meet at a corner, each window within 0.30 m of it, they become one corner window (the `add_corner_window` result): each is slid to the corner keeping its width, the glass fused (a fixed window's; other types meet at a post), and both take the first window's height, sill and type, so name first the window whose look you want; the corner is refused over 170° or under 10°. On one wall, two windows with at most 0.30 m between them and nothing between become one window spanning both (overlapping or one inside the other, their union), from the lower sill to the higher head, with the first window's type and style. Use it for two windows already built that open a corner or one wide opening (`verify_scene`'s `corner_unjoined` names a pair for the first); `add_corner_window` builds a new pair. By hand: select two windows and use Merge windows in the multi-selection panel, or place or drag a window near a corner where one waits and click or release (Alt places it plain). | `{ windowIds: [a, b] }` | `{ kind: 'corner' \| 'same_wall', windowIds, removedIds, achieved }`; refusals `window_not_found`, `not_a_window`, `same_window`, `window_not_on_wall`, `window_already_joined` (unwrap it first), `windows_already_joined`, `windows_not_adjacent`, `opening_between`, `walls_not_meeting`, `corner_angle`, `window_not_at_corner`, `height_exceeds_wall`, `opening_overlap` | | `apply_patch` | Batched create/update/delete/move, validated and dry-run before commit. Batch-first is the default: send all create/update/delete ops for a build step in one atomic call (stable order, later ops may reference earlier created ids); do not loop one-op calls. A create with an id already in the scene is refused (`node_exists`); delete it earlier in the same patch to replace it. Updates cannot change `id` or `type` (`identity_change`), `object` or `children` (`immutable_field`), move a node under a missing or childless parent (`invalid_parent`), or add schema issues (`invalid_update`); default gutters and downspouts a delete regenerates are addressable only in a later call (`regenerated_default`). Refusals are tool errors with JSON text `{ code, patchIndex, id, message }`. A level created without a `height`, or an update that clears it, gets the height the editor's load derives from what the level holds (an empty level: 2.5 m), one line per level in `notes`. A roof the patch makes or moves onto the storey whose walls carry it is seated on the level above those walls, one line per roof in `notes`; a new storey at or above the roof level moves it up. Refused: storey content on a roof level (`roof_level`), declaring a level that holds storey content the roof level (`roof_level_holds_storey`), floor indexes that put the roof level under a storey (`roof_level_on_top`). | `{ patches: Patch[] }` | `{ applied: number, notes?: string[] }` | | `add_level` | Add an empty level to a building, as the editor does: on top of its storeys, under its roof level (which moves up one), or below the lowest for a basement (every existing floor, the ground floor included, keeps its place). Omit `buildingId` for the scene's only building. | `{ buildingId?, position?, name?, height? }` | `{ levelId, buildingId, floorIndex, height, shiftedLevelIds? }`; refusals `building_required`, `building_not_found`, `no_building` | -| `set_code_profile` | Say which building code the project follows (`irc-2021`, `au-ncc`, `fr`; `null` clears it), stored as `site.metadata.codeProfile`, in one undo step. The checks that apply a code read it: warnings with `irc-2021`, information that names the US IRC with no code. Nothing is guessed from an address. | | `set_ground_level` | Make a level the building's ground floor, as the level panel's "Set as ground floor": the building names it, is seated so that floor stands on grade (height only, the plan stays), and the floor indexes are renumbered so it is 0 and the levels under it are the basements. | `{ levelId }` | `{ levelId, buildingId, floorElevation, gradeElevation, movedBuildingBy, renumbered, unchanged? }`; refusals `level_not_found`, `not_a_level`, `no_building`, `not_a_storey` | | `add_wall` | Add a wall to a level, straight or, with `curveOffset`, an arc. Omit `levelId` for the lowest storey. wallType railing builds a guard (default 0.9144 m high); railing sets style, posts, infill and cap; postSize sets thickness. | `{ start, end, levelId?, thickness?, height?, curveOffset?, type?, wallType?, railing? }` | `{ wallId, levelId, length }`; refusals `roof_level`, `wall_too_short`, `level_not_found`, `unknown_wall_type` | | `set_wall_type` | Apply a preset or project wall assembly to existing standard walls; copies layers and total thickness. null clears the assembly. | `{ wallIds, type }` | `{ ok, wallIds, type }`; refusals `unknown_wall_type`, `target_not_found`, `curtain_wall`, `railing_wall` | diff --git a/packages/mcp/src/resources/agent-guide.ts b/packages/mcp/src/resources/agent-guide.ts index 6005aca4f5..5990a290c0 100644 --- a/packages/mcp/src/resources/agent-guide.ts +++ b/packages/mcp/src/resources/agent-guide.ts @@ -52,7 +52,6 @@ export const AGENT_GUIDE = [ "- Finishes are given with `paint`, as the editor's Paint does: a library material found with `search_materials`, a colour, or a native material for an exact finish. `slots` and material presets are what `paint` writes, not what `apply_patch` is for.", '- Floors and ceilings are derived from rooms, not authored: walls, separators and a zone with `spaceRole: "room"` state the intent, and the structure reconciler builds the floor plate and the ceiling. Creating a slab or ceiling carrying the derived markers (`boundary` / `autoFromWalls`), or reshaping or relinking one, is refused; deleting one records that opt-out on the zone instead. A room without a floor or ceiling is expressed on its zone (`hasFloor: false`, `hasCeiling: false`), and its floor height with `floor.elevation`.', '- Manual slabs remain valid for things that are not rooms: pools, platforms, stair decks, terraces at their own elevation.', - "- `set_code_profile` says which building code the project follows (irc-2021, au-ncc or fr; null clears it), stored as the site's metadata.codeProfile, in one undo step. A project that names no code has none: nothing is guessed from an address. The checks that apply a code read it, as warnings with irc-2021 and as information that names the US IRC they used with no code.", '- A building’s levels stand on a ground line: the level at grade, named by `set_ground_level` (which seats the building so its floor stands at grade and renumbers it to floor index 0) or, until named, the lowest level whose floor is not under the ground; levels with a lower floor index are below grade. `add_level` with `position: "below"` goes one storey under the lowest level and every floor keeps its place. `list_levels` reads it as `groundLevels` and each level’s `gradeStanding` and `isGroundLevel`; `verify_scene` reports a basement the stack stands at grade (basement_at_grade; `set_ground_level` is the fix).', '- `furnish_room` skips or nudges poses that block door clear zones or overlap other items; `verify_scene` and `check_collisions` report remaining issues.', '- Adjacent rooms can share one wall (or have openings that line up). A door keeps about 0.65 m clear on both sides; furniture footprints do not overlap.', diff --git a/packages/mcp/src/tools/read-tool-annotations.test.ts b/packages/mcp/src/tools/read-tool-annotations.test.ts index 1cf16c78b9..738758e431 100644 --- a/packages/mcp/src/tools/read-tool-annotations.test.ts +++ b/packages/mcp/src/tools/read-tool-annotations.test.ts @@ -123,7 +123,6 @@ const TOOL_POLICIES = [ 'get_project_status', 'load_scene', 'redo', - 'set_code_profile', 'set_ground_level', 'set_unit_members', 'rename_scene', diff --git a/packages/mcp/src/tools/shared-tools.ts b/packages/mcp/src/tools/shared-tools.ts index 07e890cfc7..66729bf715 100644 --- a/packages/mcp/src/tools/shared-tools.ts +++ b/packages/mcp/src/tools/shared-tools.ts @@ -27,7 +27,6 @@ import { addLevelTool, addObjectTool, addWallTool, - codeProfileOutput, createRoofTool, createRoomTool, createStairTool, @@ -65,7 +64,6 @@ import { searchAssetsTool, searchMaterialsTool, setCheckpointTool, - setCodeProfileTool, setGroundLevelTool, setUnitMembersTool, setWallTypeTool, @@ -276,12 +274,6 @@ const SHARED_TOOLS: SharedTool[] = [ ...liveSyncOutput, }, }, - { - contract: setCodeProfileTool, - operation: AGENT_OPERATIONS.set_code_profile, - annotations: DESTRUCTIVE_TOOL_ANNOTATIONS, - outputSchema: { ...codeProfileOutput, ...achievedOutput, ...liveSyncOutput }, - }, { contract: setGroundLevelTool, operation: AGENT_OPERATIONS.set_ground_level, diff --git a/plugin-evals/tool-annotation-justifications.json b/plugin-evals/tool-annotation-justifications.json index 738144238c..0c26d82940 100644 --- a/plugin-evals/tool-annotation-justifications.json +++ b/plugin-evals/tool-annotation-justifications.json @@ -1007,19 +1007,6 @@ "openWorldHint": "It operates only on the connected Pascal scene and does not access the public internet." } }, - { - "name": "set_code_profile", - "annotations": { - "readOnlyHint": false, - "destructiveHint": true, - "openWorldHint": false - }, - "justifications": { - "readOnlyHint": "It is not read-only because it writes the building code the connected Pascal project follows on its site.", - "destructiveHint": "It replaces the project's single code profile (or clears it), so a wrong call changes which thresholds the checks apply; it removes no modeled content and leaves the rest of the site's metadata as it was.", - "openWorldHint": "It operates only on the connected Pascal scene and does not access the public internet." - } - }, { "name": "set_floor_foundation", "annotations": { diff --git a/scripts/openai-tool-annotation-policy.ts b/scripts/openai-tool-annotation-policy.ts index a51e85830e..98fc5b3688 100644 --- a/scripts/openai-tool-annotation-policy.ts +++ b/scripts/openai-tool-annotation-policy.ts @@ -76,7 +76,6 @@ export const EXPECTED_OPENAI_TOOL_ANNOTATIONS = { merge_zones: policy(false, true, false), move_node: policy(false, true, false), move_zone: policy(false, true, false), - set_code_profile: policy(false, true, false), move_roofs_to_roof_level: policy(false, true, false), paint: policy(false, true, false), photo_to_scene: policy(false, true, true), From d002a8d6b6117c4f6e99f827a0ce60cdb486cbdf Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 20:13:08 +0100 Subject: [PATCH 39/40] catalogue-shapes.ts: one line per polygon, the same data The baked outlines of the seven library fixtures were 2,018 lines, one coordinate pair per line. Each polygon is now one line (261 lines), under a biome-ignore-format note since the formatter would spread them again. The data is unchanged: a test outside the repository imported the committed file and the new one and compared them with toStrictEqual and by JSON.stringify (7 assets, 62 bands, 95 polygons, 1,133 points, same key order): pass. Nothing else reads the file's text. Co-Authored-By: Claude Sonnet 5.5 --- .../spatial/usage-field/catalogue-shapes.ts | 2197 ++--------------- 1 file changed, 220 insertions(+), 1977 deletions(-) diff --git a/packages/core/src/spatial/usage-field/catalogue-shapes.ts b/packages/core/src/spatial/usage-field/catalogue-shapes.ts index 54e88b38f1..23d8db6f74 100644 --- a/packages/core/src/spatial/usage-field/catalogue-shapes.ts +++ b/packages/core/src/spatial/usage-field/catalogue-shapes.ts @@ -2,2017 +2,260 @@ // biome-ignore-all lint/suspicious/noApproximativeNumericConstant: outline coordinates are data import type { GeometryShape } from '../../schema' +// biome-ignore format: generated data, one polygon per line export const CATALOGUE_SHAPES: Readonly> = { 'system/bathroom-sink': { tolerance: 0.045, bands: [ - { - y0: 0, - y1: 0.039, - polygons: [ - { - outer: [ - [0.715, -0.336], - [0.81, -0.336], - [0.81, 0.294], - [-1.015, 0.294], - [-1.015, -0.321], - [-0.985, -0.201], - [-0.58, -0.201], - [-0.58, -0.321], - [-0.55, -0.201], - [0.26, -0.201], - [0.26, -0.321], - [0.285, -0.201], - [0.695, -0.201], - ], - }, - ], - }, - { - y0: 0.039, - y1: 0.671, - polygons: [ - { - outer: [ - [0.715, -0.336], - [0.81, -0.336], - [0.81, 0.294], - [-1.015, 0.294], - [-1.015, -0.321], - ], - holes: [ - [ - [-0.98, -0.196], - [-0.985, 0.259], - [-0.58, 0.259], - [-0.58, -0.196], - ], - [ - [-0.545, -0.196], - [-0.55, 0.259], - [0.26, 0.259], - [0.26, -0.196], - ], - [ - [0.29, -0.196], - [0.285, 0.259], - [0.695, 0.259], - [0.695, -0.196], - ], - ], - }, - ], - }, - { - y0: 0.671, - y1: 0.966, - polygons: [ - { - outer: [ - [-1.015, -0.336], - [0.81, -0.336], - [0.81, 0.294], - [-1.015, 0.294], - ], - }, - ], - }, + { y0: 0, y1: 0.039, polygons: [ + { outer: [[0.715, -0.336], [0.81, -0.336], [0.81, 0.294], [-1.015, 0.294], [-1.015, -0.321], [-0.985, -0.201], [-0.58, -0.201], [-0.58, -0.321], [-0.55, -0.201], [0.26, -0.201], [0.26, -0.321], [0.285, -0.201], [0.695, -0.201]] }, + ] }, + { y0: 0.039, y1: 0.671, polygons: [ + { outer: [[0.715, -0.336], [0.81, -0.336], [0.81, 0.294], [-1.015, 0.294], [-1.015, -0.321]], holes: [[[-0.98, -0.196], [-0.985, 0.259], [-0.58, 0.259], [-0.58, -0.196]], [[-0.545, -0.196], [-0.55, 0.259], [0.26, 0.259], [0.26, -0.196]], [[0.29, -0.196], [0.285, 0.259], [0.695, 0.259], [0.695, -0.196]]] }, + ] }, + { y0: 0.671, y1: 0.966, polygons: [ + { outer: [[-1.015, -0.336], [0.81, -0.336], [0.81, 0.294], [-1.015, 0.294]] }, + ] }, ], }, 'system/bathtub': { tolerance: 0.015, bands: [ - { - y0: 0, - y1: 0.059, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.171, 0.556], - [-1.169, 0.556], - ], - }, - ], - }, - { - y0: 0.059, - y1: 0.078, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.171, 0.556], - [-1.169, 0.556], - ], - holes: [ - [ - [-0.239, -0.219], - [-0.489, -0.184], - [-0.574, -0.134], - [-0.614, -0.064], - [-0.614, 0.046], - [-0.579, 0.111], - [-0.494, 0.166], - [-0.219, 0.201], - [0.271, 0.196], - [0.516, 0.161], - [0.591, 0.116], - [0.636, 0.041], - [0.636, -0.064], - [0.606, -0.124], - [0.511, -0.189], - [0.276, -0.219], - ], - ], - }, - { - outer: [ - [-0.569, -0.069], - [-0.519, -0.054], - [-0.514, -0.024], - [-0.539, 0.006], - [-0.589, -0.009], - [-0.594, -0.039], - ], - }, - ], - }, - { - y0: 0.078, - y1: 0.098, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.171, 0.556], - [-1.169, 0.556], - ], - holes: [ - [ - [-0.224, -0.274], - [-0.509, -0.239], - [-0.629, -0.159], - [-0.674, -0.079], - [-0.674, 0.056], - [-0.619, 0.156], - [-0.514, 0.216], - [-0.239, 0.251], - [0.261, 0.251], - [0.496, 0.221], - [0.531, 0.216], - [0.636, 0.156], - [0.696, 0.056], - [0.686, -0.099], - [0.631, -0.184], - [0.536, -0.239], - [0.256, -0.274], - ], - ], - }, - ], - }, - { - y0: 0.098, - y1: 0.156, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.166, 0.551], - [-1.169, 0.551], - ], - holes: [ - [ - [-0.244, -0.304], - [-0.519, -0.269], - [-0.644, -0.194], - [-0.699, -0.094], - [-0.689, 0.091], - [-0.639, 0.176], - [-0.524, 0.246], - [-0.254, 0.281], - [0.276, 0.281], - [0.546, 0.246], - [0.661, 0.176], - [0.721, 0.071], - [0.716, -0.104], - [0.661, -0.199], - [0.546, -0.269], - [0.271, -0.304], - ], - ], - }, - ], - }, - { - y0: 0.156, - y1: 0.293, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.166, 0.551], - [-1.169, 0.551], - ], - holes: [ - [ - [-0.264, -0.334], - [-0.544, -0.299], - [-0.679, -0.214], - [-0.744, -0.094], - [-0.744, 0.071], - [-0.684, 0.186], - [-0.544, 0.276], - [-0.239, 0.316], - [0.261, 0.316], - [0.566, 0.276], - [0.706, 0.186], - [0.766, 0.071], - [0.766, -0.094], - [0.711, -0.199], - [0.566, -0.299], - [0.291, -0.334], - ], - ], - }, - ], - }, - { - y0: 0.293, - y1: 0.41, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.161, 0.546], - [-1.164, 0.551], - ], - holes: [ - [ - [-0.254, -0.359], - [-0.584, -0.314], - [-0.709, -0.234], - [-0.774, -0.124], - [-0.784, 0.081], - [-0.719, 0.206], - [-0.584, 0.291], - [-0.264, 0.336], - [0.286, 0.336], - [0.591, 0.296], - [0.741, 0.206], - [0.806, 0.081], - [0.796, -0.124], - [0.746, -0.219], - [0.606, -0.314], - [0.281, -0.359], - ], - ], - }, - ], - }, - { - y0: 0.41, - y1: 0.488, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.156, 0.546], - [-1.164, 0.546], - ], - holes: [ - [ - [-0.274, -0.374], - [-0.609, -0.329], - [-0.754, -0.234], - [-0.824, -0.099], - [-0.824, 0.081], - [-0.774, 0.176], - [-0.744, 0.221], - [-0.609, 0.306], - [-0.284, 0.351], - [0.306, 0.351], - [0.611, 0.311], - [0.766, 0.221], - [0.846, 0.081], - [0.846, -0.099], - [0.806, -0.179], - [0.766, -0.244], - [0.631, -0.329], - [0.301, -0.374], - ], - ], - }, - ], - }, - { - y0: 0.488, - y1: 0.507, - polygons: [ - { - outer: [ - [-1.169, -0.554], - [1.171, -0.554], - [1.156, 0.526], - [-1.159, 0.531], - ], - }, - ], - }, - { - y0: 0.507, - y1: 0.527, - polygons: [ - { - outer: [ - [0.061, -0.519], - [0.091, -0.514], - [0.101, -0.494], - [0.076, -0.459], - [0.336, -0.459], - [0.701, -0.404], - [0.856, -0.299], - [0.946, -0.129], - [0.946, 0.111], - [0.856, 0.276], - [0.701, 0.381], - [0.341, 0.436], - [-0.319, 0.436], - [-0.679, 0.381], - [-0.849, 0.261], - [-0.924, 0.111], - [-0.924, -0.129], - [-0.839, -0.294], - [-0.679, -0.404], - [-0.314, -0.459], - [0.061, -0.459], - [0.016, -0.474], - [0.021, -0.489], - [0.041, -0.484], - [0.046, -0.514], - ], - holes: [ - [ - [-0.274, -0.389], - [-0.634, -0.339], - [-0.784, -0.239], - [-0.854, -0.104], - [-0.854, 0.086], - [-0.809, 0.171], - [-0.779, 0.226], - [-0.624, 0.321], - [-0.284, 0.366], - [0.306, 0.366], - [0.646, 0.321], - [0.801, 0.226], - [0.876, 0.086], - [0.876, -0.104], - [0.836, -0.184], - [0.791, -0.254], - [0.656, -0.339], - [0.301, -0.389], - ], - ], - }, - ], - }, - { - y0: 0.527, - y1: 0.546, - polygons: [ - { - outer: [ - [0.061, -0.519], - [0.091, -0.514], - [0.091, -0.464], - [0.026, -0.464], - [0.016, -0.484], - [0.041, -0.484], - [0.046, -0.514], - ], - }, - { - outer: [ - [-0.309, -0.439], - [0.331, -0.439], - [0.681, -0.389], - [0.851, -0.279], - [0.866, -0.239], - [0.841, -0.274], - [0.671, -0.369], - [0.311, -0.414], - [-0.289, -0.414], - [-0.649, -0.369], - [-0.819, -0.274], - [-0.844, -0.239], - [-0.829, -0.279], - [-0.659, -0.389], - ], - }, - { - outer: [ - [-0.844, 0.216], - [-0.819, 0.251], - [-0.649, 0.346], - [-0.294, 0.391], - [0.316, 0.391], - [0.646, 0.351], - [0.826, 0.261], - [0.861, 0.216], - [0.866, 0.226], - [0.851, 0.256], - [0.686, 0.366], - [0.336, 0.416], - [-0.314, 0.416], - [-0.664, 0.366], - [-0.829, 0.256], - ], - }, - ], - }, - { - y0: 0.546, - y1: 0.566, - polygons: [ - { - outer: [ - [0.061, -0.519], - [0.091, -0.514], - [0.091, -0.464], - [0.026, -0.464], - [0.016, -0.484], - [0.041, -0.484], - [0.046, -0.514], - ], - }, - ], - }, - { - y0: 0.566, - y1: 0.605, - polygons: [ - { - outer: [ - [0.061, -0.519], - [0.151, -0.469], - [0.171, -0.429], - [0.126, -0.429], - [0.051, -0.464], - [0.046, -0.479], - [0.026, -0.464], - [0.016, -0.484], - [0.041, -0.484], - ], - }, - ], - }, - { - y0: 0.605, - y1: 0.683, - polygons: [ - { - outer: [ - [0.021, -0.489], - [0.041, -0.484], - [0.031, -0.464], - [0.016, -0.474], - ], - }, - ], - }, - { - y0: 0.683, - y1: 0.702, - polygons: [ - { - outer: [ - [0.021, -0.489], - [0.041, -0.484], - [0.031, -0.464], - [0.016, -0.474], - ], - }, - { - outer: [ - [0.026, -0.329], - [0.041, -0.319], - [0.031, -0.299], - [0.016, -0.309], - ], - }, - ], - }, - { - y0: 0.702, - y1: 0.722, - polygons: [ - { - outer: [ - [0.021, -0.489], - [0.041, -0.484], - [0.031, -0.464], - [0.016, -0.474], - ], - }, - { - outer: [ - [0.026, -0.334], - [0.041, -0.324], - [0.036, -0.304], - [0.016, -0.309], - ], - }, - ], - }, - { - y0: 0.722, - y1: 0.742, - polygons: [ - { - outer: [ - [0.021, -0.489], - [0.041, -0.484], - [0.031, -0.459], - [0.016, -0.464], - ], - }, - { - outer: [ - [0.026, -0.339], - [0.041, -0.329], - [0.036, -0.309], - [0.016, -0.314], - ], - }, - ], - }, - { - y0: 0.742, - y1: 0.761, - polygons: [ - { - outer: [ - [0.021, -0.484], - [0.041, -0.474], - [0.031, -0.314], - [0.016, -0.319], - ], - }, - ], - }, - { - y0: 0.761, - y1: 0.781, - polygons: [ - { - outer: [ - [0.021, -0.469], - [0.041, -0.449], - [0.031, -0.319], - [0.016, -0.324], - ], - }, - ], - }, + { y0: 0, y1: 0.059, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.171, 0.556], [-1.169, 0.556]] }, + ] }, + { y0: 0.059, y1: 0.078, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.171, 0.556], [-1.169, 0.556]], holes: [[[-0.239, -0.219], [-0.489, -0.184], [-0.574, -0.134], [-0.614, -0.064], [-0.614, 0.046], [-0.579, 0.111], [-0.494, 0.166], [-0.219, 0.201], [0.271, 0.196], [0.516, 0.161], [0.591, 0.116], [0.636, 0.041], [0.636, -0.064], [0.606, -0.124], [0.511, -0.189], [0.276, -0.219]]] }, + { outer: [[-0.569, -0.069], [-0.519, -0.054], [-0.514, -0.024], [-0.539, 0.006], [-0.589, -0.009], [-0.594, -0.039]] }, + ] }, + { y0: 0.078, y1: 0.098, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.171, 0.556], [-1.169, 0.556]], holes: [[[-0.224, -0.274], [-0.509, -0.239], [-0.629, -0.159], [-0.674, -0.079], [-0.674, 0.056], [-0.619, 0.156], [-0.514, 0.216], [-0.239, 0.251], [0.261, 0.251], [0.496, 0.221], [0.531, 0.216], [0.636, 0.156], [0.696, 0.056], [0.686, -0.099], [0.631, -0.184], [0.536, -0.239], [0.256, -0.274]]] }, + ] }, + { y0: 0.098, y1: 0.156, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.166, 0.551], [-1.169, 0.551]], holes: [[[-0.244, -0.304], [-0.519, -0.269], [-0.644, -0.194], [-0.699, -0.094], [-0.689, 0.091], [-0.639, 0.176], [-0.524, 0.246], [-0.254, 0.281], [0.276, 0.281], [0.546, 0.246], [0.661, 0.176], [0.721, 0.071], [0.716, -0.104], [0.661, -0.199], [0.546, -0.269], [0.271, -0.304]]] }, + ] }, + { y0: 0.156, y1: 0.293, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.166, 0.551], [-1.169, 0.551]], holes: [[[-0.264, -0.334], [-0.544, -0.299], [-0.679, -0.214], [-0.744, -0.094], [-0.744, 0.071], [-0.684, 0.186], [-0.544, 0.276], [-0.239, 0.316], [0.261, 0.316], [0.566, 0.276], [0.706, 0.186], [0.766, 0.071], [0.766, -0.094], [0.711, -0.199], [0.566, -0.299], [0.291, -0.334]]] }, + ] }, + { y0: 0.293, y1: 0.41, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.161, 0.546], [-1.164, 0.551]], holes: [[[-0.254, -0.359], [-0.584, -0.314], [-0.709, -0.234], [-0.774, -0.124], [-0.784, 0.081], [-0.719, 0.206], [-0.584, 0.291], [-0.264, 0.336], [0.286, 0.336], [0.591, 0.296], [0.741, 0.206], [0.806, 0.081], [0.796, -0.124], [0.746, -0.219], [0.606, -0.314], [0.281, -0.359]]] }, + ] }, + { y0: 0.41, y1: 0.488, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.156, 0.546], [-1.164, 0.546]], holes: [[[-0.274, -0.374], [-0.609, -0.329], [-0.754, -0.234], [-0.824, -0.099], [-0.824, 0.081], [-0.774, 0.176], [-0.744, 0.221], [-0.609, 0.306], [-0.284, 0.351], [0.306, 0.351], [0.611, 0.311], [0.766, 0.221], [0.846, 0.081], [0.846, -0.099], [0.806, -0.179], [0.766, -0.244], [0.631, -0.329], [0.301, -0.374]]] }, + ] }, + { y0: 0.488, y1: 0.507, polygons: [ + { outer: [[-1.169, -0.554], [1.171, -0.554], [1.156, 0.526], [-1.159, 0.531]] }, + ] }, + { y0: 0.507, y1: 0.527, polygons: [ + { outer: [[0.061, -0.519], [0.091, -0.514], [0.101, -0.494], [0.076, -0.459], [0.336, -0.459], [0.701, -0.404], [0.856, -0.299], [0.946, -0.129], [0.946, 0.111], [0.856, 0.276], [0.701, 0.381], [0.341, 0.436], [-0.319, 0.436], [-0.679, 0.381], [-0.849, 0.261], [-0.924, 0.111], [-0.924, -0.129], [-0.839, -0.294], [-0.679, -0.404], [-0.314, -0.459], [0.061, -0.459], [0.016, -0.474], [0.021, -0.489], [0.041, -0.484], [0.046, -0.514]], holes: [[[-0.274, -0.389], [-0.634, -0.339], [-0.784, -0.239], [-0.854, -0.104], [-0.854, 0.086], [-0.809, 0.171], [-0.779, 0.226], [-0.624, 0.321], [-0.284, 0.366], [0.306, 0.366], [0.646, 0.321], [0.801, 0.226], [0.876, 0.086], [0.876, -0.104], [0.836, -0.184], [0.791, -0.254], [0.656, -0.339], [0.301, -0.389]]] }, + ] }, + { y0: 0.527, y1: 0.546, polygons: [ + { outer: [[0.061, -0.519], [0.091, -0.514], [0.091, -0.464], [0.026, -0.464], [0.016, -0.484], [0.041, -0.484], [0.046, -0.514]] }, + { outer: [[-0.309, -0.439], [0.331, -0.439], [0.681, -0.389], [0.851, -0.279], [0.866, -0.239], [0.841, -0.274], [0.671, -0.369], [0.311, -0.414], [-0.289, -0.414], [-0.649, -0.369], [-0.819, -0.274], [-0.844, -0.239], [-0.829, -0.279], [-0.659, -0.389]] }, + { outer: [[-0.844, 0.216], [-0.819, 0.251], [-0.649, 0.346], [-0.294, 0.391], [0.316, 0.391], [0.646, 0.351], [0.826, 0.261], [0.861, 0.216], [0.866, 0.226], [0.851, 0.256], [0.686, 0.366], [0.336, 0.416], [-0.314, 0.416], [-0.664, 0.366], [-0.829, 0.256]] }, + ] }, + { y0: 0.546, y1: 0.566, polygons: [ + { outer: [[0.061, -0.519], [0.091, -0.514], [0.091, -0.464], [0.026, -0.464], [0.016, -0.484], [0.041, -0.484], [0.046, -0.514]] }, + ] }, + { y0: 0.566, y1: 0.605, polygons: [ + { outer: [[0.061, -0.519], [0.151, -0.469], [0.171, -0.429], [0.126, -0.429], [0.051, -0.464], [0.046, -0.479], [0.026, -0.464], [0.016, -0.484], [0.041, -0.484]] }, + ] }, + { y0: 0.605, y1: 0.683, polygons: [ + { outer: [[0.021, -0.489], [0.041, -0.484], [0.031, -0.464], [0.016, -0.474]] }, + ] }, + { y0: 0.683, y1: 0.702, polygons: [ + { outer: [[0.021, -0.489], [0.041, -0.484], [0.031, -0.464], [0.016, -0.474]] }, + { outer: [[0.026, -0.329], [0.041, -0.319], [0.031, -0.299], [0.016, -0.309]] }, + ] }, + { y0: 0.702, y1: 0.722, polygons: [ + { outer: [[0.021, -0.489], [0.041, -0.484], [0.031, -0.464], [0.016, -0.474]] }, + { outer: [[0.026, -0.334], [0.041, -0.324], [0.036, -0.304], [0.016, -0.309]] }, + ] }, + { y0: 0.722, y1: 0.742, polygons: [ + { outer: [[0.021, -0.489], [0.041, -0.484], [0.031, -0.459], [0.016, -0.464]] }, + { outer: [[0.026, -0.339], [0.041, -0.329], [0.036, -0.309], [0.016, -0.314]] }, + ] }, + { y0: 0.742, y1: 0.761, polygons: [ + { outer: [[0.021, -0.484], [0.041, -0.474], [0.031, -0.314], [0.016, -0.319]] }, + ] }, + { y0: 0.761, y1: 0.781, polygons: [ + { outer: [[0.021, -0.469], [0.041, -0.449], [0.031, -0.319], [0.016, -0.324]] }, + ] }, ], }, 'system/fridge': { tolerance: 0.009, bands: [ - { - y0: 0, - y1: 0.06, - polygons: [ - { - outer: [ - [-0.341, -0.306], - [0.344, -0.306], - [0.344, 0.309], - [-0.341, 0.309], - ], - }, - ], - }, - { - y0: 0.06, - y1: 1.858, - polygons: [ - { - outer: [ - [-0.341, -0.306], - [0.344, -0.306], - [0.344, 0.294], - [0.349, 0.294], - [0.349, 0.359], - [0.209, 0.369], - [0.209, 0.374], - [0.159, 0.374], - [0.159, 0.379], - [-0.161, 0.379], - [-0.161, 0.374], - [-0.211, 0.374], - [-0.211, 0.369], - [-0.346, 0.359], - [-0.346, 0.294], - [-0.341, 0.294], - ], - }, - ], - }, - { - y0: 1.858, - y1: 1.918, - polygons: [ - { - outer: [ - [-0.346, -0.306], - [0.349, -0.306], - [0.349, 0.389], - [0.269, 0.394], - [0.269, 0.399], - [0.219, 0.399], - [0.219, 0.404], - [0.169, 0.404], - [0.169, 0.409], - [-0.171, 0.409], - [-0.171, 0.404], - [-0.221, 0.404], - [-0.221, 0.399], - [-0.271, 0.399], - [-0.271, 0.394], - [-0.346, 0.389], - ], - }, - ], - }, + { y0: 0, y1: 0.06, polygons: [ + { outer: [[-0.341, -0.306], [0.344, -0.306], [0.344, 0.309], [-0.341, 0.309]] }, + ] }, + { y0: 0.06, y1: 1.858, polygons: [ + { outer: [[-0.341, -0.306], [0.344, -0.306], [0.344, 0.294], [0.349, 0.294], [0.349, 0.359], [0.209, 0.369], [0.209, 0.374], [0.159, 0.374], [0.159, 0.379], [-0.161, 0.379], [-0.161, 0.374], [-0.211, 0.374], [-0.211, 0.369], [-0.346, 0.359], [-0.346, 0.294], [-0.341, 0.294]] }, + ] }, + { y0: 1.858, y1: 1.918, polygons: [ + { outer: [[-0.346, -0.306], [0.349, -0.306], [0.349, 0.389], [0.269, 0.394], [0.269, 0.399], [0.219, 0.399], [0.219, 0.404], [0.169, 0.404], [0.169, 0.409], [-0.171, 0.409], [-0.171, 0.404], [-0.221, 0.404], [-0.221, 0.399], [-0.271, 0.399], [-0.271, 0.394], [-0.346, 0.389]] }, + ] }, ], }, 'system/shower-square': { tolerance: 0.015, bands: [ - { - y0: 0, - y1: 0.04, - polygons: [ - { - outer: [ - [-0.785, -0.001], - [-0.015, -0.001], - [0, 0.014], - [0, 0.764], - [-0.015, 0.789], - [-0.05, 0.804], - [-0.75, 0.804], - [-0.785, 0.789], - [-0.8, 0.764], - [-0.8, 0.014], - ], - }, - ], - }, - { - y0: 0.04, - y1: 0.1, - polygons: [ - { - outer: [ - [-0.785, -0.001], - [-0.015, -0.001], - [0, 0.014], - [0, 0.764], - [-0.015, 0.789], - [-0.05, 0.804], - [-0.75, 0.804], - [-0.785, 0.789], - [-0.8, 0.764], - [-0.8, 0.014], - ], - holes: [ - [ - [-0.71, 0.064], - [-0.735, 0.084], - [-0.725, 0.709], - [-0.695, 0.729], - [-0.09, 0.724], - [-0.07, 0.694], - [-0.065, 0.084], - [-0.085, 0.064], - ], - ], - }, - { - outer: [ - [-0.43, 0.394], - [-0.375, 0.404], - [-0.38, 0.464], - [-0.445, 0.459], - [-0.45, 0.419], - ], - }, - ], - }, - { - y0: 0.1, - y1: 0.12, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.02, -0.001], - [0, 0.014], - [0, 0.759], - [-0.025, 0.794], - [-0.765, 0.799], - [-0.79, 0.779], - [-0.8, 0.014], - ], - holes: [ - [ - [-0.7, 0.059], - [-0.74, 0.094], - [-0.725, 0.709], - [-0.7, 0.729], - [-0.09, 0.724], - [-0.07, 0.699], - [-0.065, 0.079], - [-0.095, 0.059], - ], - ], - }, - ], - }, - { - y0: 0.12, - y1: 0.88, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - ], - }, - { - y0: 0.88, - y1: 0.9, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.565, -0.001], - [-0.255, -0.001], - [-0.255, 0.124], - [-0.56, 0.129], - ], - }, - { - outer: [ - [-0.43, 0.149], - [-0.385, 0.154], - [-0.38, 0.234], - [-0.415, 0.239], - [-0.445, 0.224], - ], - }, - ], - }, - { - y0: 0.9, - y1: 0.96, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.565, -0.001], - [-0.255, -0.001], - [-0.255, 0.139], - [-0.375, 0.144], - [-0.36, 0.229], - [-0.445, 0.239], - [-0.46, 0.209], - [-0.445, 0.144], - [-0.565, 0.139], - ], - }, - ], - }, - { - y0: 0.96, - y1: 0.98, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.565, -0.001], - [-0.255, -0.001], - [-0.255, 0.129], - [-0.56, 0.134], - ], - }, - { - outer: [ - [-0.43, 0.144], - [-0.38, 0.149], - [-0.375, 0.234], - [-0.43, 0.239], - [-0.445, 0.219], - [-0.48, 0.214], - [-0.475, 0.189], - [-0.44, 0.179], - ], - }, - ], - }, - { - y0: 0.98, - y1: 1.04, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.39, 0.074], - [-0.395, 0.114], - [-0.43, 0.109], - ], - }, - { - outer: [ - [-0.525, 0.179], - [-0.455, 0.184], - [-0.435, 0.204], - [-0.45, 0.219], - [-0.53, 0.224], - [-0.555, 0.199], - ], - }, - ], - }, - { - y0: 1.04, - y1: 1.08, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.39, 0.074], - [-0.395, 0.114], - [-0.43, 0.109], - ], - }, - { - outer: [ - [-0.55, 0.179], - [-0.5, 0.184], - [-0.5, 0.219], - [-0.56, 0.219], - ], - }, - ], - }, - { - y0: 1.08, - y1: 1.54, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.39, 0.074], - [-0.395, 0.114], - [-0.43, 0.109], - ], - }, - ], - }, - { - y0: 1.54, - y1: 1.62, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.39, 0.074], - [-0.395, 0.114], - [-0.43, 0.109], - ], - }, - { - outer: [ - [-0.44, 0.259], - [-0.355, 0.264], - [-0.305, 0.289], - [-0.255, 0.344], - [-0.235, 0.399], - [-0.235, 0.469], - [-0.255, 0.524], - [-0.305, 0.579], - [-0.355, 0.604], - [-0.43, 0.609], - [-0.505, 0.584], - [-0.545, 0.549], - [-0.58, 0.484], - [-0.585, 0.414], - [-0.56, 0.339], - [-0.5, 0.279], - ], - }, - ], - }, - { - y0: 1.62, - y1: 1.66, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.39, 0.074], - [-0.395, 0.114], - [-0.43, 0.109], - ], - }, - { - outer: [ - [-0.41, 0.389], - [-0.38, 0.399], - [-0.365, 0.429], - [-0.39, 0.474], - [-0.43, 0.474], - [-0.45, 0.454], - [-0.445, 0.404], - ], - }, - ], - }, - { - y0: 1.66, - y1: 1.7, - polygons: [ - { - outer: [ - [-0.78, -0.001], - [-0.76, -0.001], - [-0.76, 0.749], - [-0.74, 0.764], - [-0.01, 0.764], - [-0.01, 0.779], - [-0.745, 0.779], - [-0.775, 0.759], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.385, 0.084], - [-0.405, 0.119], - [-0.435, 0.094], - ], - }, - { - outer: [ - [-0.42, 0.409], - [-0.39, 0.414], - [-0.39, 0.454], - [-0.43, 0.449], - ], - }, - ], - }, - { - y0: 1.7, - y1: 1.74, - polygons: [ - { - outer: [ - [-0.8, -0.001], - [-0.735, -0.001], - [-0.725, 0.709], - [-0.7, 0.729], - [-0.02, 0.729], - [-0.02, 0.804], - [-0.75, 0.804], - [-0.785, 0.789], - [-0.8, 0.764], - ], - }, - { - outer: [ - [-0.42, 0.069], - [-0.385, 0.084], - [-0.39, 0.129], - [-0.405, 0.139], - [-0.435, 0.109], - ], - }, - { - outer: [ - [-0.415, 0.389], - [-0.385, 0.409], - [-0.385, 0.439], - [-0.405, 0.459], - [-0.435, 0.434], - ], - }, - ], - }, - { - y0: 1.74, - y1: 1.78, - polygons: [ - { - outer: [ - [-0.8, -0.001], - [-0.735, -0.001], - [-0.725, 0.709], - [-0.7, 0.729], - [-0.02, 0.729], - [-0.02, 0.804], - [-0.75, 0.804], - [-0.785, 0.789], - [-0.8, 0.764], - ], - }, - { - outer: [ - [-0.415, 0.079], - [-0.385, 0.099], - [-0.385, 0.429], - [-0.405, 0.449], - [-0.435, 0.424], - [-0.435, 0.104], - ], - }, - ], - }, - { - y0: 1.78, - y1: 1.8, - polygons: [ - { - outer: [ - [-0.8, -0.001], - [-0.735, 0.004], - [-0.725, 0.714], - [-0.705, 0.729], - [-0.025, 0.729], - [-0.01, 0.744], - [-0.015, 0.799], - [-0.765, 0.799], - [-0.79, 0.779], - ], - }, - { - outer: [ - [-0.41, 0.114], - [-0.39, 0.124], - [-0.385, 0.164], - [-0.385, 0.364], - [-0.4, 0.409], - [-0.43, 0.394], - [-0.43, 0.129], - ], - }, - ], - }, + { y0: 0, y1: 0.04, polygons: [ + { outer: [[-0.785, -0.001], [-0.015, -0.001], [0, 0.014], [0, 0.764], [-0.015, 0.789], [-0.05, 0.804], [-0.75, 0.804], [-0.785, 0.789], [-0.8, 0.764], [-0.8, 0.014]] }, + ] }, + { y0: 0.04, y1: 0.1, polygons: [ + { outer: [[-0.785, -0.001], [-0.015, -0.001], [0, 0.014], [0, 0.764], [-0.015, 0.789], [-0.05, 0.804], [-0.75, 0.804], [-0.785, 0.789], [-0.8, 0.764], [-0.8, 0.014]], holes: [[[-0.71, 0.064], [-0.735, 0.084], [-0.725, 0.709], [-0.695, 0.729], [-0.09, 0.724], [-0.07, 0.694], [-0.065, 0.084], [-0.085, 0.064]]] }, + { outer: [[-0.43, 0.394], [-0.375, 0.404], [-0.38, 0.464], [-0.445, 0.459], [-0.45, 0.419]] }, + ] }, + { y0: 0.1, y1: 0.12, polygons: [ + { outer: [[-0.78, -0.001], [-0.02, -0.001], [0, 0.014], [0, 0.759], [-0.025, 0.794], [-0.765, 0.799], [-0.79, 0.779], [-0.8, 0.014]], holes: [[[-0.7, 0.059], [-0.74, 0.094], [-0.725, 0.709], [-0.7, 0.729], [-0.09, 0.724], [-0.07, 0.699], [-0.065, 0.079], [-0.095, 0.059]]] }, + ] }, + { y0: 0.12, y1: 0.88, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + ] }, + { y0: 0.88, y1: 0.9, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.565, -0.001], [-0.255, -0.001], [-0.255, 0.124], [-0.56, 0.129]] }, + { outer: [[-0.43, 0.149], [-0.385, 0.154], [-0.38, 0.234], [-0.415, 0.239], [-0.445, 0.224]] }, + ] }, + { y0: 0.9, y1: 0.96, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.565, -0.001], [-0.255, -0.001], [-0.255, 0.139], [-0.375, 0.144], [-0.36, 0.229], [-0.445, 0.239], [-0.46, 0.209], [-0.445, 0.144], [-0.565, 0.139]] }, + ] }, + { y0: 0.96, y1: 0.98, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.565, -0.001], [-0.255, -0.001], [-0.255, 0.129], [-0.56, 0.134]] }, + { outer: [[-0.43, 0.144], [-0.38, 0.149], [-0.375, 0.234], [-0.43, 0.239], [-0.445, 0.219], [-0.48, 0.214], [-0.475, 0.189], [-0.44, 0.179]] }, + ] }, + { y0: 0.98, y1: 1.04, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.42, 0.069], [-0.39, 0.074], [-0.395, 0.114], [-0.43, 0.109]] }, + { outer: [[-0.525, 0.179], [-0.455, 0.184], [-0.435, 0.204], [-0.45, 0.219], [-0.53, 0.224], [-0.555, 0.199]] }, + ] }, + { y0: 1.04, y1: 1.08, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.42, 0.069], [-0.39, 0.074], [-0.395, 0.114], [-0.43, 0.109]] }, + { outer: [[-0.55, 0.179], [-0.5, 0.184], [-0.5, 0.219], [-0.56, 0.219]] }, + ] }, + { y0: 1.08, y1: 1.54, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.42, 0.069], [-0.39, 0.074], [-0.395, 0.114], [-0.43, 0.109]] }, + ] }, + { y0: 1.54, y1: 1.62, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.42, 0.069], [-0.39, 0.074], [-0.395, 0.114], [-0.43, 0.109]] }, + { outer: [[-0.44, 0.259], [-0.355, 0.264], [-0.305, 0.289], [-0.255, 0.344], [-0.235, 0.399], [-0.235, 0.469], [-0.255, 0.524], [-0.305, 0.579], [-0.355, 0.604], [-0.43, 0.609], [-0.505, 0.584], [-0.545, 0.549], [-0.58, 0.484], [-0.585, 0.414], [-0.56, 0.339], [-0.5, 0.279]] }, + ] }, + { y0: 1.62, y1: 1.66, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.42, 0.069], [-0.39, 0.074], [-0.395, 0.114], [-0.43, 0.109]] }, + { outer: [[-0.41, 0.389], [-0.38, 0.399], [-0.365, 0.429], [-0.39, 0.474], [-0.43, 0.474], [-0.45, 0.454], [-0.445, 0.404]] }, + ] }, + { y0: 1.66, y1: 1.7, polygons: [ + { outer: [[-0.78, -0.001], [-0.76, -0.001], [-0.76, 0.749], [-0.74, 0.764], [-0.01, 0.764], [-0.01, 0.779], [-0.745, 0.779], [-0.775, 0.759]] }, + { outer: [[-0.42, 0.069], [-0.385, 0.084], [-0.405, 0.119], [-0.435, 0.094]] }, + { outer: [[-0.42, 0.409], [-0.39, 0.414], [-0.39, 0.454], [-0.43, 0.449]] }, + ] }, + { y0: 1.7, y1: 1.74, polygons: [ + { outer: [[-0.8, -0.001], [-0.735, -0.001], [-0.725, 0.709], [-0.7, 0.729], [-0.02, 0.729], [-0.02, 0.804], [-0.75, 0.804], [-0.785, 0.789], [-0.8, 0.764]] }, + { outer: [[-0.42, 0.069], [-0.385, 0.084], [-0.39, 0.129], [-0.405, 0.139], [-0.435, 0.109]] }, + { outer: [[-0.415, 0.389], [-0.385, 0.409], [-0.385, 0.439], [-0.405, 0.459], [-0.435, 0.434]] }, + ] }, + { y0: 1.74, y1: 1.78, polygons: [ + { outer: [[-0.8, -0.001], [-0.735, -0.001], [-0.725, 0.709], [-0.7, 0.729], [-0.02, 0.729], [-0.02, 0.804], [-0.75, 0.804], [-0.785, 0.789], [-0.8, 0.764]] }, + { outer: [[-0.415, 0.079], [-0.385, 0.099], [-0.385, 0.429], [-0.405, 0.449], [-0.435, 0.424], [-0.435, 0.104]] }, + ] }, + { y0: 1.78, y1: 1.8, polygons: [ + { outer: [[-0.8, -0.001], [-0.735, 0.004], [-0.725, 0.714], [-0.705, 0.729], [-0.025, 0.729], [-0.01, 0.744], [-0.015, 0.799], [-0.765, 0.799], [-0.79, 0.779]] }, + { outer: [[-0.41, 0.114], [-0.39, 0.124], [-0.385, 0.164], [-0.385, 0.364], [-0.4, 0.409], [-0.43, 0.394], [-0.43, 0.129]] }, + ] }, ], }, 'system/stove': { tolerance: 0.009, bands: [ - { - y0: 0, - y1: 0.118, - polygons: [ - { - outer: [ - [-0.399, -0.275], - [-0.344, -0.275], - [-0.344, -0.22], - [-0.399, -0.22], - ], - }, - { - outer: [ - [0.341, -0.275], - [0.396, -0.275], - [0.396, -0.22], - [0.341, -0.22], - ], - }, - { - outer: [ - [-0.399, 0.22], - [-0.344, 0.22], - [-0.344, 0.275], - [-0.399, 0.275], - ], - }, - { - outer: [ - [0.341, 0.22], - [0.396, 0.22], - [0.396, 0.275], - [0.341, 0.275], - ], - }, - ], - }, - { - y0: 0.118, - y1: 0.63, - polygons: [ - { - outer: [ - [-0.464, -0.32], - [0.456, -0.32], - [0.456, 0.335], - [0.426, 0.335], - [0.421, 0.34], - [0.421, 0.385], - [0.361, 0.385], - [0.361, 0.335], - [0.296, 0.335], - [0.286, 0.35], - [-0.394, 0.35], - [-0.404, 0.335], - [-0.464, 0.335], - ], - }, - ], - }, - { - y0: 0.63, - y1: 0.67, - polygons: [ - { - outer: [ - [-0.464, -0.32], - [0.456, -0.32], - [0.456, 0.335], - [0.296, 0.335], - [0.286, 0.35], - [0.251, 0.35], - [0.251, 0.43], - [-0.364, 0.43], - [-0.364, 0.35], - [-0.394, 0.35], - [-0.404, 0.335], - [-0.464, 0.335], - ], - holes: [ - [ - [-0.339, 0.35], - [-0.344, 0.35], - [-0.344, 0.4], - [0.231, 0.4], - [0.231, 0.35], - ], - ], - }, - ], - }, - { - y0: 0.67, - y1: 0.788, - polygons: [ - { - outer: [ - [-0.464, -0.32], - [0.456, -0.32], - [0.456, 0.335], - [0.296, 0.335], - [0.296, 0.385], - [0.241, 0.385], - [0.241, 0.35], - [0.196, 0.35], - [0.196, 0.385], - [0.136, 0.385], - [0.136, 0.35], - [0.031, 0.35], - [0.031, 0.385], - [-0.029, 0.385], - [-0.029, 0.35], - [-0.074, 0.35], - [-0.074, 0.385], - [-0.129, 0.385], - [-0.129, 0.35], - [-0.239, 0.35], - [-0.239, 0.385], - [-0.294, 0.385], - [-0.294, 0.35], - [-0.339, 0.35], - [-0.339, 0.385], - [-0.399, 0.385], - [-0.399, 0.34], - [-0.404, 0.335], - [-0.419, 0.335], - [-0.419, 0.34], - [-0.464, 0.335], - ], - }, - ], - }, - { - y0: 0.788, - y1: 0.827, - polygons: [ - { - outer: [ - [-0.464, -0.325], - [0.456, -0.325], - [0.456, 0.34], - [-0.464, 0.34], - ], - }, - ], - }, - { - y0: 0.827, - y1: 0.847, - polygons: [ - { - outer: [ - [-0.449, -0.305], - [0.446, -0.305], - [0.446, -0.15], - [0.451, -0.15], - [0.451, -0.135], - [0.446, -0.135], - [0.446, 0.325], - [-0.449, 0.325], - ], - holes: [ - [ - [-0.424, -0.285], - [-0.429, -0.285], - [-0.429, -0.15], - [-0.334, -0.15], - [-0.334, -0.165], - [-0.324, -0.175], - [-0.314, -0.175], - [-0.314, -0.18], - [-0.274, -0.175], - [-0.264, -0.165], - [-0.264, -0.15], - [-0.174, -0.15], - [-0.174, -0.285], - [-0.294, -0.285], - [-0.294, -0.185], - [-0.304, -0.185], - [-0.304, -0.285], - ], - [ - [-0.134, -0.285], - [-0.139, -0.285], - [-0.139, -0.15], - [-0.049, -0.15], - [-0.044, -0.17], - [-0.024, -0.175], - [-0.024, -0.18], - [0.016, -0.175], - [0.026, -0.145], - [0.036, -0.145], - [0.036, -0.15], - [0.121, -0.15], - [0.121, -0.285], - [-0.004, -0.285], - [-0.004, -0.185], - [-0.019, -0.185], - [-0.019, -0.285], - ], - [ - [0.161, -0.285], - [0.156, -0.285], - [0.156, -0.15], - [0.246, -0.15], - [0.246, -0.145], - [0.256, -0.145], - [0.261, -0.17], - [0.281, -0.175], - [0.281, -0.18], - [0.321, -0.175], - [0.331, -0.145], - [0.346, -0.145], - [0.346, -0.15], - [0.426, -0.15], - [0.426, -0.285], - [0.301, -0.285], - [0.301, -0.185], - [0.286, -0.185], - [0.286, -0.285], - ], - [ - [0.031, -0.14], - [0.026, -0.14], - [0.016, -0.11], - [-0.009, -0.105], - [-0.004, -0.1], - [-0.004, 0.015], - [0.121, 0.015], - [0.121, -0.135], - [0.036, -0.135], - ], - [ - [0.251, -0.14], - [0.246, -0.135], - [0.156, -0.135], - [0.156, 0.015], - [0.286, 0.015], - [0.286, -0.1], - [0.291, -0.105], - [0.266, -0.11], - [0.261, -0.125], - [0.256, -0.125], - [0.256, -0.14], - ], - [ - [0.336, -0.14], - [0.331, -0.14], - [0.321, -0.11], - [0.296, -0.105], - [0.301, -0.1], - [0.301, 0.015], - [0.426, 0.015], - [0.426, -0.135], - [0.346, -0.135], - [0.346, -0.14], - ], - [ - [-0.424, -0.135], - [-0.429, -0.135], - [-0.429, 0.015], - [-0.304, 0.015], - [-0.304, -0.105], - [-0.324, -0.11], - [-0.334, -0.12], - [-0.334, -0.135], - ], - [ - [-0.259, -0.135], - [-0.264, -0.135], - [-0.264, -0.12], - [-0.274, -0.11], - [-0.294, -0.105], - [-0.294, 0.015], - [-0.174, 0.015], - [-0.174, -0.135], - ], - [ - [-0.134, -0.135], - [-0.139, -0.135], - [-0.139, 0.015], - [-0.019, 0.015], - [-0.019, -0.1], - [-0.014, -0.105], - [-0.039, -0.11], - [-0.049, -0.135], - ], - [ - [-0.424, 0.03], - [-0.429, 0.03], - [-0.429, 0.15], - [-0.334, 0.15], - [-0.329, 0.125], - [-0.304, 0.12], - [-0.304, 0.03], - ], - [ - [-0.289, 0.03], - [-0.294, 0.03], - [-0.294, 0.12], - [-0.269, 0.125], - [-0.264, 0.15], - [-0.174, 0.15], - [-0.174, 0.03], - ], - [ - [-0.134, 0.03], - [-0.139, 0.03], - [-0.139, 0.15], - [-0.049, 0.15], - [-0.044, 0.13], - [-0.019, 0.12], - [-0.019, 0.03], - ], - [ - [0.001, 0.03], - [-0.004, 0.03], - [-0.004, 0.115], - [-0.009, 0.12], - [0.016, 0.125], - [0.026, 0.15], - [0.121, 0.15], - [0.121, 0.03], - ], - [ - [0.161, 0.03], - [0.156, 0.03], - [0.156, 0.15], - [0.256, 0.15], - [0.261, 0.13], - [0.286, 0.12], - [0.286, 0.03], - ], - [ - [0.306, 0.03], - [0.301, 0.03], - [0.301, 0.115], - [0.296, 0.12], - [0.321, 0.125], - [0.331, 0.15], - [0.426, 0.15], - [0.426, 0.03], - ], - [ - [-0.339, 0.16], - [-0.344, 0.165], - [-0.429, 0.165], - [-0.429, 0.305], - [-0.304, 0.305], - [-0.304, 0.2], - [-0.294, 0.2], - [-0.294, 0.305], - [-0.174, 0.305], - [-0.174, 0.165], - [-0.264, 0.165], - [-0.274, 0.19], - [-0.309, 0.195], - [-0.309, 0.19], - [-0.329, 0.185], - ], - [ - [0.031, 0.16], - [0.026, 0.16], - [0.021, 0.18], - [0.011, 0.19], - [0.001, 0.19], - [0.001, 0.195], - [-0.024, 0.195], - [-0.024, 0.19], - [-0.044, 0.185], - [-0.049, 0.165], - [-0.139, 0.165], - [-0.139, 0.305], - [-0.019, 0.305], - [-0.019, 0.2], - [-0.004, 0.2], - [-0.004, 0.305], - [0.121, 0.305], - [0.121, 0.165], - [0.036, 0.165], - ], - [ - [0.251, 0.16], - [0.246, 0.165], - [0.156, 0.165], - [0.156, 0.305], - [0.286, 0.305], - [0.286, 0.2], - [0.301, 0.2], - [0.301, 0.305], - [0.426, 0.305], - [0.426, 0.165], - [0.346, 0.165], - [0.346, 0.16], - [0.331, 0.16], - [0.331, 0.17], - [0.326, 0.17], - [0.326, 0.18], - [0.316, 0.19], - [0.281, 0.195], - [0.281, 0.19], - [0.261, 0.185], - [0.261, 0.17], - ], - ], - }, - ], - }, + { y0: 0, y1: 0.118, polygons: [ + { outer: [[-0.399, -0.275], [-0.344, -0.275], [-0.344, -0.22], [-0.399, -0.22]] }, + { outer: [[0.341, -0.275], [0.396, -0.275], [0.396, -0.22], [0.341, -0.22]] }, + { outer: [[-0.399, 0.22], [-0.344, 0.22], [-0.344, 0.275], [-0.399, 0.275]] }, + { outer: [[0.341, 0.22], [0.396, 0.22], [0.396, 0.275], [0.341, 0.275]] }, + ] }, + { y0: 0.118, y1: 0.63, polygons: [ + { outer: [[-0.464, -0.32], [0.456, -0.32], [0.456, 0.335], [0.426, 0.335], [0.421, 0.34], [0.421, 0.385], [0.361, 0.385], [0.361, 0.335], [0.296, 0.335], [0.286, 0.35], [-0.394, 0.35], [-0.404, 0.335], [-0.464, 0.335]] }, + ] }, + { y0: 0.63, y1: 0.67, polygons: [ + { outer: [[-0.464, -0.32], [0.456, -0.32], [0.456, 0.335], [0.296, 0.335], [0.286, 0.35], [0.251, 0.35], [0.251, 0.43], [-0.364, 0.43], [-0.364, 0.35], [-0.394, 0.35], [-0.404, 0.335], [-0.464, 0.335]], holes: [[[-0.339, 0.35], [-0.344, 0.35], [-0.344, 0.4], [0.231, 0.4], [0.231, 0.35]]] }, + ] }, + { y0: 0.67, y1: 0.788, polygons: [ + { outer: [[-0.464, -0.32], [0.456, -0.32], [0.456, 0.335], [0.296, 0.335], [0.296, 0.385], [0.241, 0.385], [0.241, 0.35], [0.196, 0.35], [0.196, 0.385], [0.136, 0.385], [0.136, 0.35], [0.031, 0.35], [0.031, 0.385], [-0.029, 0.385], [-0.029, 0.35], [-0.074, 0.35], [-0.074, 0.385], [-0.129, 0.385], [-0.129, 0.35], [-0.239, 0.35], [-0.239, 0.385], [-0.294, 0.385], [-0.294, 0.35], [-0.339, 0.35], [-0.339, 0.385], [-0.399, 0.385], [-0.399, 0.34], [-0.404, 0.335], [-0.419, 0.335], [-0.419, 0.34], [-0.464, 0.335]] }, + ] }, + { y0: 0.788, y1: 0.827, polygons: [ + { outer: [[-0.464, -0.325], [0.456, -0.325], [0.456, 0.34], [-0.464, 0.34]] }, + ] }, + { y0: 0.827, y1: 0.847, polygons: [ + { outer: [[-0.449, -0.305], [0.446, -0.305], [0.446, -0.15], [0.451, -0.15], [0.451, -0.135], [0.446, -0.135], [0.446, 0.325], [-0.449, 0.325]], holes: [[[-0.424, -0.285], [-0.429, -0.285], [-0.429, -0.15], [-0.334, -0.15], [-0.334, -0.165], [-0.324, -0.175], [-0.314, -0.175], [-0.314, -0.18], [-0.274, -0.175], [-0.264, -0.165], [-0.264, -0.15], [-0.174, -0.15], [-0.174, -0.285], [-0.294, -0.285], [-0.294, -0.185], [-0.304, -0.185], [-0.304, -0.285]], [[-0.134, -0.285], [-0.139, -0.285], [-0.139, -0.15], [-0.049, -0.15], [-0.044, -0.17], [-0.024, -0.175], [-0.024, -0.18], [0.016, -0.175], [0.026, -0.145], [0.036, -0.145], [0.036, -0.15], [0.121, -0.15], [0.121, -0.285], [-0.004, -0.285], [-0.004, -0.185], [-0.019, -0.185], [-0.019, -0.285]], [[0.161, -0.285], [0.156, -0.285], [0.156, -0.15], [0.246, -0.15], [0.246, -0.145], [0.256, -0.145], [0.261, -0.17], [0.281, -0.175], [0.281, -0.18], [0.321, -0.175], [0.331, -0.145], [0.346, -0.145], [0.346, -0.15], [0.426, -0.15], [0.426, -0.285], [0.301, -0.285], [0.301, -0.185], [0.286, -0.185], [0.286, -0.285]], [[0.031, -0.14], [0.026, -0.14], [0.016, -0.11], [-0.009, -0.105], [-0.004, -0.1], [-0.004, 0.015], [0.121, 0.015], [0.121, -0.135], [0.036, -0.135]], [[0.251, -0.14], [0.246, -0.135], [0.156, -0.135], [0.156, 0.015], [0.286, 0.015], [0.286, -0.1], [0.291, -0.105], [0.266, -0.11], [0.261, -0.125], [0.256, -0.125], [0.256, -0.14]], [[0.336, -0.14], [0.331, -0.14], [0.321, -0.11], [0.296, -0.105], [0.301, -0.1], [0.301, 0.015], [0.426, 0.015], [0.426, -0.135], [0.346, -0.135], [0.346, -0.14]], [[-0.424, -0.135], [-0.429, -0.135], [-0.429, 0.015], [-0.304, 0.015], [-0.304, -0.105], [-0.324, -0.11], [-0.334, -0.12], [-0.334, -0.135]], [[-0.259, -0.135], [-0.264, -0.135], [-0.264, -0.12], [-0.274, -0.11], [-0.294, -0.105], [-0.294, 0.015], [-0.174, 0.015], [-0.174, -0.135]], [[-0.134, -0.135], [-0.139, -0.135], [-0.139, 0.015], [-0.019, 0.015], [-0.019, -0.1], [-0.014, -0.105], [-0.039, -0.11], [-0.049, -0.135]], [[-0.424, 0.03], [-0.429, 0.03], [-0.429, 0.15], [-0.334, 0.15], [-0.329, 0.125], [-0.304, 0.12], [-0.304, 0.03]], [[-0.289, 0.03], [-0.294, 0.03], [-0.294, 0.12], [-0.269, 0.125], [-0.264, 0.15], [-0.174, 0.15], [-0.174, 0.03]], [[-0.134, 0.03], [-0.139, 0.03], [-0.139, 0.15], [-0.049, 0.15], [-0.044, 0.13], [-0.019, 0.12], [-0.019, 0.03]], [[0.001, 0.03], [-0.004, 0.03], [-0.004, 0.115], [-0.009, 0.12], [0.016, 0.125], [0.026, 0.15], [0.121, 0.15], [0.121, 0.03]], [[0.161, 0.03], [0.156, 0.03], [0.156, 0.15], [0.256, 0.15], [0.261, 0.13], [0.286, 0.12], [0.286, 0.03]], [[0.306, 0.03], [0.301, 0.03], [0.301, 0.115], [0.296, 0.12], [0.321, 0.125], [0.331, 0.15], [0.426, 0.15], [0.426, 0.03]], [[-0.339, 0.16], [-0.344, 0.165], [-0.429, 0.165], [-0.429, 0.305], [-0.304, 0.305], [-0.304, 0.2], [-0.294, 0.2], [-0.294, 0.305], [-0.174, 0.305], [-0.174, 0.165], [-0.264, 0.165], [-0.274, 0.19], [-0.309, 0.195], [-0.309, 0.19], [-0.329, 0.185]], [[0.031, 0.16], [0.026, 0.16], [0.021, 0.18], [0.011, 0.19], [0.001, 0.19], [0.001, 0.195], [-0.024, 0.195], [-0.024, 0.19], [-0.044, 0.185], [-0.049, 0.165], [-0.139, 0.165], [-0.139, 0.305], [-0.019, 0.305], [-0.019, 0.2], [-0.004, 0.2], [-0.004, 0.305], [0.121, 0.305], [0.121, 0.165], [0.036, 0.165]], [[0.251, 0.16], [0.246, 0.165], [0.156, 0.165], [0.156, 0.305], [0.286, 0.305], [0.286, 0.2], [0.301, 0.2], [0.301, 0.305], [0.426, 0.305], [0.426, 0.165], [0.346, 0.165], [0.346, 0.16], [0.331, 0.16], [0.331, 0.17], [0.326, 0.17], [0.326, 0.18], [0.316, 0.19], [0.281, 0.195], [0.281, 0.19], [0.261, 0.185], [0.261, 0.17]]] }, + ] }, ], }, 'system/toilet': { tolerance: 0.015, bands: [ - { - y0: 0, - y1: 0.139, - polygons: [ - { - outer: [ - [-0.113, -0.001], - [0.112, -0.001], - [0.112, 0.099], - [0.017, 0.099], - [0.017, 0.224], - [0.037, 0.224], - [0.097, 0.364], - [0.062, 0.454], - [-0.058, 0.454], - [-0.093, 0.374], - [-0.043, 0.239], - [-0.018, 0.224], - [-0.018, 0.099], - [-0.113, 0.099], - ], - }, - ], - }, - { - y0: 0.139, - y1: 0.159, - polygons: [ - { - outer: [ - [-0.118, -0.001], - [0.117, -0.001], - [0.117, 0.099], - [0.017, 0.099], - [0.017, 0.224], - [0.037, 0.219], - [0.107, 0.354], - [0.107, 0.394], - [0.062, 0.454], - [-0.058, 0.454], - [-0.108, 0.369], - [-0.098, 0.314], - [-0.043, 0.229], - [-0.018, 0.224], - [-0.018, 0.099], - [-0.118, 0.099], - ], - }, - ], - }, - { - y0: 0.159, - y1: 0.179, - polygons: [ - { - outer: [ - [-0.123, -0.001], - [0.127, -0.001], - [0.127, 0.099], - [0.017, 0.099], - [0.017, 0.209], - [0.052, 0.194], - [0.067, 0.259], - [0.122, 0.349], - [0.117, 0.419], - [0.062, 0.479], - [-0.068, 0.474], - [-0.123, 0.364], - [-0.113, 0.289], - [-0.053, 0.199], - [-0.018, 0.209], - [-0.018, 0.099], - [-0.123, 0.099], - ], - }, - ], - }, - { - y0: 0.179, - y1: 0.198, - polygons: [ - { - outer: [ - [-0.133, -0.001], - [0.132, -0.001], - [0.132, 0.099], - [0.017, 0.099], - [0.017, 0.184], - [0.072, 0.179], - [0.102, 0.294], - [0.137, 0.349], - [0.127, 0.444], - [0.057, 0.504], - [-0.058, 0.504], - [-0.108, 0.464], - [-0.113, 0.394], - [-0.138, 0.359], - [-0.123, 0.259], - [-0.068, 0.174], - [-0.018, 0.184], - [-0.018, 0.099], - [-0.133, 0.099], - ], - }, - ], - }, - { - y0: 0.198, - y1: 0.218, - polygons: [ - { - outer: [ - [-0.138, -0.001], - [0.142, -0.001], - [0.142, 0.099], - [0.017, 0.099], - [0.017, 0.164], - [0.067, 0.164], - [0.082, 0.149], - [0.097, 0.169], - [0.152, 0.349], - [0.132, 0.474], - [0.062, 0.524], - [-0.063, 0.524], - [-0.128, 0.474], - [-0.148, 0.364], - [-0.133, 0.234], - [-0.083, 0.149], - [-0.063, 0.164], - [-0.018, 0.164], - [-0.018, 0.099], - [-0.138, 0.099], - ], - }, - ], - }, - { - y0: 0.218, - y1: 0.238, - polygons: [ - { - outer: [ - [-0.148, -0.001], - [0.147, -0.001], - [0.147, 0.099], - [0.017, 0.099], - [0.017, 0.139], - [0.082, 0.139], - [0.097, 0.124], - [0.112, 0.144], - [0.162, 0.334], - [0.147, 0.479], - [0.057, 0.544], - [-0.058, 0.544], - [-0.143, 0.484], - [-0.158, 0.299], - [-0.138, 0.189], - [-0.098, 0.124], - [-0.078, 0.139], - [-0.018, 0.139], - [-0.018, 0.099], - [-0.148, 0.099], - ], - }, - ], - }, - { - y0: 0.238, - y1: 0.258, - polygons: [ - { - outer: [ - [-0.153, -0.001], - [0.152, -0.001], - [0.152, 0.099], - [0.112, 0.099], - [0.142, 0.144], - [0.157, 0.209], - [0.167, 0.359], - [0.152, 0.479], - [0.062, 0.549], - [-0.058, 0.549], - [-0.148, 0.484], - [-0.163, 0.384], - [-0.158, 0.234], - [-0.148, 0.159], - [-0.113, 0.099], - [-0.153, 0.099], - ], - holes: [ - [ - [-0.098, 0.099], - [-0.093, 0.114], - [-0.018, 0.114], - [-0.018, 0.099], - ], - [ - [0.022, 0.099], - [0.017, 0.114], - [0.102, 0.104], - ], - ], - }, - ], - }, - { - y0: 0.258, - y1: 0.317, - polygons: [ - { - outer: [ - [-0.173, -0.001], - [0.177, -0.001], - [0.177, 0.099], - [0.162, 0.099], - [0.182, 0.339], - [0.167, 0.474], - [0.157, 0.499], - [0.067, 0.564], - [-0.063, 0.564], - [-0.163, 0.494], - [-0.178, 0.374], - [-0.163, 0.169], - ], - }, - { - outer: [ - [-0.013, 0.589], - [-0.008, 0.589], - [-0.003, 0.589], - [0.002, 0.589], - [0.007, 0.589], - [0.012, 0.589], - [0.012, 0.594], - [0.007, 0.594], - [0.007, 0.599], - [0.002, 0.599], - [-0.003, 0.599], - [-0.008, 0.599], - [-0.008, 0.594], - [-0.013, 0.594], - ], - }, - ], - }, - { - y0: 0.317, - y1: 0.377, - polygons: [ - { - outer: [ - [-0.188, -0.031], - [0.192, -0.031], - [0.202, 0.469], - [0.127, 0.574], - [0.007, 0.599], - [-0.128, 0.574], - [-0.193, 0.484], - ], - }, - ], - }, - { - y0: 0.377, - y1: 0.397, - polygons: [ - { - outer: [ - [-0.163, -0.111], - [0.162, -0.111], - [0.162, -0.031], - [0.192, -0.031], - [0.202, 0.469], - [0.127, 0.574], - [0.007, 0.599], - [-0.128, 0.574], - [-0.198, 0.474], - [-0.193, -0.006], - [-0.188, -0.031], - [-0.163, -0.031], - ], - }, - ], - }, - { - y0: 0.397, - y1: 0.417, - polygons: [ - { - outer: [ - [-0.163, -0.111], - [0.167, -0.111], - [0.167, 0.084], - [-0.163, 0.084], - ], - }, - { - outer: [ - [-0.183, 0.094], - [0.182, 0.094], - [0.187, 0.474], - [0.117, 0.564], - [-0.118, 0.564], - [-0.183, 0.479], - ], - }, - ], - }, - { - y0: 0.417, - y1: 0.437, - polygons: [ - { - outer: [ - [-0.163, -0.111], - [0.167, -0.111], - [0.167, 0.084], - [-0.163, 0.084], - ], - }, - { - outer: [ - [-0.163, 0.094], - [0.162, 0.094], - [0.172, 0.469], - [0.147, 0.504], - [-0.143, 0.504], - [-0.158, 0.489], - ], - }, - ], - }, - { - y0: 0.437, - y1: 0.754, - polygons: [ - { - outer: [ - [-0.188, -0.111], - [0.192, -0.111], - [0.192, 0.084], - [-0.188, 0.084], - ], - }, - ], - }, - { - y0: 0.754, - y1: 0.814, - polygons: [ - { - outer: [ - [-0.208, -0.116], - [0.212, -0.116], - [0.212, 0.094], - [-0.208, 0.094], - ], - }, - ], - }, + { y0: 0, y1: 0.139, polygons: [ + { outer: [[-0.113, -0.001], [0.112, -0.001], [0.112, 0.099], [0.017, 0.099], [0.017, 0.224], [0.037, 0.224], [0.097, 0.364], [0.062, 0.454], [-0.058, 0.454], [-0.093, 0.374], [-0.043, 0.239], [-0.018, 0.224], [-0.018, 0.099], [-0.113, 0.099]] }, + ] }, + { y0: 0.139, y1: 0.159, polygons: [ + { outer: [[-0.118, -0.001], [0.117, -0.001], [0.117, 0.099], [0.017, 0.099], [0.017, 0.224], [0.037, 0.219], [0.107, 0.354], [0.107, 0.394], [0.062, 0.454], [-0.058, 0.454], [-0.108, 0.369], [-0.098, 0.314], [-0.043, 0.229], [-0.018, 0.224], [-0.018, 0.099], [-0.118, 0.099]] }, + ] }, + { y0: 0.159, y1: 0.179, polygons: [ + { outer: [[-0.123, -0.001], [0.127, -0.001], [0.127, 0.099], [0.017, 0.099], [0.017, 0.209], [0.052, 0.194], [0.067, 0.259], [0.122, 0.349], [0.117, 0.419], [0.062, 0.479], [-0.068, 0.474], [-0.123, 0.364], [-0.113, 0.289], [-0.053, 0.199], [-0.018, 0.209], [-0.018, 0.099], [-0.123, 0.099]] }, + ] }, + { y0: 0.179, y1: 0.198, polygons: [ + { outer: [[-0.133, -0.001], [0.132, -0.001], [0.132, 0.099], [0.017, 0.099], [0.017, 0.184], [0.072, 0.179], [0.102, 0.294], [0.137, 0.349], [0.127, 0.444], [0.057, 0.504], [-0.058, 0.504], [-0.108, 0.464], [-0.113, 0.394], [-0.138, 0.359], [-0.123, 0.259], [-0.068, 0.174], [-0.018, 0.184], [-0.018, 0.099], [-0.133, 0.099]] }, + ] }, + { y0: 0.198, y1: 0.218, polygons: [ + { outer: [[-0.138, -0.001], [0.142, -0.001], [0.142, 0.099], [0.017, 0.099], [0.017, 0.164], [0.067, 0.164], [0.082, 0.149], [0.097, 0.169], [0.152, 0.349], [0.132, 0.474], [0.062, 0.524], [-0.063, 0.524], [-0.128, 0.474], [-0.148, 0.364], [-0.133, 0.234], [-0.083, 0.149], [-0.063, 0.164], [-0.018, 0.164], [-0.018, 0.099], [-0.138, 0.099]] }, + ] }, + { y0: 0.218, y1: 0.238, polygons: [ + { outer: [[-0.148, -0.001], [0.147, -0.001], [0.147, 0.099], [0.017, 0.099], [0.017, 0.139], [0.082, 0.139], [0.097, 0.124], [0.112, 0.144], [0.162, 0.334], [0.147, 0.479], [0.057, 0.544], [-0.058, 0.544], [-0.143, 0.484], [-0.158, 0.299], [-0.138, 0.189], [-0.098, 0.124], [-0.078, 0.139], [-0.018, 0.139], [-0.018, 0.099], [-0.148, 0.099]] }, + ] }, + { y0: 0.238, y1: 0.258, polygons: [ + { outer: [[-0.153, -0.001], [0.152, -0.001], [0.152, 0.099], [0.112, 0.099], [0.142, 0.144], [0.157, 0.209], [0.167, 0.359], [0.152, 0.479], [0.062, 0.549], [-0.058, 0.549], [-0.148, 0.484], [-0.163, 0.384], [-0.158, 0.234], [-0.148, 0.159], [-0.113, 0.099], [-0.153, 0.099]], holes: [[[-0.098, 0.099], [-0.093, 0.114], [-0.018, 0.114], [-0.018, 0.099]], [[0.022, 0.099], [0.017, 0.114], [0.102, 0.104]]] }, + ] }, + { y0: 0.258, y1: 0.317, polygons: [ + { outer: [[-0.173, -0.001], [0.177, -0.001], [0.177, 0.099], [0.162, 0.099], [0.182, 0.339], [0.167, 0.474], [0.157, 0.499], [0.067, 0.564], [-0.063, 0.564], [-0.163, 0.494], [-0.178, 0.374], [-0.163, 0.169]] }, + { outer: [[-0.013, 0.589], [-0.008, 0.589], [-0.003, 0.589], [0.002, 0.589], [0.007, 0.589], [0.012, 0.589], [0.012, 0.594], [0.007, 0.594], [0.007, 0.599], [0.002, 0.599], [-0.003, 0.599], [-0.008, 0.599], [-0.008, 0.594], [-0.013, 0.594]] }, + ] }, + { y0: 0.317, y1: 0.377, polygons: [ + { outer: [[-0.188, -0.031], [0.192, -0.031], [0.202, 0.469], [0.127, 0.574], [0.007, 0.599], [-0.128, 0.574], [-0.193, 0.484]] }, + ] }, + { y0: 0.377, y1: 0.397, polygons: [ + { outer: [[-0.163, -0.111], [0.162, -0.111], [0.162, -0.031], [0.192, -0.031], [0.202, 0.469], [0.127, 0.574], [0.007, 0.599], [-0.128, 0.574], [-0.198, 0.474], [-0.193, -0.006], [-0.188, -0.031], [-0.163, -0.031]] }, + ] }, + { y0: 0.397, y1: 0.417, polygons: [ + { outer: [[-0.163, -0.111], [0.167, -0.111], [0.167, 0.084], [-0.163, 0.084]] }, + { outer: [[-0.183, 0.094], [0.182, 0.094], [0.187, 0.474], [0.117, 0.564], [-0.118, 0.564], [-0.183, 0.479]] }, + ] }, + { y0: 0.417, y1: 0.437, polygons: [ + { outer: [[-0.163, -0.111], [0.167, -0.111], [0.167, 0.084], [-0.163, 0.084]] }, + { outer: [[-0.163, 0.094], [0.162, 0.094], [0.172, 0.469], [0.147, 0.504], [-0.143, 0.504], [-0.158, 0.489]] }, + ] }, + { y0: 0.437, y1: 0.754, polygons: [ + { outer: [[-0.188, -0.111], [0.192, -0.111], [0.192, 0.084], [-0.188, 0.084]] }, + ] }, + { y0: 0.754, y1: 0.814, polygons: [ + { outer: [[-0.208, -0.116], [0.212, -0.116], [0.212, 0.094], [-0.208, 0.094]] }, + ] }, ], }, 'system/washing-machine': { tolerance: 0.009, bands: [ - { - y0: 0, - y1: 0.757, - polygons: [ - { - outer: [ - [-0.299, -0.253], - [0.301, -0.253], - [0.301, 0.257], - [0.206, 0.257], - [0.206, 0.272], - [0.181, 0.272], - [0.181, 0.277], - [-0.174, 0.277], - [-0.174, 0.272], - [-0.199, 0.272], - [-0.199, 0.257], - [-0.299, 0.257], - ], - }, - ], - }, - { - y0: 0.757, - y1: 0.857, - polygons: [ - { - outer: [ - [-0.299, -0.253], - [0.301, -0.253], - [0.301, 0.257], - [0.226, 0.257], - [0.226, 0.262], - [0.181, 0.262], - [0.181, 0.257], - [0.166, 0.257], - [0.166, 0.262], - [0.126, 0.262], - [0.126, 0.257], - [0.111, 0.257], - [0.111, 0.262], - [0.071, 0.262], - [0.071, 0.257], - [-0.299, 0.257], - ], - }, - ], - }, + { y0: 0, y1: 0.757, polygons: [ + { outer: [[-0.299, -0.253], [0.301, -0.253], [0.301, 0.257], [0.206, 0.257], [0.206, 0.272], [0.181, 0.272], [0.181, 0.277], [-0.174, 0.277], [-0.174, 0.272], [-0.199, 0.272], [-0.199, 0.257], [-0.299, 0.257]] }, + ] }, + { y0: 0.757, y1: 0.857, polygons: [ + { outer: [[-0.299, -0.253], [0.301, -0.253], [0.301, 0.257], [0.226, 0.257], [0.226, 0.262], [0.181, 0.262], [0.181, 0.257], [0.166, 0.257], [0.166, 0.262], [0.126, 0.262], [0.126, 0.257], [0.111, 0.257], [0.111, 0.262], [0.071, 0.262], [0.071, 0.257], [-0.299, 0.257]] }, + ] }, ], }, } From e490b8a4c4ff675978e81ba88c4b6e8b564faa74 Mon Sep 17 00:00:00 2001 From: Adam NAILI Date: Tue, 3 Nov 2026 20:35:42 +0100 Subject: [PATCH 40/40] move-duplicate.test.ts imports the MCP SDK v2 packages The test imported @modelcontextprotocol/sdk (client, inMemory, server/mcp.js), which the editor's packages/mcp no longer declares since the move to @modelcontextprotocol/server and /client. It ran only where a checkout above the editor still carried the old package, and failed with "Cannot find module" in the editor's own install. It now imports Client from @modelcontextprotocol/client and InMemoryTransport and McpServer from @modelcontextprotocol/server, as shared-tools.test.ts does. No other file this branch touches imports the old package. Co-Authored-By: Claude Sonnet 5.5 --- packages/mcp/src/tools/move-duplicate.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/mcp/src/tools/move-duplicate.test.ts b/packages/mcp/src/tools/move-duplicate.test.ts index d87e261ddb..61f9e68a59 100644 --- a/packages/mcp/src/tools/move-duplicate.test.ts +++ b/packages/mcp/src/tools/move-duplicate.test.ts @@ -1,7 +1,6 @@ import { describe, expect, test } from 'bun:test' -import { Client } from '@modelcontextprotocol/sdk/client/index.js' -import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { Client } from '@modelcontextprotocol/client' +import { InMemoryTransport, McpServer } from '@modelcontextprotocol/server' import { duplicateNodeTool, moveNodeTool } from '@pascal-app/core/agent-tools' import { DoorNode, LevelNode, WallNode, WindowNode } from '@pascal-app/core/schema' import { SceneBridge } from '../bridge/scene-bridge'