@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,1474 @@
1
+ /**
2
+ * Room- & Site-Aware Auto-Furnisher + Exterior Landscaper (`src/furnishings/autopopulate.ts`).
3
+ *
4
+ * Consumes `extractBuildingFurnishingsAnatomy()` (powered by `@kruschdev/pascal-mep-kernel`)
5
+ * to stage every room with zero cabinetry overlap, ergonomic clearances, electronics/AV setups,
6
+ * potted houseplants, and exterior foundation bushes + privacy hedges + shade/ornamental trees.
7
+ *
8
+ * Pure framework-free TypeScript: zero `three`, `react`, `@pascal-app/*`, or `next` imports.
9
+ */
10
+
11
+ import {
12
+ extractNodeYawRad,
13
+ type OrientedPrismY,
14
+ } from '@kruschdev/pascal-mep-kernel'
15
+ import {
16
+ belongsToLevel,
17
+ compileBuildingAnatomy,
18
+ isPointEnclosedByWalls,
19
+ pointInPolygon2D,
20
+ resolveNodeLevelId,
21
+ } from '@kruschdev/pascal-mep-kernel/anatomy'
22
+ import { buildFurnishingElectricalDemand, deriveDisplayDimensionsM, getFurnishingSpec } from './catalog'
23
+ import {
24
+ type FurnishingRoomAnalysis,
25
+ type SolidWallAnchor,
26
+ createFurnishingPrismY,
27
+ expandOpeningPrism,
28
+ extractBuildingFurnishingsAnatomy,
29
+ findContainingRoom,
30
+ findRankedSolidWallsForRoom,
31
+ minDistanceToExteriorWallM,
32
+ orientedPrismsIntersect,
33
+ } from './geometry'
34
+ import {
35
+ type BlueprintFurnishingItemDirective,
36
+ type BudgetTier,
37
+ PLANT_MATURITY_SCALE,
38
+ type PlantMaturity,
39
+ type PlantSeason,
40
+ STYLE_PRESET_PALETTES,
41
+ type SceneNodeLike,
42
+ type StylePreset,
43
+ round3,
44
+ } from './types'
45
+
46
+ export type FurnishingsAutoPopulateOptions = {
47
+ readonly levelId?: string
48
+ readonly stylePreset?: StylePreset
49
+ readonly budgetTier?: BudgetTier
50
+ readonly season?: PlantSeason
51
+ readonly includeInteriorFurniture?: boolean
52
+ readonly includeElectronics?: boolean
53
+ readonly includeHouseplants?: boolean
54
+ readonly includeRugsAndDecor?: boolean
55
+ readonly includeExteriorLandscaping?: boolean
56
+ readonly clearExisting?: boolean
57
+ }
58
+
59
+ export type PlannedNodeCreate = {
60
+ readonly parentId: string
61
+ readonly node: Record<string, unknown> & { readonly id: string; readonly type: string }
62
+ }
63
+
64
+ export type FurnishingsAutoPopulatePlan = {
65
+ readonly summary: string
66
+ readonly deleteIds: readonly string[]
67
+ readonly create: readonly PlannedNodeCreate[]
68
+ readonly counts: {
69
+ readonly furnitureItems: number
70
+ readonly electronicsItems: number
71
+ readonly indoorPlants: number
72
+ readonly outdoorPlants: number
73
+ readonly roomsStaged: number
74
+ }
75
+ }
76
+
77
+ const MANAGED_TYPES = new Set([
78
+ 'furnishings:assembly',
79
+ 'furnishings:item',
80
+ 'furnishings:electronics',
81
+ 'furnishings:plant',
82
+ ])
83
+
84
+ export function planFurnishingsAutoPopulate(
85
+ nodes: Readonly<Record<string, SceneNodeLike>>,
86
+ options: FurnishingsAutoPopulateOptions = {},
87
+ ): FurnishingsAutoPopulatePlan {
88
+ const stylePreset: StylePreset = options.stylePreset ?? 'mid-century'
89
+ const budgetTier: BudgetTier = options.budgetTier ?? 'mid-tier'
90
+ const season: PlantSeason = options.season ?? 'summer'
91
+ const includeInteriorFurniture = options.includeInteriorFurniture ?? true
92
+ const includeElectronics = options.includeElectronics ?? true
93
+ const includeHouseplants = options.includeHouseplants ?? true
94
+ const includeRugsAndDecor = options.includeRugsAndDecor ?? true
95
+ const includeExteriorLandscaping = options.includeExteriorLandscaping ?? true
96
+ const clearExisting = options.clearExisting ?? true
97
+
98
+ const palette = STYLE_PRESET_PALETTES[stylePreset]
99
+ const anatomy = extractBuildingFurnishingsAnatomy(nodes, options.levelId ?? null)
100
+
101
+ const targetLevelId = options.levelId ?? anatomy.primaryLevelId
102
+ if (!targetLevelId || !nodes[targetLevelId]) {
103
+ return {
104
+ summary: 'No building level found in scene to stage furnishings.',
105
+ deleteIds: [],
106
+ create: [],
107
+ counts: { furnitureItems: 0, electronicsItems: 0, indoorPlants: 0, outdoorPlants: 0, roomsStaged: 0 },
108
+ }
109
+ }
110
+
111
+ const deleteIds: string[] = []
112
+ if (clearExisting) {
113
+ for (const n of Object.values(nodes)) {
114
+ if (!MANAGED_TYPES.has(n.type)) continue
115
+ if (options.levelId && !belongsToLevel(nodes, n, options.levelId)) continue
116
+ deleteIds.push(n.id)
117
+ }
118
+ }
119
+
120
+ const usedIds = new Set<string>(Object.keys(nodes))
121
+ for (const id of deleteIds) usedIds.delete(id)
122
+
123
+ const nextId = (prefix: string): string => {
124
+ let i = 1
125
+ while (usedIds.has(`${prefix}_${i}`)) i += 1
126
+ const id = `${prefix}_${i}`
127
+ usedIds.add(id)
128
+ return id
129
+ }
130
+
131
+ const create: PlannedNodeCreate[] = []
132
+ let furnitureItems = 0
133
+ let electronicsItems = 0
134
+ let indoorPlants = 0
135
+ let outdoorPlants = 0
136
+ let roomsStaged = 0
137
+
138
+ const deletedSet = new Set(deleteIds)
139
+
140
+ // Resolve the lowest/ground level so exterior in-ground landscaping never floats on upper floors
141
+ const allLevels = Object.values(nodes).filter((n) => n.type === 'level')
142
+ const groundLevelId =
143
+ allLevels.length > 0
144
+ ? allLevels
145
+ .slice()
146
+ .sort((a, b) => {
147
+ const la = typeof a.level === 'number' && Number.isFinite(a.level) ? a.level : 0
148
+ const lb = typeof b.level === 'number' && Number.isFinite(b.level) ? b.level : 0
149
+ if (la !== lb) return la - lb
150
+ const ea = typeof a.elevation === 'number' && Number.isFinite(a.elevation) ? a.elevation : 0
151
+ const eb = typeof b.elevation === 'number' && Number.isFinite(b.elevation) ? b.elevation : 0
152
+ return ea - eb
153
+ })[0]!.id
154
+ : targetLevelId
155
+ const shouldStageExteriorLandscaping =
156
+ includeExteriorLandscaping && (!options.levelId || options.levelId === groundLevelId)
157
+ const exteriorLevelId = groundLevelId && nodes[groundLevelId] ? groundLevelId : targetLevelId
158
+
159
+ // 1. Assembly node (whole-building FF&E & Landscape staging configuration — avoid duplicates when clearExisting=false)
160
+ const hasSurvivingAssembly = Object.values(nodes).some(
161
+ (n) => n.type === 'furnishings:assembly' && !deletedSet.has(n.id),
162
+ )
163
+ if (!hasSurvivingAssembly) {
164
+ create.push({
165
+ parentId: targetLevelId,
166
+ node: {
167
+ object: 'node',
168
+ id: nextId('frnasm'),
169
+ type: 'furnishings:assembly',
170
+ name: `FF&E & Landscape Package (${palette.label})`,
171
+ parentId: targetLevelId,
172
+ visible: true,
173
+ metadata: {},
174
+ position: [0, 0, 0],
175
+ rotation: 0,
176
+ stylePreset,
177
+ budgetTier,
178
+ season,
179
+ includeExteriorLandscaping,
180
+ includeElectronics,
181
+ includeHouseplants,
182
+ includeRugsAndDecor,
183
+ hardinessZone: '7b',
184
+ },
185
+ })
186
+ }
187
+
188
+ // Track placed exact 3D oriented prisms to guarantee zero collisions.
189
+ // When `clearExisting` is false, seed surviving furnishings (including floor HVAC registers & wall-mounted items)
190
+ // so new items never overlap existing floor or wall placements.
191
+ const placedPrisms: Array<{ levelId: string; prism: OrientedPrismY }> = []
192
+ const placedWallPrisms: Array<{ levelId: string; prism: OrientedPrismY }> = []
193
+ for (const n of Object.values(nodes)) {
194
+ if (deletedSet.has(n.id) || n.visible === false) continue
195
+ // Seed existing plumbing fixtures (toilets, vanities, tubs, sinks, washers) so furniture never overlaps MEP fixtures
196
+ if (n.type === 'plumbing:fixture') {
197
+ const pos = Array.isArray(n.position) ? n.position : null
198
+ if (pos && typeof pos[0] === 'number' && typeof pos[2] === 'number') {
199
+ const fk = String(n.fixtureKind ?? n.kind ?? '').toLowerCase()
200
+ const [defW, defD, defH]: [number, number, number] =
201
+ fk === 'bathtub' || fk === 'tub-shower-combo'
202
+ ? [1.62, 0.78, 0.65]
203
+ : fk === 'shower'
204
+ ? [1.15, 0.92, 2.05]
205
+ : fk === 'lavatory'
206
+ ? [0.85, 0.56, 0.86]
207
+ : fk === 'water-closet'
208
+ ? [0.46, 0.72, 0.78]
209
+ : fk === 'kitchen-sink' || fk === 'dishwasher' || fk === 'clothes-washer' || fk === 'laundry-sink'
210
+ ? [0.72, 0.66, 0.88]
211
+ : [0.75, 0.75, 0.9]
212
+ const fw = Math.max(0.01, typeof n.widthM === 'number' && Number.isFinite(n.widthM) ? n.widthM : defW)
213
+ const fd = Math.max(0.01, typeof n.depthM === 'number' && Number.isFinite(n.depthM) ? n.depthM : defD)
214
+ const fh = Math.max(0.01, typeof n.heightM === 'number' && Number.isFinite(n.heightM) ? n.heightM : defH)
215
+ const lv = resolveNodeLevelId(nodes, n) ?? targetLevelId
216
+ placedPrisms.push({
217
+ levelId: lv,
218
+ prism: createFurnishingPrismY({
219
+ centerX: pos[0],
220
+ centerZ: pos[2],
221
+ yawRad: extractNodeYawRad(n.rotation),
222
+ widthM: fw,
223
+ depthM: fd,
224
+ yMin: 0,
225
+ yMax: fh,
226
+ }),
227
+ })
228
+ }
229
+ continue
230
+ }
231
+ if (n.type !== 'furnishings:item' && n.type !== 'furnishings:electronics' && n.type !== 'furnishings:plant') {
232
+ continue
233
+ }
234
+ const kind = String(n.itemKind ?? n.plantKind ?? '')
235
+ const spec = getFurnishingSpec(kind)
236
+ const isFloorHvacGrate = kind === 'vent-grate-floor-brass'
237
+ const pos = Array.isArray(n.position) ? n.position : [0, 0, 0]
238
+ const nx = typeof pos[0] === 'number' && Number.isFinite(pos[0]) ? pos[0] : 0
239
+ const ny = typeof pos[1] === 'number' && Number.isFinite(pos[1]) ? pos[1] : (spec?.defaultElevationM ?? 0)
240
+ const nz = typeof pos[2] === 'number' && Number.isFinite(pos[2]) ? pos[2] : 0
241
+ const isWallItem =
242
+ kind === 'vent-grille-return-flush'
243
+ ? ny < 2.1
244
+ : Boolean(spec?.isWallMounted || n.mountStyle === 'wall-mount')
245
+ if (
246
+ (spec?.isFloorCovering && !isFloorHvacGrate) ||
247
+ spec?.isDeskTopItem ||
248
+ (!isWallItem && spec?.isCeilingMounted)
249
+ ) {
250
+ continue
251
+ }
252
+ if (n.type === 'furnishings:electronics' && !isWallItem) {
253
+ const ms = String(n.mountStyle ?? spec?.defaultMountStyle ?? 'stand')
254
+ if (!(ny === 0 && (ms === 'floor' || ms === 'stand'))) continue
255
+ }
256
+ let nw = Math.max(0.01, typeof n.widthM === 'number' && Number.isFinite(n.widthM) ? n.widthM : (spec?.widthM ?? 0.8))
257
+ let nd = Math.max(0.01, typeof n.depthM === 'number' && Number.isFinite(n.depthM) ? n.depthM : (spec?.depthM ?? 0.8))
258
+ let nh = Math.max(0.01, typeof n.heightM === 'number' && Number.isFinite(n.heightM) ? n.heightM : (spec?.heightM ?? 0.8))
259
+ if (n.type === 'furnishings:electronics' && typeof n.screenDiagonalIn === 'number') {
260
+ const derived = deriveDisplayDimensionsM(kind, n.screenDiagonalIn)
261
+ const usesCatalogDefaults =
262
+ (n.widthM === undefined || n.widthM === spec?.widthM) &&
263
+ (n.heightM === undefined || n.heightM === spec?.heightM)
264
+ if (derived && usesCatalogDefaults) {
265
+ nw = Math.max(0.01, derived.widthM)
266
+ nh = Math.max(0.01, derived.heightM)
267
+ }
268
+ }
269
+ if (isFloorHvacGrate) {
270
+ nh = Math.max(nh, 0.5)
271
+ }
272
+ if (n.type === 'furnishings:plant') {
273
+ const matKey = String(n.maturity ?? 'mature') as PlantMaturity
274
+ const scale = PLANT_MATURITY_SCALE[matKey] ?? 1.0
275
+ const canopyR = Math.max(
276
+ 0.01,
277
+ typeof n.canopyRadiusM === 'number' && Number.isFinite(n.canopyRadiusM)
278
+ ? n.canopyRadiusM
279
+ : (spec?.widthM ?? 1.0) / 2,
280
+ )
281
+ nw = Math.max(0.01, canopyR * 2 * scale)
282
+ const isLinear = kind === 'bush-hedge-row' || kind === 'plant-succulent-trough'
283
+ nd = Math.max(0.01, isLinear ? (spec?.depthM ?? 0.5) * scale : canopyR * 2 * scale)
284
+ nh = Math.max(0.01, nh * scale)
285
+ }
286
+ const lv = resolveNodeLevelId(nodes, n) ?? targetLevelId
287
+ const seededPrism = createFurnishingPrismY({
288
+ centerX: nx,
289
+ centerZ: nz,
290
+ yawRad: extractNodeYawRad(n.rotation),
291
+ widthM: nw,
292
+ depthM: nd,
293
+ yMin: ny,
294
+ yMax: ny + nh,
295
+ })
296
+ if (isWallItem) {
297
+ if (kind !== 'curtain-drape') placedWallPrisms.push({ levelId: lv, prism: seededPrism })
298
+ } else {
299
+ placedPrisms.push({ levelId: lv, prism: seededPrism })
300
+ }
301
+ }
302
+
303
+ const isDoorBlockedPoint = (levelId: string, x: number, z: number, padM = 0.65): boolean => {
304
+ for (const dp of anatomy.doorPrisms) {
305
+ if (dp.levelId !== levelId) continue
306
+ const dx = x - dp.centerX
307
+ const dz = z - dp.centerZ
308
+ const lx = dx * dp.cos + dz * dp.sin
309
+ const lz = -dx * dp.sin + dz * dp.cos
310
+ const clx = Math.max(dp.lxMin - lx, 0, lx - dp.lxMax)
311
+ const clz = Math.max(dp.lzMin - lz, 0, lz - dp.lzMax)
312
+ if (Math.hypot(clx, clz) < padM) return true
313
+ }
314
+ return false
315
+ }
316
+
317
+ const prismHitsDoorSwing = (levelId: string, prism: OrientedPrismY, marginM = 0.48): boolean => {
318
+ for (const dp of anatomy.doorPrisms) {
319
+ if (dp.levelId !== levelId) continue
320
+ const expanded = expandOpeningPrism(dp, marginM, marginM)
321
+ if (orientedPrismsIntersect(prism, expanded)) return true
322
+ }
323
+ return false
324
+ }
325
+
326
+ const prismHitsWindowOpening = (levelId: string, prism: OrientedPrismY): boolean => {
327
+ for (const wp of anatomy.windowPrisms) {
328
+ if (wp.levelId !== levelId) continue
329
+ const expanded = expandOpeningPrism(wp, 0.04, 0.35)
330
+ if (orientedPrismsIntersect(prism, expanded)) return true
331
+ }
332
+ return false
333
+ }
334
+
335
+ const addFurniture = (params: {
336
+ levelId: string
337
+ kind: string
338
+ x: number
339
+ y?: number
340
+ z: number
341
+ rotation: number
342
+ roomName: string
343
+ widthM?: number
344
+ depthM?: number
345
+ heightM?: number
346
+ ignoreCollision?: boolean
347
+ }): boolean => {
348
+ const spec = getFurnishingSpec(params.kind)
349
+ if (!spec) return false
350
+ const fw = round3(Math.max(0.01, typeof params.widthM === 'number' && Number.isFinite(params.widthM) ? params.widthM : spec.widthM))
351
+ const fd = round3(Math.max(0.01, typeof params.depthM === 'number' && Number.isFinite(params.depthM) ? params.depthM : spec.depthM))
352
+ const fh = round3(Math.max(0.01, typeof params.heightM === 'number' && Number.isFinite(params.heightM) ? params.heightM : spec.heightM))
353
+ const fy = round3(params.y ?? spec.defaultElevationM)
354
+ const isSolidFloor = !spec.isFloorCovering && !spec.isDeskTopItem && !spec.isWallMounted && !spec.isCeilingMounted
355
+ const checksWindow =
356
+ !spec.isFloorCovering &&
357
+ !spec.isCeilingMounted &&
358
+ !spec.isDeskTopItem &&
359
+ spec.kind !== 'curtain-drape' &&
360
+ (Boolean(spec.isWallMounted) || fh >= 1.4)
361
+ if (isSolidFloor || checksWindow) {
362
+ const candidatePrism = createFurnishingPrismY({
363
+ centerX: params.x,
364
+ centerZ: params.z,
365
+ yawRad: params.rotation,
366
+ widthM: fw,
367
+ depthM: fd,
368
+ yMin: fy,
369
+ yMax: fy + fh,
370
+ })
371
+ if (isSolidFloor && prismHitsDoorSwing(params.levelId, candidatePrism)) return false
372
+ if (checksWindow && prismHitsWindowOpening(params.levelId, candidatePrism)) return false
373
+ if (isSolidFloor && !params.ignoreCollision) {
374
+ for (const placed of placedPrisms) {
375
+ if (placed.levelId !== params.levelId) continue
376
+ if (orientedPrismsIntersect(placed.prism, candidatePrism)) return false
377
+ }
378
+ placedPrisms.push({ levelId: params.levelId, prism: candidatePrism })
379
+ } else if (spec.isWallMounted && spec.kind !== 'curtain-drape' && !params.ignoreCollision) {
380
+ for (const placed of placedWallPrisms) {
381
+ if (placed.levelId !== params.levelId) continue
382
+ if (orientedPrismsIntersect(placed.prism, candidatePrism)) return false
383
+ }
384
+ placedWallPrisms.push({ levelId: params.levelId, prism: candidatePrism })
385
+ }
386
+ }
387
+ furnitureItems += 1
388
+ const electricalDemand = buildFurnishingElectricalDemand(spec, {
389
+ wattageW: Math.max(0, spec.wattageW),
390
+ elevationM: fy,
391
+ })
392
+ create.push({
393
+ parentId: params.levelId,
394
+ node: {
395
+ object: 'node',
396
+ id: nextId('frnitm'),
397
+ type: 'furnishings:item',
398
+ name: spec.label,
399
+ parentId: params.levelId,
400
+ visible: true,
401
+ metadata: {},
402
+ itemKind: spec.kind,
403
+ position: [round3(params.x), fy, round3(params.z)],
404
+ rotation: round3(params.rotation),
405
+ roomName: params.roomName,
406
+ stylePreset,
407
+ woodFinish: palette.woodFinish,
408
+ fabricFinish: palette.fabricFinish,
409
+ metalFinish: palette.metalFinish,
410
+ widthM: fw,
411
+ depthM: fd,
412
+ heightM: fh,
413
+ quantity: 1,
414
+ ...(electricalDemand ? { electricalDemand } : {}),
415
+ notes: '',
416
+ },
417
+ })
418
+ return true
419
+ }
420
+
421
+ const addElectronics = (params: {
422
+ levelId: string
423
+ kind: string
424
+ x: number
425
+ y?: number
426
+ z: number
427
+ rotation: number
428
+ roomName: string
429
+ screenDiagonalIn?: number
430
+ channelRole?: string
431
+ screenState?: 'ambient' | 'cinema' | 'code' | 'off'
432
+ ignoreCollision?: boolean
433
+ }): boolean => {
434
+ const spec = getFurnishingSpec(params.kind)
435
+ if (!spec) return false
436
+ const ey = round3(params.y ?? spec.defaultElevationM)
437
+ const mountStyle = spec.defaultMountStyle ?? 'stand'
438
+ const resolvedScreenDiagonalIn = params.screenDiagonalIn ?? spec.defaultScreenDiagonalIn
439
+ const derivedDims = deriveDisplayDimensionsM(spec.kind, resolvedScreenDiagonalIn)
440
+ const ew = round3(Math.max(0.01, derivedDims?.widthM ?? spec.widthM))
441
+ const ed = round3(Math.max(0.01, spec.depthM))
442
+ const eh = round3(Math.max(0.01, derivedDims?.heightM ?? spec.heightM))
443
+ const isFloorStanding = ey === 0 && (mountStyle === 'floor' || mountStyle === 'stand')
444
+ const isWallMount = Boolean(spec.isWallMounted || mountStyle === 'wall-mount')
445
+ if (isFloorStanding || isWallMount) {
446
+ const candidatePrism = createFurnishingPrismY({
447
+ centerX: params.x,
448
+ centerZ: params.z,
449
+ yawRad: params.rotation,
450
+ widthM: ew,
451
+ depthM: ed,
452
+ yMin: ey,
453
+ yMax: ey + eh,
454
+ })
455
+ if (prismHitsDoorSwing(params.levelId, candidatePrism)) return false
456
+ if (isWallMount && prismHitsWindowOpening(params.levelId, candidatePrism)) return false
457
+ if (isFloorStanding && !params.ignoreCollision) {
458
+ for (const placed of placedPrisms) {
459
+ if (placed.levelId !== params.levelId) continue
460
+ if (orientedPrismsIntersect(placed.prism, candidatePrism)) return false
461
+ }
462
+ placedPrisms.push({ levelId: params.levelId, prism: candidatePrism })
463
+ } else if (isWallMount && !params.ignoreCollision) {
464
+ for (const placed of placedWallPrisms) {
465
+ if (placed.levelId !== params.levelId) continue
466
+ if (orientedPrismsIntersect(placed.prism, candidatePrism)) return false
467
+ }
468
+ placedWallPrisms.push({ levelId: params.levelId, prism: candidatePrism })
469
+ }
470
+ }
471
+ electronicsItems += 1
472
+ const wattageW = Math.max(0, spec.wattageW)
473
+ const electricalDemand = buildFurnishingElectricalDemand(spec, { wattageW, elevationM: ey })
474
+ create.push({
475
+ parentId: params.levelId,
476
+ node: {
477
+ object: 'node',
478
+ id: nextId('frnav'),
479
+ type: 'furnishings:electronics',
480
+ name: spec.label,
481
+ parentId: params.levelId,
482
+ visible: true,
483
+ metadata: {},
484
+ itemKind: spec.kind,
485
+ position: [round3(params.x), ey, round3(params.z)],
486
+ rotation: round3(params.rotation),
487
+ roomName: params.roomName,
488
+ ...(resolvedScreenDiagonalIn !== undefined ? { screenDiagonalIn: resolvedScreenDiagonalIn } : {}),
489
+ mountStyle,
490
+ finish: palette.electronicsFinish,
491
+ widthM: ew,
492
+ depthM: ed,
493
+ heightM: eh,
494
+ wattageW,
495
+ channelRole: params.channelRole ?? spec.defaultChannelRole ?? 'aux',
496
+ screenState: params.screenState ?? 'ambient',
497
+ quantity: 1,
498
+ ...(electricalDemand ? { electricalDemand } : {}),
499
+ notes: '',
500
+ },
501
+ })
502
+ return true
503
+ }
504
+
505
+ const addPlant = (params: {
506
+ levelId: string
507
+ kind: string
508
+ x: number
509
+ z: number
510
+ rotation?: number
511
+ zoneName: string
512
+ isOutdoor: boolean
513
+ registerCollision?: boolean
514
+ ignoreCollision?: boolean
515
+ maturity?: 'sapling' | 'juvenile' | 'mature' | 'specimen'
516
+ seed: number
517
+ }): boolean => {
518
+ const spec = getFurnishingSpec(params.kind)
519
+ if (!spec) return false
520
+ const rot = params.rotation ?? 0
521
+ const pw = Math.max(0.01, spec.widthM)
522
+ const pd = Math.max(0.01, spec.depthM)
523
+ const ph = Math.max(0.01, spec.heightM)
524
+ const plantPrism = createFurnishingPrismY({
525
+ centerX: params.x,
526
+ centerZ: params.z,
527
+ yawRad: rot,
528
+ widthM: pw,
529
+ depthM: pd,
530
+ yMin: 0,
531
+ yMax: ph,
532
+ })
533
+ if (prismHitsDoorSwing(params.levelId, plantPrism)) return false
534
+ if ((!params.isOutdoor || params.registerCollision) && !params.ignoreCollision) {
535
+ for (const placed of placedPrisms) {
536
+ if (placed.levelId !== params.levelId) continue
537
+ if (orientedPrismsIntersect(placed.prism, plantPrism)) return false
538
+ }
539
+ placedPrisms.push({ levelId: params.levelId, prism: plantPrism })
540
+ }
541
+ if (params.isOutdoor) outdoorPlants += 1
542
+ else indoorPlants += 1
543
+ create.push({
544
+ parentId: params.levelId,
545
+ node: {
546
+ object: 'node',
547
+ id: nextId('frnplt'),
548
+ type: 'furnishings:plant',
549
+ name: spec.label,
550
+ parentId: params.levelId,
551
+ visible: true,
552
+ metadata: {},
553
+ plantKind: spec.kind,
554
+ position: [round3(params.x), 0, round3(params.z)],
555
+ rotation: round3(params.rotation ?? 0),
556
+ zoneName: params.zoneName,
557
+ placement: spec.defaultPlacement ?? (params.isOutdoor ? 'in-ground' : 'potted'),
558
+ species: spec.defaultSpecies ?? spec.label,
559
+ maturity: params.maturity ?? 'mature',
560
+ season,
561
+ potStyle: spec.defaultPlacement === 'in-ground' ? 'none' : (spec.defaultPotStyle ?? palette.potStyle),
562
+ heightM: round3(ph),
563
+ canopyRadiusM: round3(Math.max(0.01, pw / 2)),
564
+ seed: params.seed,
565
+ quantity: 1,
566
+ notes: '',
567
+ },
568
+ })
569
+ return true
570
+ }
571
+
572
+ const placeBlueprintDirective = (
573
+ room: FurnishingRoomAnalysis,
574
+ levelId: string,
575
+ dir: BlueprintFurnishingItemDirective,
576
+ seedBase: number,
577
+ ): boolean => {
578
+ const spec = getFurnishingSpec(dir.kind)
579
+ if (!spec) return false
580
+ const insideRoom = (x: number, z: number): boolean => pointInPolygon2D(x, z, room.polygon)
581
+ const count = Math.max(1, Math.min(12, Math.floor(dir.count ?? 1)))
582
+ const effWidthM = Math.max(0.01, typeof dir.widthM === 'number' && Number.isFinite(dir.widthM) ? dir.widthM : spec.widthM)
583
+ const effDepthM = Math.max(0.01, typeof dir.depthM === 'number' && Number.isFinite(dir.depthM) ? dir.depthM : spec.depthM)
584
+ const spacing = dir.spacingM ?? effWidthM + 0.18
585
+
586
+ let baseX = room.centroid[0]
587
+ let baseZ = room.centroid[1]
588
+ let baseYaw = dir.rotationRad ?? 0
589
+ let tangX = 1
590
+ let tangZ = 0
591
+
592
+ if (dir.position && Number.isFinite(dir.position[0]) && Number.isFinite(dir.position[1])) {
593
+ baseX = dir.position[0]
594
+ baseZ = dir.position[1]
595
+ tangX = Math.cos(baseYaw)
596
+ tangZ = -Math.sin(baseYaw)
597
+ } else if (dir.wall && dir.wall !== 'center') {
598
+ const wallAnchor = findRankedSolidWallsForRoom(room, anatomy.walls, dir.wall)[0]
599
+ if (wallAnchor) {
600
+ const dist = dir.distanceFromWallM ?? (spec.isWallMounted ? 0.12 : effDepthM / 2 + 0.14)
601
+ const off = dir.offsetAlongWallM ?? 0
602
+ tangX = -wallAnchor.inwardNz
603
+ tangZ = wallAnchor.inwardNx
604
+ baseX = wallAnchor.midX + wallAnchor.inwardNx * dist + tangX * off
605
+ baseZ = wallAnchor.midZ + wallAnchor.inwardNz * dist + tangZ * off
606
+ baseYaw = dir.rotationRad ?? wallAnchor.yawRad
607
+ }
608
+ }
609
+
610
+ let placedAny = false
611
+ for (let k = 0; k < count; k++) {
612
+ const shift = count === 1 ? 0 : (k - (count - 1) / 2) * spacing
613
+ const px = baseX + tangX * shift
614
+ const pz = baseZ + tangZ * shift
615
+ if (room.polygon.length >= 3 && !insideRoom(px, pz)) continue
616
+ if (spec.nodeType === 'furnishings:plant') {
617
+ if (room.isOutdoor ? !includeExteriorLandscaping : !includeHouseplants) continue
618
+ const ok = addPlant({
619
+ levelId,
620
+ kind: spec.kind,
621
+ x: px,
622
+ z: pz,
623
+ rotation: baseYaw,
624
+ zoneName: room.name,
625
+ isOutdoor: room.isOutdoor,
626
+ registerCollision: true,
627
+ ignoreCollision: dir.ignoreCollision,
628
+ seed: seedBase + k * 7,
629
+ })
630
+ if (ok) placedAny = true
631
+ } else if (spec.nodeType === 'furnishings:electronics') {
632
+ if (!includeElectronics) continue
633
+ const ok = addElectronics({
634
+ levelId,
635
+ kind: spec.kind,
636
+ x: px,
637
+ y: dir.yM ?? spec.defaultElevationM,
638
+ z: pz,
639
+ rotation: baseYaw,
640
+ roomName: room.name,
641
+ screenDiagonalIn: dir.screenDiagonalIn,
642
+ channelRole: dir.channelRole,
643
+ ignoreCollision: dir.ignoreCollision,
644
+ })
645
+ if (ok) placedAny = true
646
+ } else {
647
+ if (spec.isFloorCovering ? !includeRugsAndDecor : !includeInteriorFurniture) continue
648
+ const ok = addFurniture({
649
+ levelId,
650
+ kind: spec.kind,
651
+ x: px,
652
+ y: dir.yM ?? spec.defaultElevationM,
653
+ z: pz,
654
+ rotation: baseYaw,
655
+ roomName: room.name,
656
+ widthM: dir.widthM,
657
+ depthM: dir.depthM,
658
+ ignoreCollision: dir.ignoreCollision,
659
+ })
660
+ if (ok) placedAny = true
661
+ }
662
+ }
663
+ return placedAny
664
+ }
665
+
666
+ const stageRoom = (room: FurnishingRoomAnalysis, idx: number) => {
667
+ const levelId = room.levelId ?? targetLevelId
668
+ const plan = room.furnishingPlan
669
+ if (plan?.mode === 'skip') return
670
+
671
+ // Honor explicit blueprint / design-deck furnishing items before falling back to heuristic staging
672
+ if (plan?.items && plan.items.length > 0) {
673
+ for (let di = 0; di < plan.items.length; di++) {
674
+ placeBlueprintDirective(room, levelId, plan.items[di]!, 600 + idx * 31 + di * 13)
675
+ }
676
+ }
677
+ if (plan?.mode === 'blueprint-only') return
678
+
679
+ const cx = room.centroid[0]
680
+ const cz = room.centroid[1]
681
+ const rankedWalls = findRankedSolidWallsForRoom(room, anatomy.walls, plan?.preferredAnchorWall)
682
+ const anchor: SolidWallAnchor | null = rankedWalls[0] ?? null
683
+ const inNx = anchor?.inwardNx ?? 0
684
+ const inNz = anchor?.inwardNz ?? 1
685
+ const wallYaw = anchor?.yawRad ?? 0
686
+ const faceWallYaw = Math.atan2(-inNx, -inNz)
687
+ const tangX = -inNz
688
+ const tangZ = inNx
689
+ const anchorX = anchor?.midX ?? cx
690
+ const anchorZ = anchor?.midZ ?? room.bounds.minZ + 0.15
691
+
692
+ const insideRoom = (x: number, z: number): boolean => pointInPolygon2D(x, z, room.polygon)
693
+
694
+ if (room.kind === 'living' || room.kind === 'media') {
695
+ const isMedia = room.kind === 'media'
696
+ // Media wall (console + OLED TV + soundbar or 5.1 speakers)
697
+ const mediaDist = 0.34
698
+ const mediaX = anchorX + inNx * mediaDist
699
+ const mediaZ = anchorZ + inNz * mediaDist
700
+ const mediaConsolePlaced =
701
+ includeInteriorFurniture && insideRoom(mediaX, mediaZ)
702
+ ? addFurniture({
703
+ levelId,
704
+ kind: 'media-console',
705
+ x: mediaX,
706
+ z: mediaZ,
707
+ rotation: wallYaw,
708
+ roomName: room.name,
709
+ })
710
+ : false
711
+ if (includeElectronics && insideRoom(mediaX, mediaZ)) {
712
+ addElectronics({
713
+ levelId,
714
+ kind: 'tv-oled-wall',
715
+ x: anchorX + inNx * 0.12,
716
+ y: 1.08,
717
+ z: anchorZ + inNz * 0.12,
718
+ rotation: wallYaw,
719
+ roomName: room.name,
720
+ screenDiagonalIn: isMedia || room.areaSqm >= 24 ? 77 : 65,
721
+ channelRole: 'display',
722
+ screenState: isMedia ? 'cinema' : 'ambient',
723
+ })
724
+ if (isMedia) {
725
+ if (mediaConsolePlaced) {
726
+ addElectronics({
727
+ levelId,
728
+ kind: 'speaker-center',
729
+ x: mediaX,
730
+ y: 0.56,
731
+ z: mediaZ,
732
+ rotation: wallYaw,
733
+ roomName: room.name,
734
+ channelRole: 'center',
735
+ })
736
+ }
737
+ // Symmetric L/R Floorstanding Tower Speakers
738
+ const spkOff = 1.32
739
+ const lx = mediaX - tangX * spkOff
740
+ const lz = mediaZ - tangZ * spkOff
741
+ const rx = mediaX + tangX * spkOff
742
+ const rz = mediaZ + tangZ * spkOff
743
+ if (insideRoom(lx, lz)) {
744
+ addElectronics({
745
+ levelId,
746
+ kind: 'speaker-tower',
747
+ x: lx,
748
+ y: 0,
749
+ z: lz,
750
+ rotation: wallYaw + 0.14,
751
+ roomName: room.name,
752
+ channelRole: 'left',
753
+ })
754
+ }
755
+ if (insideRoom(rx, rz)) {
756
+ addElectronics({
757
+ levelId,
758
+ kind: 'speaker-tower',
759
+ x: rx,
760
+ y: 0,
761
+ z: rz,
762
+ rotation: wallYaw - 0.14,
763
+ roomName: room.name,
764
+ channelRole: 'right',
765
+ })
766
+ }
767
+ const subX = mediaX + tangX * 1.78
768
+ const subZ = mediaZ + tangZ * 1.78
769
+ if (insideRoom(subX, subZ)) {
770
+ addElectronics({
771
+ levelId,
772
+ kind: 'subwoofer-powered',
773
+ x: subX,
774
+ y: 0,
775
+ z: subZ,
776
+ rotation: wallYaw,
777
+ roomName: room.name,
778
+ channelRole: 'subwoofer',
779
+ })
780
+ }
781
+ } else if (mediaConsolePlaced) {
782
+ addElectronics({
783
+ levelId,
784
+ kind: 'soundbar-dolby',
785
+ x: mediaX,
786
+ y: 0.56,
787
+ z: mediaZ,
788
+ rotation: wallYaw,
789
+ roomName: room.name,
790
+ channelRole: 'soundbar',
791
+ })
792
+ }
793
+ }
794
+
795
+ // Rug + Coffee Table + Sofa facing TV at ergonomic viewing distance (~2.6-3.1m)
796
+ const sofaKind = room.areaSqm >= 28 && Math.min(room.widthM, room.depthM) >= 5.2 ? 'sofa-sectional-l' : 'sofa-3seat'
797
+ const sofaSpec = getFurnishingSpec(sofaKind)!
798
+ const coffeeSpec = getFurnishingSpec('coffee-table')!
799
+ const viewDist = Math.min(3.1, Math.max(2.35, Math.min(room.widthM, room.depthM) * 0.62))
800
+ const sofaX = anchorX + inNx * viewDist
801
+ const sofaZ = anchorZ + inNz * viewDist
802
+ const coffeeOffsetFromSofa = sofaSpec.depthM / 2 + coffeeSpec.depthM / 2 + 0.45
803
+ const coffeeX = anchorX + inNx * Math.max(1.1, viewDist - coffeeOffsetFromSofa)
804
+ const coffeeZ = anchorZ + inNz * Math.max(1.1, viewDist - coffeeOffsetFromSofa)
805
+
806
+ if (includeRugsAndDecor && insideRoom(coffeeX, coffeeZ)) {
807
+ addFurniture({
808
+ levelId,
809
+ kind: 'area-rug-rect',
810
+ x: coffeeX,
811
+ z: coffeeZ,
812
+ rotation: wallYaw,
813
+ roomName: room.name,
814
+ widthM: Math.min(3.05, Math.max(2.0, room.widthM * 0.65)),
815
+ depthM: Math.min(2.44, Math.max(1.6, room.depthM * 0.55)),
816
+ })
817
+ }
818
+ if (includeInteriorFurniture) {
819
+ if (insideRoom(sofaX, sofaZ)) {
820
+ addFurniture({
821
+ levelId,
822
+ kind: sofaKind,
823
+ x: sofaX,
824
+ z: sofaZ,
825
+ rotation: faceWallYaw,
826
+ roomName: room.name,
827
+ })
828
+ }
829
+ if (insideRoom(coffeeX, coffeeZ)) {
830
+ addFurniture({
831
+ levelId,
832
+ kind: 'coffee-table',
833
+ x: coffeeX,
834
+ z: coffeeZ,
835
+ rotation: wallYaw,
836
+ roomName: room.name,
837
+ })
838
+ }
839
+ // Accent armchair & floor lamp spaced cleanly beyond sofa width
840
+ const chairOff = sofaSpec.widthM / 2 + 0.68
841
+ const chairX = coffeeX + tangX * chairOff
842
+ const chairZ = coffeeZ + tangZ * chairOff
843
+ if (insideRoom(chairX, chairZ)) {
844
+ addFurniture({
845
+ levelId,
846
+ kind: 'armchair-accent',
847
+ x: chairX,
848
+ z: chairZ,
849
+ rotation: faceWallYaw - Math.PI / 3,
850
+ roomName: room.name,
851
+ })
852
+ }
853
+ if (includeRugsAndDecor) {
854
+ const lampOff = sofaSpec.widthM / 2 + 0.58
855
+ const lampX = sofaX - tangX * lampOff
856
+ const lampZ = sofaZ - tangZ * lampOff
857
+ if (insideRoom(lampX, lampZ)) {
858
+ addFurniture({
859
+ levelId,
860
+ kind: 'floor-lamp-arc',
861
+ x: lampX,
862
+ z: lampZ,
863
+ rotation: wallYaw,
864
+ roomName: room.name,
865
+ })
866
+ }
867
+ }
868
+ }
869
+ if (includeHouseplants) {
870
+ const plantX = mediaX - tangX * 1.65
871
+ const plantZ = mediaZ - tangZ * 1.65
872
+ if (insideRoom(plantX, plantZ)) {
873
+ addPlant({
874
+ levelId,
875
+ kind: 'plant-fiddle-leaf-fig',
876
+ x: plantX,
877
+ z: plantZ,
878
+ zoneName: room.name,
879
+ isOutdoor: false,
880
+ seed: 101 + idx * 17,
881
+ })
882
+ }
883
+ }
884
+
885
+ // Open-concept Great Room: when large (>= 36 m²) and no dedicated dining room exists on this level,
886
+ // stage a secondary Dining table + chairs in the clear opposite end of the room.
887
+ const hasDedicatedDining = anatomy.rooms.some(
888
+ (other) => other.id !== room.id && other.levelId === levelId && other.kind === 'dining',
889
+ )
890
+ if (room.kind === 'living' && room.areaSqm >= 36 && !hasDedicatedDining && includeInteriorFurniture) {
891
+ const longSpanX = room.widthM >= room.depthM
892
+ const candCenters: Array<[number, number, number]> = longSpanX
893
+ ? [
894
+ [room.bounds.maxX - Math.min(2.1, room.widthM * 0.25), cz, Math.PI / 2],
895
+ [room.bounds.minX + Math.min(2.1, room.widthM * 0.25), cz, Math.PI / 2],
896
+ ]
897
+ : [
898
+ [cx, room.bounds.maxZ - Math.min(2.2, room.depthM * 0.24), 0],
899
+ [cx, room.bounds.minZ + Math.min(2.2, room.depthM * 0.24), 0],
900
+ ]
901
+ // Sort candidate quadrants farthest from the living sofa so dining & lounge stay clearly separated
902
+ candCenters.sort(
903
+ (a, b) => Math.hypot(b[0] - sofaX, b[1] - sofaZ) - Math.hypot(a[0] - sofaX, a[1] - sofaZ),
904
+ )
905
+ for (const [dx, dz, dYaw] of candCenters) {
906
+ if (!insideRoom(dx, dz) || Math.hypot(dx - sofaX, dz - sofaZ) < 2.6) continue
907
+ const tablePlaced = addFurniture({
908
+ levelId,
909
+ kind: 'dining-table-rect',
910
+ x: dx,
911
+ z: dz,
912
+ rotation: dYaw,
913
+ roomName: room.name,
914
+ })
915
+ if (tablePlaced) {
916
+ const cosD = Math.cos(dYaw)
917
+ const sinD = Math.sin(dYaw)
918
+ const chairOffsets: Array<[number, number, number]> = [
919
+ [-0.6, 0.78, Math.PI],
920
+ [0, 0.78, Math.PI],
921
+ [0.6, 0.78, Math.PI],
922
+ [-0.6, -0.78, 0],
923
+ [0, -0.78, 0],
924
+ [0.6, -0.78, 0],
925
+ ]
926
+ for (const [lx, lz, localYaw] of chairOffsets) {
927
+ const chX = dx + lx * cosD + lz * sinD
928
+ const chZ = dz - lx * sinD + lz * cosD
929
+ if (insideRoom(chX, chZ)) {
930
+ addFurniture({
931
+ levelId,
932
+ kind: 'dining-chair',
933
+ x: chX,
934
+ z: chZ,
935
+ rotation: dYaw + localYaw,
936
+ roomName: room.name,
937
+ ignoreCollision: true,
938
+ })
939
+ }
940
+ }
941
+ break
942
+ }
943
+ }
944
+ }
945
+ return
946
+ }
947
+
948
+ if (room.kind === 'bedroom') {
949
+ const isPrimaryBed = /(master|primary)/i.test(room.name)
950
+ const preferredBedKind =
951
+ plan?.bedSize === 'king'
952
+ ? 'bed-king'
953
+ : plan?.bedSize === 'queen'
954
+ ? 'bed-queen'
955
+ : plan?.bedSize === 'twin'
956
+ ? 'bed-twin'
957
+ : plan?.bedSize === 'bunk'
958
+ ? 'bunk-bed'
959
+ : (isPrimaryBed && room.areaSqm >= 16) || room.areaSqm >= 24
960
+ ? 'bed-king'
961
+ : room.areaSqm >= 11.5
962
+ ? 'bed-queen'
963
+ : 'bed-twin'
964
+ const fallbackSizes: readonly string[] =
965
+ preferredBedKind === 'bed-king'
966
+ ? ['bed-king', 'bed-queen', 'bed-twin']
967
+ : preferredBedKind === 'bed-queen'
968
+ ? ['bed-queen', 'bed-twin']
969
+ : [preferredBedKind]
970
+
971
+ const bedRankedWalls = findRankedSolidWallsForRoom(room, anatomy.walls, plan?.preferredAnchorWall, {
972
+ allowWindows: true,
973
+ })
974
+ const wallCandidates: Array<{
975
+ midX: number
976
+ midZ: number
977
+ inwardNx: number
978
+ inwardNz: number
979
+ yawRad: number
980
+ }> =
981
+ bedRankedWalls.length > 0
982
+ ? bedRankedWalls
983
+ : [{ midX: anchorX, midZ: anchorZ, inwardNx: inNx, inwardNz: inNz, yawRad: wallYaw }]
984
+
985
+ let placedBedWall: (typeof wallCandidates)[number] | null = null
986
+ let placedBedSpec = getFurnishingSpec(preferredBedKind)!
987
+ let placedBedX = cx
988
+ let placedBedZ = cz
989
+
990
+ if (includeInteriorFurniture) {
991
+ outerBedSearch: for (const sizeKind of fallbackSizes) {
992
+ const bSpec = getFurnishingSpec(sizeKind)
993
+ if (!bSpec) continue
994
+ const bDist = bSpec.depthM / 2 + 0.14
995
+ for (const cand of wallCandidates) {
996
+ const bx = cand.midX + cand.inwardNx * bDist
997
+ const bz = cand.midZ + cand.inwardNz * bDist
998
+ if (!insideRoom(bx, bz)) continue
999
+ if (
1000
+ addFurniture({
1001
+ levelId,
1002
+ kind: sizeKind,
1003
+ x: bx,
1004
+ z: bz,
1005
+ rotation: cand.yawRad,
1006
+ roomName: room.name,
1007
+ })
1008
+ ) {
1009
+ placedBedWall = cand
1010
+ placedBedSpec = bSpec
1011
+ placedBedX = bx
1012
+ placedBedZ = bz
1013
+ break outerBedSearch
1014
+ }
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ if (includeInteriorFurniture && !placedBedWall) return
1020
+
1021
+ const refWall = placedBedWall ?? wallCandidates[0]!
1022
+ const refBedDist = placedBedSpec.depthM / 2 + 0.14
1023
+ const refBedX = placedBedWall ? placedBedX : refWall.midX + refWall.inwardNx * refBedDist
1024
+ const refBedZ = placedBedWall ? placedBedZ : refWall.midZ + refWall.inwardNz * refBedDist
1025
+ const bNx = refWall.inwardNx
1026
+ const bNz = refWall.inwardNz
1027
+ const bYaw = refWall.yawRad
1028
+ const bFaceYaw = Math.atan2(-bNx, -bNz)
1029
+ const bTangX = -bNz
1030
+ const bTangZ = bNx
1031
+
1032
+ if (includeRugsAndDecor && insideRoom(refBedX, refBedZ)) {
1033
+ addFurniture({
1034
+ levelId,
1035
+ kind: 'area-rug-rect',
1036
+ x: refBedX + bNx * 0.35,
1037
+ z: refBedZ + bNz * 0.35,
1038
+ rotation: bYaw,
1039
+ roomName: room.name,
1040
+ widthM: Math.max(0.8, Math.min(2.74, room.widthM * 0.72)),
1041
+ depthM: Math.max(0.8, Math.min(2.13, room.depthM * 0.62)),
1042
+ })
1043
+ }
1044
+
1045
+ if (includeInteriorFurniture && placedBedWall) {
1046
+ const nsOffset = placedBedSpec.widthM / 2 + 0.42
1047
+ const nsDist = 0.34
1048
+ for (const side of [-1, 1] as const) {
1049
+ const nxPos = placedBedWall.midX + bNx * nsDist + bTangX * nsOffset * side
1050
+ const nzPos = placedBedWall.midZ + bNz * nsDist + bTangZ * nsOffset * side
1051
+ if (insideRoom(nxPos, nzPos)) {
1052
+ const nightstandPlaced = addFurniture({
1053
+ levelId,
1054
+ kind: 'nightstand',
1055
+ x: nxPos,
1056
+ z: nzPos,
1057
+ rotation: bYaw,
1058
+ roomName: room.name,
1059
+ })
1060
+ if (nightstandPlaced && includeRugsAndDecor) {
1061
+ addFurniture({
1062
+ levelId,
1063
+ kind: 'table-lamp',
1064
+ x: nxPos,
1065
+ y: 0.58,
1066
+ z: nzPos,
1067
+ rotation: bYaw,
1068
+ roomName: room.name,
1069
+ })
1070
+ }
1071
+ }
1072
+ }
1073
+ // Dresser opposite or adjacent if space allows
1074
+ const dresserX = placedBedX + bNx * 2.15
1075
+ const dresserZ = placedBedZ + bNz * 2.15
1076
+ if (insideRoom(dresserX, dresserZ)) {
1077
+ addFurniture({
1078
+ levelId,
1079
+ kind: 'dresser-6drawer',
1080
+ x: dresserX,
1081
+ z: dresserZ,
1082
+ rotation: bFaceYaw,
1083
+ roomName: room.name,
1084
+ })
1085
+ }
1086
+ }
1087
+ if (includeHouseplants) {
1088
+ const px = refBedX + bTangX * (placedBedSpec.widthM / 2 + 1.05)
1089
+ const pz = refBedZ + bTangZ * (placedBedSpec.widthM / 2 + 1.05)
1090
+ if (insideRoom(px, pz)) {
1091
+ addPlant({
1092
+ levelId,
1093
+ kind: 'plant-snake-planter',
1094
+ x: px,
1095
+ z: pz,
1096
+ zoneName: room.name,
1097
+ isOutdoor: false,
1098
+ seed: 207 + idx * 13,
1099
+ })
1100
+ }
1101
+ }
1102
+ return
1103
+ }
1104
+
1105
+ if (room.kind === 'closet') {
1106
+ // Walk-in closets / pantries are NEVER furnished as bedrooms; large walk-in closets (>= 7.5 m²)
1107
+ // may receive a dressing bench or floor mirror if clear of doors & walls.
1108
+ if (includeInteriorFurniture && room.areaSqm >= 7.5 && Math.min(room.widthM, room.depthM) >= 2.0) {
1109
+ if (insideRoom(cx, cz)) {
1110
+ addFurniture({
1111
+ levelId,
1112
+ kind: 'bench-entryway',
1113
+ x: cx,
1114
+ z: cz,
1115
+ rotation: wallYaw,
1116
+ roomName: room.name,
1117
+ })
1118
+ }
1119
+ if (includeRugsAndDecor && anchor) {
1120
+ const mx = anchor.midX + anchor.inwardNx * 0.22
1121
+ const mz = anchor.midZ + anchor.inwardNz * 0.22
1122
+ if (insideRoom(mx, mz)) {
1123
+ addFurniture({
1124
+ levelId,
1125
+ kind: 'floor-mirror',
1126
+ x: mx,
1127
+ z: mz,
1128
+ rotation: anchor.yawRad,
1129
+ roomName: room.name,
1130
+ })
1131
+ }
1132
+ }
1133
+ }
1134
+ return
1135
+ }
1136
+
1137
+ if (room.kind === 'dining') {
1138
+ const useRound = room.areaSqm < 13
1139
+ const tableKind = useRound ? 'dining-table-round' : 'dining-table-rect'
1140
+ if (includeRugsAndDecor) {
1141
+ addFurniture({
1142
+ levelId,
1143
+ kind: useRound ? 'area-rug-round' : 'area-rug-rect',
1144
+ x: cx,
1145
+ z: cz,
1146
+ rotation: wallYaw,
1147
+ roomName: room.name,
1148
+ widthM: Math.max(0.8, Math.min(2.8, room.widthM * 0.72)),
1149
+ depthM: Math.max(0.8, Math.min(2.2, room.depthM * 0.68)),
1150
+ })
1151
+ }
1152
+ if (includeInteriorFurniture) {
1153
+ addFurniture({
1154
+ levelId,
1155
+ kind: tableKind,
1156
+ x: cx,
1157
+ z: cz,
1158
+ rotation: wallYaw,
1159
+ roomName: room.name,
1160
+ })
1161
+ const chairOffsets: Array<[number, number, number]> = useRound
1162
+ ? [
1163
+ [0, 0.92, Math.PI],
1164
+ [0, -0.92, 0],
1165
+ [0.92, 0, -Math.PI / 2],
1166
+ [-0.92, 0, Math.PI / 2],
1167
+ ]
1168
+ : [
1169
+ [-0.6, 0.78, Math.PI],
1170
+ [0, 0.78, Math.PI],
1171
+ [0.6, 0.78, Math.PI],
1172
+ [-0.6, -0.78, 0],
1173
+ [0, -0.78, 0],
1174
+ [0.6, -0.78, 0],
1175
+ ]
1176
+ const cosY = Math.cos(wallYaw)
1177
+ const sinY = Math.sin(wallYaw)
1178
+ for (const [lx, lz, localYaw] of chairOffsets) {
1179
+ const chX = cx + lx * cosY + lz * sinY
1180
+ const chZ = cz - lx * sinY + lz * cosY
1181
+ if (insideRoom(chX, chZ)) {
1182
+ addFurniture({
1183
+ levelId,
1184
+ kind: 'dining-chair',
1185
+ x: chX,
1186
+ z: chZ,
1187
+ rotation: wallYaw + localYaw,
1188
+ roomName: room.name,
1189
+ ignoreCollision: true,
1190
+ })
1191
+ }
1192
+ }
1193
+ const credX = anchorX + inNx * 0.32
1194
+ const credZ = anchorZ + inNz * 0.32
1195
+ if (insideRoom(credX, credZ) && Math.hypot(credX - cx, credZ - cz) > 1.45) {
1196
+ addFurniture({
1197
+ levelId,
1198
+ kind: 'credenza-sideboard',
1199
+ x: credX,
1200
+ z: credZ,
1201
+ rotation: wallYaw,
1202
+ roomName: room.name,
1203
+ })
1204
+ }
1205
+ }
1206
+ return
1207
+ }
1208
+
1209
+ if (room.kind === 'office') {
1210
+ const deskX = anchorX + inNx * 0.6
1211
+ const deskZ = anchorZ + inNz * 0.6
1212
+ let deskPlaced = false
1213
+ if (includeInteriorFurniture && insideRoom(deskX, deskZ)) {
1214
+ deskPlaced = addFurniture({
1215
+ levelId,
1216
+ kind: 'standing-desk',
1217
+ x: deskX,
1218
+ z: deskZ,
1219
+ rotation: wallYaw,
1220
+ roomName: room.name,
1221
+ })
1222
+ const chairX = deskX + inNx * 0.75
1223
+ const chairZ = deskZ + inNz * 0.75
1224
+ if (insideRoom(chairX, chairZ)) {
1225
+ addFurniture({
1226
+ levelId,
1227
+ kind: 'office-ergonomic-chair',
1228
+ x: chairX,
1229
+ z: chairZ,
1230
+ rotation: faceWallYaw,
1231
+ roomName: room.name,
1232
+ })
1233
+ }
1234
+ const shelfX = anchorX + inNx * 0.28 + tangX * 1.45
1235
+ const shelfZ = anchorZ + inNz * 0.28 + tangZ * 1.45
1236
+ if (insideRoom(shelfX, shelfZ)) {
1237
+ addFurniture({
1238
+ levelId,
1239
+ kind: 'bookshelf-tall',
1240
+ x: shelfX,
1241
+ z: shelfZ,
1242
+ rotation: wallYaw,
1243
+ roomName: room.name,
1244
+ })
1245
+ }
1246
+ }
1247
+ if (deskPlaced && includeElectronics && insideRoom(deskX, deskZ)) {
1248
+ addElectronics({
1249
+ levelId,
1250
+ kind: 'desktop-pc-dual-monitor',
1251
+ x: deskX,
1252
+ y: 0.75,
1253
+ z: deskZ,
1254
+ rotation: wallYaw,
1255
+ roomName: room.name,
1256
+ channelRole: 'workstation',
1257
+ screenState: 'code',
1258
+ })
1259
+ }
1260
+ if (includeHouseplants) {
1261
+ const px = anchorX + inNx * 0.5 - tangX * 1.25
1262
+ const pz = anchorZ + inNz * 0.5 - tangZ * 1.25
1263
+ if (insideRoom(px, pz)) {
1264
+ addPlant({
1265
+ levelId,
1266
+ kind: 'plant-monstera-potted',
1267
+ x: px,
1268
+ z: pz,
1269
+ zoneName: room.name,
1270
+ isOutdoor: false,
1271
+ seed: 311 + idx * 19,
1272
+ })
1273
+ }
1274
+ }
1275
+ return
1276
+ }
1277
+
1278
+ if (room.kind === 'entryway') {
1279
+ const conX = anchorX + inNx * 0.28
1280
+ const conZ = anchorZ + inNz * 0.28
1281
+ if (includeInteriorFurniture && insideRoom(conX, conZ)) {
1282
+ addFurniture({
1283
+ levelId,
1284
+ kind: 'console-table',
1285
+ x: conX,
1286
+ z: conZ,
1287
+ rotation: wallYaw,
1288
+ roomName: room.name,
1289
+ })
1290
+ }
1291
+ if (includeHouseplants) {
1292
+ const px = conX + tangX * 0.95
1293
+ const pz = conZ + tangZ * 0.95
1294
+ if (insideRoom(px, pz)) {
1295
+ addPlant({
1296
+ levelId,
1297
+ kind: 'plant-snake-planter',
1298
+ x: px,
1299
+ z: pz,
1300
+ zoneName: room.name,
1301
+ isOutdoor: false,
1302
+ seed: 409 + idx * 7,
1303
+ })
1304
+ }
1305
+ }
1306
+ return
1307
+ }
1308
+
1309
+ if (room.kind === 'patio') {
1310
+ if (includeInteriorFurniture) {
1311
+ const sofaX = cx
1312
+ const sofaZ = cz - 0.85
1313
+ if (insideRoom(sofaX, sofaZ)) {
1314
+ addFurniture({
1315
+ levelId,
1316
+ kind: 'patio-sofa-set',
1317
+ x: sofaX,
1318
+ z: sofaZ,
1319
+ rotation: 0,
1320
+ roomName: room.name,
1321
+ })
1322
+ }
1323
+ const fireX = cx
1324
+ const fireZ = cz + 0.55
1325
+ if (insideRoom(fireX, fireZ)) {
1326
+ addFurniture({
1327
+ levelId,
1328
+ kind: 'fire-pit-table',
1329
+ x: fireX,
1330
+ z: fireZ,
1331
+ rotation: 0,
1332
+ roomName: room.name,
1333
+ })
1334
+ }
1335
+ }
1336
+ if (includeExteriorLandscaping) {
1337
+ const troughX = cx + Math.min(1.6, room.widthM * 0.35)
1338
+ const troughZ = cz
1339
+ if (insideRoom(troughX, troughZ)) {
1340
+ addPlant({
1341
+ levelId,
1342
+ kind: 'plant-succulent-trough',
1343
+ x: troughX,
1344
+ z: troughZ,
1345
+ zoneName: room.name,
1346
+ isOutdoor: true,
1347
+ registerCollision: true,
1348
+ seed: 521 + idx * 11,
1349
+ })
1350
+ }
1351
+ }
1352
+ }
1353
+ }
1354
+
1355
+ for (let i = 0; i < anatomy.rooms.length; i++) {
1356
+ const beforeRoomCount = create.length
1357
+ stageRoom(anatomy.rooms[i]!, i)
1358
+ if (create.length > beforeRoomCount) roomsStaged += 1
1359
+ }
1360
+
1361
+ // 2. Exterior Site Landscaping (Foundation Bushes, Privacy Hedges, Ornamental & Shade Trees — ground level only)
1362
+ if (shouldStageExteriorLandscaping && anatomy.footprintBounds) {
1363
+ const b = anatomy.footprintBounds
1364
+ const spanX = Math.max(4, b.maxX - b.minX)
1365
+ const spanZ = Math.max(4, b.maxZ - b.minZ)
1366
+ const centerZ = (b.minZ + b.maxZ) / 2
1367
+
1368
+ const exteriorCanonicalWalls = compileBuildingAnatomy(nodes).getWalls(exteriorLevelId)
1369
+ const exteriorLevelWallAnalyses = anatomy.walls.filter((w) => !w.levelId || w.levelId === exteriorLevelId)
1370
+ const exteriorWallAnalyses = exteriorLevelWallAnalyses.length > 0 ? exteriorLevelWallAnalyses : anatomy.walls
1371
+
1372
+ const canPlaceExteriorLandscape = (x: number, z: number, kind: string): boolean => {
1373
+ if (findContainingRoom(x, z, anatomy.rooms)) return false
1374
+ if (exteriorCanonicalWalls.length > 0 && isPointEnclosedByWalls(x, z, exteriorCanonicalWalls)) return false
1375
+ const spec = getFurnishingSpec(kind)
1376
+ const minClear = spec?.minFoundationClearanceM ?? 0
1377
+ if (minClear > 0 && exteriorWallAnalyses.length > 0) {
1378
+ if (minDistanceToExteriorWallM(x, z, exteriorWallAnalyses) < minClear) return false
1379
+ }
1380
+ return true
1381
+ }
1382
+
1383
+ // Foundation bushes along front/south (maxZ + 1.05m) avoiding doors, detached buildings & foundation keepouts
1384
+ const bushStep = 2.1
1385
+ const bushCount = Math.min(8, Math.max(2, Math.floor(spanX / bushStep)))
1386
+ for (let i = 0; i < bushCount; i++) {
1387
+ const bx = b.minX + 0.9 + ((spanX - 1.8) * i) / Math.max(1, bushCount - 1)
1388
+ const bz = b.maxZ + 1.05
1389
+ const bushKind = i % 2 === 0 ? 'bush-boxwood-round' : 'bush-flowering-hydrangea'
1390
+ if (isDoorBlockedPoint(exteriorLevelId, bx, bz, 1.35)) continue
1391
+ if (!canPlaceExteriorLandscape(bx, bz, bushKind)) continue
1392
+ addPlant({
1393
+ levelId: exteriorLevelId,
1394
+ kind: bushKind,
1395
+ x: bx,
1396
+ z: bz,
1397
+ zoneName: 'Front Foundation Bed',
1398
+ isOutdoor: true,
1399
+ maturity: 'mature',
1400
+ seed: 701 + i * 29,
1401
+ })
1402
+ }
1403
+
1404
+ // Privacy hedge row along rear/north boundary (minZ - 2.5m)
1405
+ const hedgeCount = Math.min(5, Math.max(2, Math.floor(spanX / 2.6)))
1406
+ for (let i = 0; i < hedgeCount; i++) {
1407
+ const hx = b.minX + 1.2 + ((spanX - 2.4) * i) / Math.max(1, hedgeCount - 1)
1408
+ const hz = b.minZ - 2.5
1409
+ if (!canPlaceExteriorLandscape(hx, hz, 'bush-hedge-row')) continue
1410
+ addPlant({
1411
+ levelId: exteriorLevelId,
1412
+ kind: 'bush-hedge-row',
1413
+ x: hx,
1414
+ z: hz,
1415
+ rotation: 0,
1416
+ zoneName: 'Rear Privacy Border',
1417
+ isOutdoor: true,
1418
+ maturity: 'mature',
1419
+ seed: 811 + i * 31,
1420
+ })
1421
+ }
1422
+
1423
+ // Shade & ornamental trees positioned safely outside foundation clearance (>= minFoundationClearanceM)
1424
+ const treeCandidates: Array<{ kind: string; x: number; z: number; zone: string; seed: number }> = [
1425
+ { kind: 'tree-oak-deciduous', x: b.minX - 4.2, z: b.maxZ + 3.8, zone: 'Front Yard', seed: 901 },
1426
+ { kind: 'tree-maple-japanese', x: b.maxX + 2.4, z: b.maxZ + 2.6, zone: 'Front Accent', seed: 907 },
1427
+ { kind: 'tree-pine-evergreen', x: b.minX - 4.0, z: b.minZ - 4.0, zone: 'Rear Windbreak', seed: 919 },
1428
+ { kind: 'tree-cypress-columnar', x: b.maxX + 2.0, z: centerZ, zone: 'Side Screening', seed: 929 },
1429
+ { kind: 'tree-oak-deciduous', x: b.maxX + 4.4, z: b.minZ - 4.0, zone: 'Backyard Shade', seed: 941 },
1430
+ ]
1431
+ for (const tc of treeCandidates) {
1432
+ if (!canPlaceExteriorLandscape(tc.x, tc.z, tc.kind)) continue
1433
+ addPlant({
1434
+ levelId: exteriorLevelId,
1435
+ kind: tc.kind,
1436
+ x: tc.x,
1437
+ z: tc.z,
1438
+ zoneName: tc.zone,
1439
+ isOutdoor: true,
1440
+ maturity: 'mature',
1441
+ seed: tc.seed,
1442
+ })
1443
+ }
1444
+
1445
+ // Ornamental grasses flanking side yard
1446
+ const grassX = b.minX - 1.25
1447
+ const grassZ = centerZ
1448
+ if (spanZ >= 4 && canPlaceExteriorLandscape(grassX, grassZ, 'plant-ornamental-grass')) {
1449
+ addPlant({
1450
+ levelId: exteriorLevelId,
1451
+ kind: 'plant-ornamental-grass',
1452
+ x: grassX,
1453
+ z: grassZ,
1454
+ zoneName: 'Side Garden',
1455
+ isOutdoor: true,
1456
+ seed: 953,
1457
+ })
1458
+ }
1459
+ }
1460
+
1461
+ const totalPlaced = furnitureItems + electronicsItems + indoorPlants + outdoorPlants
1462
+ return {
1463
+ summary: `Staged ${roomsStaged} room(s) and exterior landscape (${palette.label}, ${season}): ${furnitureItems} furniture/decor, ${electronicsItems} TV/audio/computer, ${indoorPlants} indoor plants, ${outdoorPlants} outdoor trees & bushes (${totalPlaced} total).`,
1464
+ deleteIds,
1465
+ create,
1466
+ counts: {
1467
+ furnitureItems,
1468
+ electronicsItems,
1469
+ indoorPlants,
1470
+ outdoorPlants,
1471
+ roomsStaged,
1472
+ },
1473
+ }
1474
+ }