@kruschdev/pascal-plugin-furnishings 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,753 @@
1
+ /**
2
+ * Spatial Anatomy Adapter (`src/furnishings/geometry.ts`).
3
+ *
4
+ * Consumes `@kruschdev/pascal-mep-kernel/anatomy` (`compileBuildingAnatomy`) to extract:
5
+ * - Room polygons, centroids, areas, bounding boxes, and multilingual `RoomStagingKind` classification
6
+ * - Interior & exterior walls, solid wall segments (avoiding door/window openings), and door swing clearance zones
7
+ * - Electrical receptacles (`electrical:device`) for plug-in AV/workstation outlet proximity coordination
8
+ * - Building outer footprint bounds and exterior yard perimeter / foundation planting zones
9
+ *
10
+ * Pure framework-free TypeScript: zero `three`, `react`, `@pascal-app/*`, or `next` imports.
11
+ */
12
+
13
+ import { createOrientedPrismY } from '@kruschdev/pascal-mep-kernel'
14
+ import {
15
+ type CanonicalWall,
16
+ type TaggedOpeningPrism,
17
+ belongsToLevel,
18
+ compileBuildingAnatomy,
19
+ distancePointToSegment2D,
20
+ isPointEnclosedByWalls,
21
+ pointInPolygon2D,
22
+ polygonAreaAndCentroid,
23
+ polygonBounds2D,
24
+ } from '@kruschdev/pascal-mep-kernel/anatomy'
25
+ import {
26
+ type BlueprintRoomFurnishingPlan,
27
+ type BlueprintWallSide,
28
+ ROOM_STAGING_KINDS,
29
+ type RoomStagingKind,
30
+ SQM_TO_SQFT,
31
+ type OrientedPrismY,
32
+ type SceneNodeLike,
33
+ type Vec2,
34
+ type XzBounds2D,
35
+ round2,
36
+ round3,
37
+ } from './types'
38
+
39
+ export type FurnishingRoomAnalysis = {
40
+ readonly id: string
41
+ readonly levelId: string | null
42
+ readonly name: string
43
+ readonly kind: RoomStagingKind
44
+ readonly polygon: readonly Vec2[]
45
+ readonly centroid: Vec2
46
+ readonly bounds: XzBounds2D
47
+ readonly widthM: number
48
+ readonly depthM: number
49
+ readonly areaSqm: number
50
+ readonly areaSqft: number
51
+ readonly isOutdoor: boolean
52
+ readonly furnishingPlan?: BlueprintRoomFurnishingPlan
53
+ }
54
+
55
+ export type FurnishingWallAnalysis = {
56
+ readonly id: string
57
+ readonly levelId: string | null
58
+ readonly start: Vec2
59
+ readonly end: Vec2
60
+ readonly lengthM: number
61
+ readonly heightM: number
62
+ readonly thicknessM: number
63
+ readonly ux: number
64
+ readonly uz: number
65
+ readonly nx: number
66
+ readonly nz: number
67
+ readonly isExterior: boolean
68
+ readonly exteriorNormalSign: -1 | 0 | 1
69
+ readonly openingIntervals: readonly {
70
+ readonly kind: 'door' | 'window'
71
+ readonly startU: number
72
+ readonly endU: number
73
+ }[]
74
+ }
75
+
76
+ export type ElectricalOutletPoint = {
77
+ readonly id: string
78
+ readonly levelId: string | null
79
+ readonly x: number
80
+ readonly y: number
81
+ readonly z: number
82
+ }
83
+
84
+ export type LevelDoorPrism = TaggedOpeningPrism & {
85
+ readonly levelId: string
86
+ }
87
+
88
+ export type BuildingFurnishingsAnatomy = {
89
+ readonly levelIds: readonly string[]
90
+ readonly primaryLevelId: string | null
91
+ readonly rooms: readonly FurnishingRoomAnalysis[]
92
+ readonly walls: readonly FurnishingWallAnalysis[]
93
+ readonly doorPrisms: readonly LevelDoorPrism[]
94
+ readonly windowPrisms: readonly LevelDoorPrism[]
95
+ readonly outlets: readonly ElectricalOutletPoint[]
96
+ readonly footprintBounds: XzBounds2D | null
97
+ }
98
+
99
+ const VALID_ROOM_KINDS = new Set<string>(ROOM_STAGING_KINDS)
100
+
101
+ function parseRoomKindOverride(raw: unknown): RoomStagingKind | undefined {
102
+ if (typeof raw !== 'string') return undefined
103
+ const k = raw.trim().toLowerCase()
104
+ return VALID_ROOM_KINDS.has(k) ? (k as RoomStagingKind) : undefined
105
+ }
106
+
107
+ function extractFurnishingPlan(node: SceneNodeLike | undefined): BlueprintRoomFurnishingPlan | undefined {
108
+ if (!node) return undefined
109
+ const meta = node.metadata as Record<string, unknown> | undefined
110
+ if (!meta || typeof meta !== 'object') return undefined
111
+ const rawPlan = meta.furnishingPlan as Record<string, unknown> | undefined
112
+ const metaRoomKind = parseRoomKindOverride(meta.roomKind ?? meta.stagingKind)
113
+ if (!rawPlan || typeof rawPlan !== 'object') {
114
+ return metaRoomKind ? { roomKind: metaRoomKind } : undefined
115
+ }
116
+ const roomKind = parseRoomKindOverride(rawPlan.roomKind) ?? metaRoomKind
117
+ const mode =
118
+ rawPlan.mode === 'blueprint-only' || rawPlan.mode === 'blueprint-plus-auto' || rawPlan.mode === 'skip'
119
+ ? rawPlan.mode
120
+ : undefined
121
+ const preferredAnchorWall =
122
+ rawPlan.preferredAnchorWall === 'north' ||
123
+ rawPlan.preferredAnchorWall === 'south' ||
124
+ rawPlan.preferredAnchorWall === 'east' ||
125
+ rawPlan.preferredAnchorWall === 'west' ||
126
+ rawPlan.preferredAnchorWall === 'center' ||
127
+ rawPlan.preferredAnchorWall === 'auto'
128
+ ? rawPlan.preferredAnchorWall
129
+ : undefined
130
+ const bedSize =
131
+ rawPlan.bedSize === 'king' ||
132
+ rawPlan.bedSize === 'queen' ||
133
+ rawPlan.bedSize === 'twin' ||
134
+ rawPlan.bedSize === 'bunk'
135
+ ? rawPlan.bedSize
136
+ : undefined
137
+ const items = Array.isArray(rawPlan.items) ? (rawPlan.items as BlueprintRoomFurnishingPlan['items']) : undefined
138
+ return {
139
+ ...(roomKind ? { roomKind } : {}),
140
+ ...(mode ? { mode } : {}),
141
+ ...(preferredAnchorWall ? { preferredAnchorWall } : {}),
142
+ ...(bedSize ? { bedSize } : {}),
143
+ ...(items ? { items } : {}),
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Multilingual room name classifier for interior staging & exterior patios.
149
+ *
150
+ * Specific functional nouns (`bathroom`, `closet`/`W.I.C.`/`pantry`, `laundry`, `kitchen`,
151
+ * `patio`/`balcony`, `office`, `dining`, `living`, `entryway`, `hallway`, `garage`) always
152
+ * take precedence over generic prefixes (`master`, `primary`, `suite`, `guest`) so rooms
153
+ * like "Master Bathroom" or "Master W.I.C." are never misclassified as bedrooms.
154
+ */
155
+ export function classifyRoomStagingKind(name: string | undefined, category?: string): RoomStagingKind {
156
+ const text = `${name ?? ''} ${category ?? ''}`.toLowerCase()
157
+ if (/(\bbath\b|bathroom|salle\s*de\s*bain|\bw\.?c\.?\b|toilet|powder|\bpdr\.?\b|shower|\bbad\b)/.test(text)) {
158
+ return 'bathroom'
159
+ }
160
+ // Distinguish a dedicated "Kitchen Pantry" (closet) from a compound "Kitchen & Pantry" (kitchen)
161
+ if (/\bkitchen\s+pantry\b/.test(text)) return 'closet'
162
+ if (/(kitchen|kitchenette|cuisine|k[üu]che|cocina)/.test(text)) return 'kitchen'
163
+ if (/(laundry|washroom|\butility\b)/.test(text)) return 'laundry'
164
+ if (/(\bw\.?\s*i\.?\s*c\.?\b|walk[-\s]*in|closet|wardrobe|dressing\s*room|linen|pantry|storage)/.test(text)) {
165
+ return 'closet'
166
+ }
167
+ if (/(theater|cinema|media|home\s*theater|screening|game\s*room|gaming)/.test(text)) return 'media'
168
+ if (/(living|salon|sejour|séjour|family|lounge|great\s*room|\bden\b|sitting|wohnzimmer|studio)/.test(text)) {
169
+ return 'living'
170
+ }
171
+ if (/(dining|salle\s*[àa]\s*manger|breakfast|nook|esszimmer|comedor)/.test(text)) return 'dining'
172
+ if (/(office|study|bureau|workspace|library|desk|arbeitszimmer|estudio)/.test(text)) return 'office'
173
+ if (/(patio|deck|terrace|terrasse|balcony|balcon|porch|veranda|lanai|pool\s*deck|loggia)/.test(text)) return 'patio'
174
+ if (/(yard|garden|jardin|lawn|courtyard|exterior|site|landscape)/.test(text)) return 'yard'
175
+ if (/(entry|foyer|mudroom|vestibule|entr[ée]e|lobby)/.test(text)) return 'entryway'
176
+ if (/(hall|corridor|couloir|passage|landing|stair)/.test(text)) return 'hallway'
177
+ if (/(garage|carport|workshop|mechanical|boiler)/.test(text)) return 'garage'
178
+ if (/(bed|chambre|master|primary|suite|guest\s*room|nursery|schlafzimmer|dormitorio)/.test(text)) return 'bedroom'
179
+ return 'general'
180
+ }
181
+
182
+ const BATH_FIXTURE_RE = /(water-closet|toilet|lavatory|vanity|shower|bathtub|tub-shower|bidet|urinal)/i
183
+ const KITCHEN_FIXTURE_RE = /(kitchen-sink|dishwasher|garbage-disposal|range|cooktop)/i
184
+ const LAUNDRY_FIXTURE_RE = /(clothes-washer|\bwasher\b|dryer|laundry-sink|utility-sink)/i
185
+
186
+ function inferRoomKindFromFixtures(
187
+ room: { levelId: string | null; polygon: readonly Vec2[] },
188
+ nodes: Readonly<Record<string, SceneNodeLike>>,
189
+ ): RoomStagingKind | null {
190
+ let bathHits = 0
191
+ let laundryHits = 0
192
+ let kitchenHits = 0
193
+ for (const n of Object.values(nodes)) {
194
+ if (n.visible === false) continue
195
+ if (n.type !== 'plumbing:fixture') continue
196
+ if (room.levelId && !belongsToLevel(nodes, n, room.levelId)) continue
197
+ const pos = Array.isArray(n.position) ? n.position : null
198
+ if (!pos || typeof pos[0] !== 'number' || typeof pos[2] !== 'number') continue
199
+ if (!pointInPolygon2D(pos[0], pos[2], room.polygon)) continue
200
+ const fk = String(n.fixtureKind ?? n.kind ?? n.name ?? '')
201
+ if (BATH_FIXTURE_RE.test(fk)) bathHits++
202
+ else if (KITCHEN_FIXTURE_RE.test(fk)) kitchenHits++
203
+ else if (LAUNDRY_FIXTURE_RE.test(fk)) laundryHits++
204
+ }
205
+ if (bathHits > 0) return 'bathroom'
206
+ if (kitchenHits > 0) return 'kitchen'
207
+ if (laundryHits > 0) return 'laundry'
208
+ return null
209
+ }
210
+
211
+ export function extractBuildingFurnishingsAnatomy(
212
+ nodes: Readonly<Record<string, SceneNodeLike>>,
213
+ targetLevelId?: string | null,
214
+ ): BuildingFurnishingsAnatomy {
215
+ const anatomy = compileBuildingAnatomy(nodes)
216
+ const activeLevelIds = targetLevelId
217
+ ? anatomy.levelIds.filter((id) => id === targetLevelId)
218
+ : anatomy.levelIds
219
+ const primaryLevelId = activeLevelIds[0] ?? null
220
+
221
+ const rooms: FurnishingRoomAnalysis[] = []
222
+ const walls: FurnishingWallAnalysis[] = []
223
+ const doorPrisms: LevelDoorPrism[] = []
224
+ const windowPrisms: LevelDoorPrism[] = []
225
+ const outlets: ElectricalOutletPoint[] = []
226
+
227
+ let minX = Number.POSITIVE_INFINITY
228
+ let maxX = Number.NEGATIVE_INFINITY
229
+ let minZ = Number.POSITIVE_INFINITY
230
+ let maxZ = Number.NEGATIVE_INFINITY
231
+
232
+ const includeBounds = (b: XzBounds2D | null | undefined) => {
233
+ if (!b) return
234
+ if (b.minX < minX) minX = b.minX
235
+ if (b.maxX > maxX) maxX = b.maxX
236
+ if (b.minZ < minZ) minZ = b.minZ
237
+ if (b.maxZ > maxZ) maxZ = b.maxZ
238
+ }
239
+
240
+ for (const levelId of activeLevelIds) {
241
+ const levelWalls = anatomy.getWalls(levelId)
242
+ const fp = anatomy.getFootprint(levelId)
243
+ includeBounds(fp.bounds)
244
+
245
+ for (const prism of anatomy.getOpeningPrisms(levelId)) {
246
+ if (prism.kind === 'door') {
247
+ doorPrisms.push({ ...prism, levelId })
248
+ } else if (prism.kind === 'window') {
249
+ windowPrisms.push({ ...prism, levelId })
250
+ }
251
+ }
252
+
253
+ for (const w of levelWalls) {
254
+ const dx = w.end[0] - w.start[0]
255
+ const dz = w.end[1] - w.start[1]
256
+ const len = Math.hypot(dx, dz)
257
+ if (len < 0.15) continue
258
+ const ux = dx / len
259
+ const uz = dz / len
260
+ const nx = -uz
261
+ const nz = ux
262
+ const midX = (w.start[0] + w.end[0]) / 2
263
+ const midZ = (w.start[1] + w.end[1]) / 2
264
+ const probeDist = Math.max(0.45, w.thicknessM + 0.35)
265
+ const posInside = isPointEnclosedByWalls(midX + nx * probeDist, midZ + nz * probeDist, levelWalls)
266
+ const negInside = isPointEnclosedByWalls(midX - nx * probeDist, midZ - nz * probeDist, levelWalls)
267
+ const isExterior = posInside !== negInside || (!posInside && !negInside)
268
+ const exteriorNormalSign: -1 | 0 | 1 = !posInside && negInside ? 1 : posInside && !negInside ? -1 : 0
269
+
270
+ walls.push({
271
+ id: w.id,
272
+ levelId,
273
+ start: w.start,
274
+ end: w.end,
275
+ lengthM: round3(len),
276
+ heightM: round3(w.heightM),
277
+ thicknessM: round3(w.thicknessM),
278
+ ux,
279
+ uz,
280
+ nx,
281
+ nz,
282
+ isExterior,
283
+ exteriorNormalSign,
284
+ openingIntervals: w.openings.map((o) => ({
285
+ kind: o.kind,
286
+ startU: round3(o.startU),
287
+ endU: round3(o.endU),
288
+ })),
289
+ })
290
+ }
291
+
292
+ // Collect explicit zone/room polygons first; fall back to base room polygons from kernel
293
+ const seenRoomIds = new Set<string>()
294
+ const hasExplicitZones = Object.values(nodes).some(
295
+ (n) => belongsToLevel(nodes, n, levelId) && n.visible !== false && (n.type === 'zone' || n.type === 'room'),
296
+ )
297
+ for (const node of Object.values(nodes)) {
298
+ if (!belongsToLevel(nodes, node, levelId)) continue
299
+ if (node.visible === false) continue
300
+ if (node.type === 'zone' || node.type === 'room' || node.type === 'slab') {
301
+ const poly = node.polygon
302
+ if (!Array.isArray(poly) || poly.length < 3) continue
303
+ if (node.type === 'slab' && hasExplicitZones) continue
304
+ const { areaSqM, centroid } = polygonAreaAndCentroid(poly)
305
+ if (areaSqM < 1.0) continue
306
+ const bounds = polygonBounds2D(poly)
307
+ if (!bounds) continue
308
+ const name = typeof node.name === 'string' && node.name.trim() ? node.name.trim() : `Room ${rooms.length + 1}`
309
+ const furnishingPlan = extractFurnishingPlan(node)
310
+ const nameKind = classifyRoomStagingKind(name, typeof node.category === 'string' ? node.category : undefined)
311
+ const fixtureKind = inferRoomKindFromFixtures({ levelId, polygon: poly }, nodes)
312
+ let kind: RoomStagingKind = furnishingPlan?.roomKind ?? nameKind
313
+ // Evidence-based safety net: physical plumbing bath/laundry fixtures override misnamed/ambiguous rooms
314
+ if (!furnishingPlan?.roomKind && fixtureKind) {
315
+ if (fixtureKind === 'bathroom' || fixtureKind === 'laundry') {
316
+ kind = fixtureKind
317
+ } else if (fixtureKind === 'kitchen' && (kind === 'general' || kind === 'bedroom')) {
318
+ kind = 'kitchen'
319
+ }
320
+ }
321
+ const isOutdoor = kind === 'patio' || kind === 'yard'
322
+ seenRoomIds.add(node.id)
323
+ rooms.push({
324
+ id: node.id,
325
+ levelId,
326
+ name,
327
+ kind,
328
+ polygon: poly,
329
+ centroid: [round3(centroid[0]), round3(centroid[1])],
330
+ bounds,
331
+ widthM: round3(bounds.maxX - bounds.minX),
332
+ depthM: round3(bounds.maxZ - bounds.minZ),
333
+ areaSqm: round2(areaSqM),
334
+ areaSqft: round2(areaSqM * SQM_TO_SQFT),
335
+ isOutdoor,
336
+ ...(furnishingPlan ? { furnishingPlan } : {}),
337
+ })
338
+ }
339
+ }
340
+
341
+ for (const baseRoom of fp.roomPolygons) {
342
+ if (seenRoomIds.has(baseRoom.id)) continue
343
+ const bounds = polygonBounds2D(baseRoom.polygon)
344
+ if (!bounds) continue
345
+ const { areaSqM, centroid } = polygonAreaAndCentroid(baseRoom.polygon)
346
+ if (areaSqM < 1.0) continue
347
+ const alreadyCovered = rooms.some(
348
+ (r) => r.levelId === levelId && pointInPolygon2D(centroid[0], centroid[1], r.polygon),
349
+ )
350
+ if (alreadyCovered) continue
351
+ const srcNode = nodes[baseRoom.id]
352
+ const furnishingPlan = extractFurnishingPlan(srcNode)
353
+ const name =
354
+ (typeof srcNode?.name === 'string' && srcNode.name.trim()) ||
355
+ `Level Space ${rooms.length + 1}`
356
+ const nameKind = classifyRoomStagingKind(
357
+ name,
358
+ typeof srcNode?.category === 'string' ? srcNode.category : undefined,
359
+ )
360
+ const fixtureKind = inferRoomKindFromFixtures({ levelId, polygon: baseRoom.polygon }, nodes)
361
+ let kind: RoomStagingKind = furnishingPlan?.roomKind ?? nameKind
362
+ if (!furnishingPlan?.roomKind && fixtureKind) {
363
+ if (fixtureKind === 'bathroom' || fixtureKind === 'laundry') {
364
+ kind = fixtureKind
365
+ } else if (fixtureKind === 'kitchen' && (kind === 'general' || kind === 'bedroom')) {
366
+ kind = 'kitchen'
367
+ }
368
+ } else if (!furnishingPlan?.roomKind && kind === 'general' && areaSqM >= 14) {
369
+ kind = 'living'
370
+ }
371
+ seenRoomIds.add(baseRoom.id)
372
+ rooms.push({
373
+ id: baseRoom.id,
374
+ levelId,
375
+ name,
376
+ kind,
377
+ polygon: baseRoom.polygon,
378
+ centroid: [round3(centroid[0]), round3(centroid[1])],
379
+ bounds,
380
+ widthM: round3(bounds.maxX - bounds.minX),
381
+ depthM: round3(bounds.maxZ - bounds.minZ),
382
+ areaSqm: round2(areaSqM),
383
+ areaSqft: round2(areaSqM * SQM_TO_SQFT),
384
+ isOutdoor: kind === 'patio' || kind === 'yard',
385
+ ...(furnishingPlan ? { furnishingPlan } : {}),
386
+ })
387
+ }
388
+
389
+ // Extract electrical receptacles for outlet proximity checks
390
+ for (const node of Object.values(nodes)) {
391
+ if (!belongsToLevel(nodes, node, levelId)) continue
392
+ if (node.visible === false) continue
393
+ if (node.type === 'electrical:device') {
394
+ const devKind = String(node.deviceKind ?? node.kind ?? '').toLowerCase()
395
+ if (devKind.includes('receptacle') || devKind.includes('outlet') || devKind.includes('gfci') || devKind.includes('usb')) {
396
+ const pos = Array.isArray(node.position) ? node.position : null
397
+ if (pos && typeof pos[0] === 'number' && typeof pos[2] === 'number') {
398
+ outlets.push({
399
+ id: node.id,
400
+ levelId,
401
+ x: round3(pos[0]),
402
+ y: round3(typeof pos[1] === 'number' && Number.isFinite(pos[1]) ? pos[1] : 0),
403
+ z: round3(pos[2]),
404
+ })
405
+ }
406
+ }
407
+ }
408
+ }
409
+ }
410
+
411
+ const footprintBounds: XzBounds2D | null =
412
+ Number.isFinite(minX) && Number.isFinite(maxX) && Number.isFinite(minZ) && Number.isFinite(maxZ)
413
+ ? { minX: round3(minX), maxX: round3(maxX), minZ: round3(minZ), maxZ: round3(maxZ) }
414
+ : rooms.length > 0
415
+ ? {
416
+ minX: round3(Math.min(...rooms.map((r) => r.bounds.minX))),
417
+ maxX: round3(Math.max(...rooms.map((r) => r.bounds.maxX))),
418
+ minZ: round3(Math.min(...rooms.map((r) => r.bounds.minZ))),
419
+ maxZ: round3(Math.max(...rooms.map((r) => r.bounds.maxZ))),
420
+ }
421
+ : null
422
+
423
+ return {
424
+ levelIds: activeLevelIds,
425
+ primaryLevelId,
426
+ rooms,
427
+ walls,
428
+ doorPrisms,
429
+ windowPrisms,
430
+ outlets,
431
+ footprintBounds,
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Determine whether a 2D XZ point sits inside any enclosed interior room polygon.
437
+ */
438
+ export function findContainingRoom(
439
+ x: number,
440
+ z: number,
441
+ rooms: readonly FurnishingRoomAnalysis[],
442
+ ): FurnishingRoomAnalysis | null {
443
+ for (const room of rooms) {
444
+ if (pointInPolygon2D(x, z, room.polygon)) {
445
+ return room
446
+ }
447
+ }
448
+ return null
449
+ }
450
+
451
+ /**
452
+ * Minimum horizontal distance from an XZ point to any exterior wall segment (foundation check).
453
+ */
454
+ export function minDistanceToExteriorWallM(
455
+ x: number,
456
+ z: number,
457
+ walls: readonly FurnishingWallAnalysis[],
458
+ ): number {
459
+ let minD = Number.POSITIVE_INFINITY
460
+ for (const w of walls) {
461
+ if (!w.isExterior) continue
462
+ const d = distancePointToSegment2D(x, z, w.start[0], w.start[1], w.end[0], w.end[1])
463
+ if (d < minD) minD = d
464
+ }
465
+ return minD
466
+ }
467
+
468
+ export type SolidWallAnchor = {
469
+ readonly wall: FurnishingWallAnalysis
470
+ readonly midX: number
471
+ readonly midZ: number
472
+ readonly inwardNx: number
473
+ readonly inwardNz: number
474
+ readonly yawRad: number
475
+ readonly spanLenM: number
476
+ readonly score: number
477
+ }
478
+
479
+ function cardinalAlignmentBonus(
480
+ inwardNx: number,
481
+ inwardNz: number,
482
+ preferredSide?: BlueprintWallSide,
483
+ ): number {
484
+ if (!preferredSide || preferredSide === 'auto' || preferredSide === 'center') return 0
485
+ // Pascal world axes: -Z = north (inward normal +Z), +Z = south (inward -Z), -X = west (inward +X), +X = east (inward -X)
486
+ if (preferredSide === 'north' && inwardNz > 0.7) return 12
487
+ if (preferredSide === 'south' && inwardNz < -0.7) return 12
488
+ if (preferredSide === 'west' && inwardNx > 0.7) return 12
489
+ if (preferredSide === 'east' && inwardNx < -0.7) return 12
490
+ return 0
491
+ }
492
+
493
+ /**
494
+ * Return all valid solid (opening-free) wall segments bordering a room, ranked best-first.
495
+ * Supports optional cardinal preference (`north`/`south`/`east`/`west`) from blueprint plans
496
+ * and enables multi-wall fallback when the top wall is obstructed by a door swing or fixture.
497
+ */
498
+ export function findRankedSolidWallsForRoom(
499
+ room: FurnishingRoomAnalysis,
500
+ walls: readonly FurnishingWallAnalysis[],
501
+ preferredSide?: BlueprintWallSide,
502
+ options?: { readonly allowWindows?: boolean },
503
+ ): SolidWallAnchor[] {
504
+ const allowWindows = options?.allowWindows ?? false
505
+ const candidates: SolidWallAnchor[] = []
506
+
507
+ for (const w of walls) {
508
+ if (room.levelId && w.levelId && w.levelId !== room.levelId) continue
509
+ const distToCenter = distancePointToSegment2D(
510
+ room.centroid[0],
511
+ room.centroid[1],
512
+ w.start[0],
513
+ w.start[1],
514
+ w.end[0],
515
+ w.end[1],
516
+ )
517
+ const maxReach = Math.hypot(room.widthM, room.depthM) * 0.65
518
+ if (distToCenter > maxReach) continue
519
+
520
+ // Clip wall span to this room's projected extent so continuous multi-room walls
521
+ // evaluate each room's own bordering span instead of landing on an interior partition.
522
+ let minRoomU = Number.POSITIVE_INFINITY
523
+ let maxRoomU = Number.NEGATIVE_INFINITY
524
+ for (const [vx, vz] of room.polygon) {
525
+ const proj = (vx - w.start[0]) * w.ux + (vz - w.start[1]) * w.uz
526
+ if (proj < minRoomU) minRoomU = proj
527
+ if (proj > maxRoomU) maxRoomU = proj
528
+ }
529
+ const spanStartU = Math.max(0, minRoomU)
530
+ const spanEndU = Math.min(w.lengthM, maxRoomU)
531
+ if (spanEndU - spanStartU < 1.1) continue
532
+
533
+ // Compute longest uninterrupted span on this wall within the room's extent.
534
+ // Floor-standing furniture (beds, desks, dressers) may back against windowed walls when
535
+ // solid walls are obstructed by doors (`allowWindows: true`), while still preferring solid walls.
536
+ const blockingIntervals = [...w.openingIntervals]
537
+ .filter((iv) => !allowWindows || iv.kind === 'door')
538
+ .sort((a, b) => a.startU - b.startU)
539
+ let prevU = spanStartU
540
+ let bestSpanLen = 0
541
+ let bestSpanMidU = (spanStartU + spanEndU) / 2
542
+ for (const iv of blockingIntervals) {
543
+ if (iv.endU <= spanStartU) continue
544
+ if (iv.startU >= spanEndU) break
545
+ const clampedStart = Math.max(spanStartU, iv.startU)
546
+ const clampedEnd = Math.min(spanEndU, iv.endU)
547
+ const span = clampedStart - prevU
548
+ if (span > bestSpanLen) {
549
+ bestSpanLen = span
550
+ bestSpanMidU = prevU + span / 2
551
+ }
552
+ prevU = Math.max(prevU, clampedEnd)
553
+ }
554
+ if (spanEndU - prevU > bestSpanLen) {
555
+ bestSpanLen = spanEndU - prevU
556
+ bestSpanMidU = prevU + (spanEndU - prevU) / 2
557
+ }
558
+ if (bestSpanLen < 1.1) continue
559
+
560
+ // Orient inward normal toward room centroid from the clipped span midpoint
561
+ const spanMidX = w.start[0] + w.ux * bestSpanMidU
562
+ const spanMidZ = w.start[1] + w.uz * bestSpanMidU
563
+ const toCenterX = room.centroid[0] - spanMidX
564
+ const toCenterZ = room.centroid[1] - spanMidZ
565
+ const dot = toCenterX * w.nx + toCenterZ * w.nz
566
+ const inwardNx = dot >= 0 ? w.nx : -w.nx
567
+ const inwardNz = dot >= 0 ? w.nz : -w.nz
568
+
569
+ // Verify a probe point 0.4m inside the wall lands inside this room
570
+ const px = spanMidX + inwardNx * 0.4
571
+ const pz = spanMidZ + inwardNz * 0.4
572
+ if (!pointInPolygon2D(px, pz, room.polygon)) continue
573
+
574
+ // Prefer longer spans; reward genuinely opening-free walls and blueprint preferred cardinal walls
575
+ const hasAnyOpeningInSpan = w.openingIntervals.some((iv) => iv.endU > spanStartU && iv.startU < spanEndU)
576
+ const hasDoorInSpan = w.openingIntervals.some(
577
+ (iv) => iv.kind === 'door' && iv.endU > spanStartU && iv.startU < spanEndU,
578
+ )
579
+ const score =
580
+ bestSpanLen +
581
+ (hasAnyOpeningInSpan ? 0 : 0.8) +
582
+ (hasDoorInSpan ? -0.4 : 0.4) +
583
+ cardinalAlignmentBonus(inwardNx, inwardNz, preferredSide)
584
+ const yawRad = Math.atan2(inwardNx, inwardNz)
585
+ candidates.push({
586
+ wall: w,
587
+ midX: round3(spanMidX),
588
+ midZ: round3(spanMidZ),
589
+ inwardNx,
590
+ inwardNz,
591
+ yawRad: round3(yawRad),
592
+ spanLenM: round3(bestSpanLen),
593
+ score: round3(score),
594
+ })
595
+ }
596
+
597
+ candidates.sort((a, b) => b.score - a.score)
598
+ return candidates
599
+ }
600
+
601
+ /**
602
+ * Find the longest solid (opening-free) wall segment bordering a room for anchoring TVs, beds, or sofas.
603
+ */
604
+ export function findBestSolidWallForRoom(
605
+ room: FurnishingRoomAnalysis,
606
+ walls: readonly FurnishingWallAnalysis[],
607
+ preferredSide?: BlueprintWallSide,
608
+ ): { wall: FurnishingWallAnalysis; midX: number; midZ: number; inwardNx: number; inwardNz: number; yawRad: number } | null {
609
+ const best = findRankedSolidWallsForRoom(room, walls, preferredSide)[0]
610
+ if (!best) return null
611
+ return {
612
+ wall: best.wall,
613
+ midX: best.midX,
614
+ midZ: best.midZ,
615
+ inwardNx: best.inwardNx,
616
+ inwardNz: best.inwardNz,
617
+ yawRad: best.yawRad,
618
+ }
619
+ }
620
+
621
+ /**
622
+ * Construct an `OrientedPrismY` aligned with Three.js right-handed Y-up rotation (`rotation.y = yawRad`).
623
+ * Three.js maps local `(lx, lz)` to `(lx*cos + lz*sin, -lx*sin + lz*cos)`, whereas
624
+ * `@kruschdev/pascal-mep-kernel`'s `createOrientedPrismY` uses `(lx*cos - lz*sin, lx*sin + lz*cos)`.
625
+ * Passing `sin: -Math.sin(yawRad)` aligns collision OBBs 1:1 with 3D meshes and 2D floorplans.
626
+ */
627
+ export function createFurnishingPrismY(params: {
628
+ readonly centerX: number
629
+ readonly centerZ: number
630
+ readonly yawRad: number
631
+ readonly widthM: number
632
+ readonly depthM: number
633
+ readonly yMin: number
634
+ readonly yMax: number
635
+ }): OrientedPrismY {
636
+ return createOrientedPrismY({
637
+ centerX: params.centerX,
638
+ centerZ: params.centerZ,
639
+ cos: Math.cos(params.yawRad),
640
+ sin: -Math.sin(params.yawRad),
641
+ lxMin: -params.widthM / 2,
642
+ lxMax: params.widthM / 2,
643
+ lzMin: -params.depthM / 2,
644
+ lzMax: params.depthM / 2,
645
+ yMin: params.yMin,
646
+ yMax: params.yMax,
647
+ })
648
+ }
649
+
650
+ /**
651
+ * Expand a wall-aligned door or window `OrientedPrismY` along its exact wall tangent (`alongPadM`)
652
+ * and wall normal (`perpPadM`) axes, preserving diagonal wall orientation without AABB axis-swap bugs.
653
+ */
654
+ export function expandOpeningPrism(
655
+ p: OrientedPrismY,
656
+ alongPadM: number,
657
+ perpPadM: number,
658
+ ): OrientedPrismY {
659
+ const along = Math.max(0, Number.isFinite(alongPadM) ? alongPadM : 0)
660
+ const perp = Math.max(0, Number.isFinite(perpPadM) ? perpPadM : 0)
661
+ return createOrientedPrismY({
662
+ centerX: p.centerX,
663
+ centerZ: p.centerZ,
664
+ cos: p.cos,
665
+ sin: p.sin,
666
+ lxMin: p.lxMin - along,
667
+ lxMax: p.lxMax + along,
668
+ lzMin: p.lzMin - perp,
669
+ lzMax: p.lzMax + perp,
670
+ yMin: p.yMin,
671
+ yMax: p.yMax,
672
+ })
673
+ }
674
+
675
+ function prismXzCorners(p: OrientedPrismY, halfShrinkXZ: number): readonly (readonly [number, number])[] {
676
+ const sx = p.lxMax - p.lxMin > halfShrinkXZ * 2 + 0.005 ? halfShrinkXZ : 0
677
+ const sz = p.lzMax - p.lzMin > halfShrinkXZ * 2 + 0.005 ? halfShrinkXZ : 0
678
+ const lx0 = p.lxMin + sx
679
+ const lx1 = p.lxMax - sx
680
+ const lz0 = p.lzMin + sz
681
+ const lz1 = p.lzMax - sz
682
+ const { centerX, centerZ, cos, sin } = p
683
+ return [
684
+ [centerX + lx0 * cos - lz0 * sin, centerZ + lx0 * sin + lz0 * cos],
685
+ [centerX + lx1 * cos - lz0 * sin, centerZ + lx1 * sin + lz0 * cos],
686
+ [centerX + lx1 * cos - lz1 * sin, centerZ + lx1 * sin + lz1 * cos],
687
+ [centerX + lx0 * cos - lz1 * sin, centerZ + lx0 * sin + lz1 * cos],
688
+ ]
689
+ }
690
+
691
+ /**
692
+ * Exact symmetric OBB-vs-OBB overlap test (2D SAT in XZ on all 4 rotated axes + Y interval overlap).
693
+ * Optional `shrinkXZ` / `shrinkY` specify total penetration tolerances split symmetrically across both prisms
694
+ * while guarding thin prisms (`heightM <= 0.06` keeps full Y span so `minY < maxY` is never violated).
695
+ */
696
+ export function orientedPrismsIntersect(
697
+ a: OrientedPrismY,
698
+ b: OrientedPrismY,
699
+ shrinkXZ = 0,
700
+ shrinkY = 0,
701
+ ): boolean {
702
+ const halfY = Math.max(0, shrinkY) / 2
703
+ const ayShrink = a.yMax - a.yMin > 0.06 ? halfY : 0
704
+ const byShrink = b.yMax - b.yMin > 0.06 ? halfY : 0
705
+ const aMinY = a.yMin + ayShrink
706
+ const aMaxY = a.yMax - ayShrink
707
+ const bMinY = b.yMin + byShrink
708
+ const bMaxY = b.yMax - byShrink
709
+ if (!(aMinY < aMaxY) || !(bMinY < bMaxY)) return false
710
+ if (aMaxY <= bMinY + 1e-9 || bMaxY <= aMinY + 1e-9) return false
711
+
712
+ // Fast AABB XZ broadphase
713
+ if (
714
+ a.aabb.maxX <= b.aabb.minX + 1e-9 ||
715
+ b.aabb.maxX <= a.aabb.minX + 1e-9 ||
716
+ a.aabb.maxZ <= b.aabb.minZ + 1e-9 ||
717
+ b.aabb.maxZ <= a.aabb.minZ + 1e-9
718
+ ) {
719
+ return false
720
+ }
721
+
722
+ const halfXZ = Math.max(0, shrinkXZ) / 2
723
+ const cornersA = prismXzCorners(a, halfXZ)
724
+ const cornersB = prismXzCorners(b, halfXZ)
725
+ const axes: readonly (readonly [number, number])[] = [
726
+ [a.cos, a.sin],
727
+ [-a.sin, a.cos],
728
+ [b.cos, b.sin],
729
+ [-b.sin, b.cos],
730
+ ]
731
+
732
+ for (const [ax, az] of axes) {
733
+ let minA = Number.POSITIVE_INFINITY
734
+ let maxA = Number.NEGATIVE_INFINITY
735
+ for (const [cx, cz] of cornersA) {
736
+ const proj = cx * ax + cz * az
737
+ if (proj < minA) minA = proj
738
+ if (proj > maxA) maxA = proj
739
+ }
740
+ let minB = Number.POSITIVE_INFINITY
741
+ let maxB = Number.NEGATIVE_INFINITY
742
+ for (const [cx, cz] of cornersB) {
743
+ const proj = cx * ax + cz * az
744
+ if (proj < minB) minB = proj
745
+ if (proj > maxB) maxB = proj
746
+ }
747
+ if (maxA <= minB + 1e-9 || maxB <= minA + 1e-9) return false
748
+ }
749
+
750
+ return true
751
+ }
752
+
753
+ export type { CanonicalWall }