-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathwall-system.tsx
More file actions
1567 lines (1398 loc) · 53 KB
/
Copy pathwall-system.tsx
File metadata and controls
1567 lines (1398 loc) · 53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type AnyNode,
type AnyNodeId,
DEFAULT_LEVEL_HEIGHT,
type DoorNode,
getAdjacentWallIds,
getEffectiveNode,
getWallBandSlotId,
getWallCurveFrameAt,
getWallFaceBandConfig,
getWallFaceBandForHeight,
getWallMiterBoundaryPoints,
getWallPlaneTop,
getWallPlanFootprint,
getWallSurfacePolygon,
getWallThickness,
isCurvedWall,
type Point2D,
pointToKey,
resolveLevelId,
resolveWallTop,
sceneRegistry,
spatialGridManager,
terrainSupportLift,
useLiveNodeOverrides,
useLiveTransforms,
useScene,
type WallMiterData,
type WallNode,
type WallSlabSupportSegment,
type WallSurfaceSide,
type WallSurfaceSlotId,
type WindowNode,
} from '@pascal-app/core'
import { useFrame } from '@react-three/fiber'
import { useEffect } from 'react'
import * as THREE from 'three'
import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'
import { ADDITION, Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg'
import { computeBoundsTree } from 'three-mesh-bvh'
import { ensureRenderableGeometryAttributes, prepareBrushForCSG } from '../../lib/csg-utils'
import { setGroupsSortedByMaterial } from '../../lib/geometry-groups'
import { timeSpan } from '../../lib/perf-tracks'
import { buildTerrainPerimeterFillGeometry } from '../../lib/terrain-perimeter-fill'
import { clearLevelMiterCache, getCachedLevelMiters } from './level-miter-cache'
import {
buildOpeningCutoutGeometry,
getOpeningCutoutBottomPadding,
} from './opening-cutout-geometry'
import {
drainStats,
endInitialBuild,
initiallyBuiltWalls,
isWallInitialBuildActive,
pendingAdjacentByLevel,
publishWallDrainStats,
} from './wall-build-lifecycle'
import { sweepUnbuiltWalls, WALL_PLACEHOLDER_SWEEP_INTERVAL } from './wall-placeholder-sweep'
import { notifyWallRebuilt } from './wall-rebuild-notifications'
export { isWallInitialBuildActive } from './wall-build-lifecycle'
export { drainRebuiltWalls } from './wall-rebuild-notifications'
// Reusable CSG evaluator for better performance
const csgEvaluator = new Evaluator()
csgEvaluator.attributes = ['position', 'normal', 'uv', 'uv2']
const CURVED_WALL_3D_ENDPOINT_INSET = 0.0015
const WALL_FACE_NORMAL_Y_EPSILON = 0.6
const WALL_FACE_EDGE_DISTANCE_EPSILON = 0.003
const WALL_BAND_SPLIT_EPSILON = 1e-5
const WALL_BAND_SLOT_MATERIAL_INDEX: Record<WallSurfaceSlotId, number> = {
interior: 1,
exterior: 2,
lowerInterior: 3,
middleInterior: 4,
upperInterior: 5,
topInterior: 6,
lowerExterior: 7,
middleExterior: 8,
upperExterior: 9,
topExterior: 10,
skirtingInterior: 0,
skirtingExterior: 0,
crownInterior: 0,
crownExterior: 0,
chairRailInterior: 0,
chairRailExterior: 0,
}
function computeGeometryBoundsTree(geometry: THREE.BufferGeometry) {
;(geometry as any).computeBoundsTree = computeBoundsTree
;(geometry as any).computeBoundsTree({ maxLeafSize: 10 })
}
function csgGeometry(brush: Brush): THREE.BufferGeometry {
return brush.geometry as unknown as THREE.BufferGeometry
}
function isBoxCutout(brush: Brush, bounds: THREE.Box3): boolean {
const geometry = csgGeometry(brush)
const positions = geometry.getAttribute('position')
if ((geometry.index?.count ?? positions.count) !== 36) return false
const vertex = new THREE.Vector3()
const corners = new Set<number>()
for (let index = 0; index < positions.count; index++) {
vertex.fromBufferAttribute(positions, index).applyMatrix4(brush.matrixWorld)
let corner = 0
for (const [bit, axis] of ['x', 'y', 'z'].entries()) {
const coordinate = axis as 'x' | 'y' | 'z'
if (Math.abs(vertex[coordinate] - bounds.min[coordinate]) <= 1e-6) continue
if (Math.abs(vertex[coordinate] - bounds.max[coordinate]) > 1e-6) return false
corner |= 1 << bit
}
corners.add(corner)
}
// A rotated box's AABB can contain another cutter without the solid doing so.
return corners.size === 8
}
export function mergeWallCutoutBrushes(brushes: readonly Brush[]): {
cutter: Brush | null
fallbackBrushes: Brush[]
droppedCount: number
} {
const cutouts = brushes.map((brush) => {
prepareBrushForCSG(brush)
const geometry = csgGeometry(brush)
geometry.computeBoundingBox()
const bounds = geometry.boundingBox!.clone().applyMatrix4(brush.matrixWorld)
return {
brush,
bounds,
containerBounds: bounds.clone().expandByScalar(1e-5),
isBox: isBoxCutout(brush, bounds),
}
})
const retained: typeof cutouts = []
for (const cutout of cutouts) {
if (cutout.isBox) {
if (
retained.some((other) => other.isBox && other.containerBounds.containsBox(cutout.bounds))
) {
continue
}
for (let index = retained.length - 1; index >= 0; index--) {
const other = retained[index]!
if (other.isBox && cutout.containerBounds.containsBox(other.bounds)) {
retained.splice(index, 1)
}
}
}
retained.push(cutout)
}
const droppedCount = cutouts.length - retained.length
const bounds = retained.map((cutout) => cutout.bounds.clone().expandByScalar(1e-6))
const parents = retained.map((_, index) => index)
const root = (index: number): number => {
while (parents[index] !== index) {
parents[index] = parents[parents[index]!]!
index = parents[index]!
}
return index
}
for (let a = 0; a < retained.length; a++) {
for (let b = a + 1; b < retained.length; b++) {
if (bounds[a]!.intersectsBox(bounds[b]!)) parents[root(b)] = root(a)
}
}
const groups = new Map<number, Brush[]>()
retained.forEach(({ brush }, index) => {
const key = root(index)
const group = groups.get(key) ?? []
group.push(brush)
groups.set(key, group)
})
const geometries: THREE.BufferGeometry[] = []
const intermediateGeometries = new Set<THREE.BufferGeometry>()
const fallbackBrushes: Brush[] = []
try {
for (const group of groups.values()) {
// Long unions of coplanar openings can grow explosively; subtract these directly.
if (group.length > 4) {
fallbackBrushes.push(...group)
continue
}
let result = group[0]!
for (let index = 1; index < group.length; index++) {
const next = csgEvaluator.evaluate(result, group[index]!, ADDITION)
intermediateGeometries.add(csgGeometry(next))
if (intermediateGeometries.delete(csgGeometry(result))) csgGeometry(result).dispose()
result = next
}
const source = csgGeometry(result)
const geometry = source.index ? source.toNonIndexed() : source.clone()
geometries.push(geometry)
geometry.applyMatrix4(result.matrixWorld)
for (const attribute of Object.keys(geometry.attributes)) {
if (!csgEvaluator.attributes.includes(attribute)) geometry.deleteAttribute(attribute)
}
}
if (geometries.length === 0) return { cutter: null, fallbackBrushes, droppedCount }
// CSG material indices are temporary: assignWallMaterialGroups classifies
// the final faces, including reveals, into the wall's semantic slots.
const merged = mergeGeometries(geometries, false)
if (!merged) throw new Error('Unable to merge wall cutout geometries')
const cutter = new Brush(merged)
prepareBrushForCSG(cutter)
return { cutter, fallbackBrushes, droppedCount }
} finally {
for (const geometry of geometries) geometry.dispose()
for (const geometry of intermediateGeometries) geometry.dispose()
}
}
type WallBoundaryEdgeTag = 'front' | 'back' | 'base'
type TaggedWallBoundaryEdge = {
start: THREE.Vector2
end: THREE.Vector2
tag: WallBoundaryEdgeTag
}
function insetCurvedWallBoundaryPointsFor3D(
wall: WallNode,
boundaryPoints: ReturnType<typeof getWallMiterBoundaryPoints>,
miterData: WallMiterData,
) {
if (!(boundaryPoints && isCurvedWall(wall))) {
return boundaryPoints
}
const insetDistance = Math.min(
CURVED_WALL_3D_ENDPOINT_INSET,
Math.max((wall.thickness ?? 0.1) * 0.01, 0.0005),
)
if (insetDistance <= 0) {
return boundaryPoints
}
const next = { ...boundaryPoints }
const startJunction = miterData.junctions.get(pointToKey({ x: wall.start[0], y: wall.start[1] }))
const endJunction = miterData.junctions.get(pointToKey({ x: wall.end[0], y: wall.end[1] }))
if (startJunction && startJunction.connectedWalls.length > 1) {
const frame = getWallCurveFrameAt(wall, 0)
next.startLeft = {
x: next.startLeft.x + frame.tangent.x * insetDistance,
y: next.startLeft.y + frame.tangent.y * insetDistance,
}
next.startRight = {
x: next.startRight.x + frame.tangent.x * insetDistance,
y: next.startRight.y + frame.tangent.y * insetDistance,
}
}
if (endJunction && endJunction.connectedWalls.length > 1) {
const frame = getWallCurveFrameAt(wall, 1)
next.endLeft = {
x: next.endLeft.x - frame.tangent.x * insetDistance,
y: next.endLeft.y - frame.tangent.y * insetDistance,
}
next.endRight = {
x: next.endRight.x - frame.tangent.x * insetDistance,
y: next.endRight.y - frame.tangent.y * insetDistance,
}
}
return next
}
function addTaggedWallBoundaryEdge(
edges: TaggedWallBoundaryEdge[],
points: { x: number; z: number }[],
startIndex: number,
endIndex: number,
tag: WallBoundaryEdgeTag,
) {
const start = points[startIndex]
const end = points[endIndex]
if (!(start && end)) return
if (Math.hypot(end.x - start.x, end.z - start.z) < 1e-6) return
edges.push({
start: new THREE.Vector2(start.x, start.z),
end: new THREE.Vector2(end.x, end.z),
tag,
})
}
function buildTaggedWallBoundaryEdges(
wall: WallNode,
localPoints: { x: number; z: number }[],
miterData: WallMiterData,
): TaggedWallBoundaryEdge[] {
if (localPoints.length < 2) return []
const edges: TaggedWallBoundaryEdge[] = []
if (isCurvedWall(wall)) {
const sidePointCount = Math.floor(localPoints.length / 2)
if (sidePointCount < 2) return edges
for (let index = 0; index < sidePointCount - 1; index += 1) {
addTaggedWallBoundaryEdge(edges, localPoints, index, index + 1, 'back')
}
addTaggedWallBoundaryEdge(edges, localPoints, sidePointCount - 1, sidePointCount, 'base')
for (let index = sidePointCount; index < localPoints.length - 1; index += 1) {
addTaggedWallBoundaryEdge(edges, localPoints, index, index + 1, 'front')
}
addTaggedWallBoundaryEdge(edges, localPoints, localPoints.length - 1, 0, 'base')
return edges
}
const startKey = pointToKey({ x: wall.start[0], y: wall.start[1] })
const startJunction = miterData.junctionData.get(startKey)?.get(wall.id)
const startLeftIndex = startJunction ? localPoints.length - 2 : localPoints.length - 1
const endLeftIndex = startJunction ? localPoints.length - 3 : localPoints.length - 2
addTaggedWallBoundaryEdge(edges, localPoints, 0, 1, 'back')
for (let index = 1; index < endLeftIndex; index += 1) {
addTaggedWallBoundaryEdge(edges, localPoints, index, index + 1, 'base')
}
addTaggedWallBoundaryEdge(edges, localPoints, endLeftIndex, startLeftIndex, 'front')
for (let index = startLeftIndex; index < localPoints.length - 1; index += 1) {
addTaggedWallBoundaryEdge(edges, localPoints, index, index + 1, 'base')
}
addTaggedWallBoundaryEdge(edges, localPoints, localPoints.length - 1, 0, 'base')
return edges
}
function distanceToWallBoundaryEdge(point: THREE.Vector2, edge: TaggedWallBoundaryEdge): number {
const edgeDx = edge.end.x - edge.start.x
const edgeDz = edge.end.y - edge.start.y
const pointDx = point.x - edge.start.x
const pointDz = point.y - edge.start.y
const edgeLengthSq = edgeDx * edgeDx + edgeDz * edgeDz
if (edgeLengthSq < 1e-12) {
return point.distanceTo(edge.start)
}
const t = THREE.MathUtils.clamp((pointDx * edgeDx + pointDz * edgeDz) / edgeLengthSq, 0, 1)
const closestX = edge.start.x + edgeDx * t
const closestZ = edge.start.y + edgeDz * t
return Math.hypot(point.x - closestX, point.y - closestZ)
}
function getWallFaceMaterialIndex(
wall: Pick<WallNode, 'frontSide' | 'backSide' | 'height' | 'faceBands'>,
face: 'front' | 'back',
y: number,
effectiveWallHeight: number,
): number {
const semantic = face === 'front' ? wall.frontSide : wall.backSide
const fallback: WallSurfaceSide = face === 'front' ? 'interior' : 'exterior'
const side = semantic === 'interior' || semantic === 'exterior' ? semantic : fallback
const bands = getWallFaceBandConfig(wall, effectiveWallHeight)
if (!bands.enabled) return WALL_BAND_SLOT_MATERIAL_INDEX[side]
const band = getWallFaceBandForHeight(wall, y, effectiveWallHeight)
return WALL_BAND_SLOT_MATERIAL_INDEX[getWallBandSlotId(side, band)]
}
function assignWallMaterialGroups(
geometry: THREE.BufferGeometry,
wall: WallNode,
boundaryEdges: TaggedWallBoundaryEdge[],
effectiveWallHeight: number,
) {
const position = geometry.getAttribute('position')
if (!position) return
const index = geometry.getIndex()
const triangleCount = index ? Math.floor(index.count / 3) : Math.floor(position.count / 3)
if (triangleCount === 0) {
geometry.clearGroups()
return
}
const triangleMaterials = new Array<number>(triangleCount).fill(0)
const a = new THREE.Vector3()
const b = new THREE.Vector3()
const c = new THREE.Vector3()
const ab = new THREE.Vector3()
const ac = new THREE.Vector3()
const normal = new THREE.Vector3()
const centroid = new THREE.Vector3()
const projectedCentroid = new THREE.Vector2()
const maxBoundaryDistance = Math.max(
getWallThickness(wall) * 0.02,
WALL_FACE_EDGE_DISTANCE_EPSILON,
)
for (let triangleIndex = 0; triangleIndex < triangleCount; triangleIndex += 1) {
const baseIndex = triangleIndex * 3
const ia = index ? index.getX(baseIndex) : baseIndex
const ib = index ? index.getX(baseIndex + 1) : baseIndex + 1
const ic = index ? index.getX(baseIndex + 2) : baseIndex + 2
a.fromBufferAttribute(position, ia)
b.fromBufferAttribute(position, ib)
c.fromBufferAttribute(position, ic)
ab.subVectors(b, a)
ac.subVectors(c, a)
normal.crossVectors(ab, ac)
if (normal.lengthSq() < 1e-12) {
triangleMaterials[triangleIndex] = 0
continue
}
normal.normalize()
if (Math.abs(normal.y) >= WALL_FACE_NORMAL_Y_EPSILON) {
triangleMaterials[triangleIndex] = 0
continue
}
centroid
.copy(a)
.add(b)
.add(c)
.multiplyScalar(1 / 3)
projectedCentroid.set(centroid.x, centroid.z)
let nearestTag: WallBoundaryEdgeTag | null = null
let nearestDistance = Number.POSITIVE_INFINITY
for (const edge of boundaryEdges) {
const distance = distanceToWallBoundaryEdge(projectedCentroid, edge)
if (distance < nearestDistance) {
nearestDistance = distance
nearestTag = edge.tag
}
}
if (!nearestTag || nearestDistance > maxBoundaryDistance) {
triangleMaterials[triangleIndex] = 0
continue
}
if (nearestTag === 'base') {
triangleMaterials[triangleIndex] = 0
continue
}
triangleMaterials[triangleIndex] = getWallFaceMaterialIndex(
wall,
nearestTag,
centroid.y,
effectiveWallHeight,
)
}
setGroupsSortedByMaterial(geometry, triangleMaterials)
}
type SplitVertex = {
x: number
y: number
z: number
}
function interpolateSplitVertex(a: SplitVertex, b: SplitVertex, t: number): SplitVertex {
return {
x: a.x + (b.x - a.x) * t,
y: a.y + (b.y - a.y) * t,
z: a.z + (b.z - a.z) * t,
}
}
function clipPolygonByY(polygon: SplitVertex[], planeY: number, keepBelow: boolean): SplitVertex[] {
const out: SplitVertex[] = []
if (polygon.length === 0) return out
const isInside = (vertex: SplitVertex) =>
keepBelow
? vertex.y <= planeY + WALL_BAND_SPLIT_EPSILON
: vertex.y >= planeY - WALL_BAND_SPLIT_EPSILON
for (let index = 0; index < polygon.length; index += 1) {
const current = polygon[index]!
const previous = polygon[(index + polygon.length - 1) % polygon.length]!
const currentInside = isInside(current)
const previousInside = isInside(previous)
if (currentInside !== previousInside) {
const denom = current.y - previous.y
if (Math.abs(denom) > WALL_BAND_SPLIT_EPSILON) {
out.push(interpolateSplitVertex(previous, current, (planeY - previous.y) / denom))
}
}
if (currentInside) out.push(current)
}
return out
}
function triangulateSplitPolygon(polygon: SplitVertex[], positions: number[]) {
if (polygon.length < 3) return
const first = polygon[0]!
for (let index = 1; index < polygon.length - 1; index += 1) {
const b = polygon[index]!
const c = polygon[index + 1]!
positions.push(first.x, first.y, first.z, b.x, b.y, b.z, c.x, c.y, c.z)
}
}
function splitGeometryAtHorizontalPlanes(
geometry: THREE.BufferGeometry,
planes: number[],
): THREE.BufferGeometry {
const splitPlanes = Array.from(
new Set(
planes
.filter((plane) => Number.isFinite(plane) && plane > WALL_BAND_SPLIT_EPSILON)
.map((plane) => Math.round(plane / WALL_BAND_SPLIT_EPSILON) * WALL_BAND_SPLIT_EPSILON),
),
).sort((a, b) => a - b)
if (splitPlanes.length === 0) return geometry
const source = geometry.index ? geometry.toNonIndexed() : geometry
const position = source.getAttribute('position')
if (!position || position.count === 0) return source
const positions: number[] = []
for (let index = 0; index < position.count; index += 3) {
let polygons: SplitVertex[][] = [
[
{ x: position.getX(index), y: position.getY(index), z: position.getZ(index) },
{ x: position.getX(index + 1), y: position.getY(index + 1), z: position.getZ(index + 1) },
{ x: position.getX(index + 2), y: position.getY(index + 2), z: position.getZ(index + 2) },
],
]
for (const plane of splitPlanes) {
const next: SplitVertex[][] = []
for (const polygon of polygons) {
const minY = Math.min(...polygon.map((vertex) => vertex.y))
const maxY = Math.max(...polygon.map((vertex) => vertex.y))
if (plane <= minY + WALL_BAND_SPLIT_EPSILON || plane >= maxY - WALL_BAND_SPLIT_EPSILON) {
next.push(polygon)
continue
}
const below = clipPolygonByY(polygon, plane, true)
const above = clipPolygonByY(polygon, plane, false)
if (below.length >= 3) next.push(below)
if (above.length >= 3) next.push(above)
}
polygons = next
}
for (const polygon of polygons) triangulateSplitPolygon(polygon, positions)
}
if (source !== geometry) geometry.dispose()
source.dispose()
const split = new THREE.BufferGeometry()
split.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3))
split.computeVertexNormals()
return split
}
function getWallBandSplitPlanes(wall: WallNode, effectiveWallHeight: number): number[] {
const bands = getWallFaceBandConfig(wall, effectiveWallHeight)
if (!bands.enabled) return []
const planes = [bands.lowerTop]
if (bands.count >= 3) planes.push(bands.middleTop)
if (bands.count >= 4) planes.push(bands.upperTop)
return planes.filter(
(plane) =>
plane > WALL_BAND_SPLIT_EPSILON && plane < effectiveWallHeight - WALL_BAND_SPLIT_EPSILON,
)
}
// ============================================================================
// WALL SYSTEM
// ============================================================================
let useFrameNb = 0
// ─── Drag-throttle state (singleton — one WallSystem mounted globally) ──
//
// Endpoint drags fire `markDirty(wallId)` on every pointermove tick. Without
// throttling, each tick rebuilds the dragged wall (~1 CSG + miter pass) AND
// every adjacent wall sharing a corner (3–4× in a t-junction or room).
// Visible as drag lag, especially on walls with door/window cutouts.
//
// Strategy: rebuild the dragged wall every tick (so the drag follows the
// cursor with full fidelity), but defer adjacent rebuilds to a trailing-
// edge flush DRAG_FLUSH_MS after the dirty stream stops. Visually, neighbor
// corners stay at their pre-drag miter until release, then snap into place
// within ~80ms. Standard CAD-app behavior. Speeds up t-junction drags ~3×,
// 4-corner-room drags ~4×.
const DRAG_FLUSH_MS = 80
const MAX_WALL_REBUILDS_PER_FRAME = 8
const WALL_PROGRESSIVE_DIRTY_THRESHOLD = MAX_WALL_REBUILDS_PER_FRAME
const WALL_PROGRESSIVE_TIME_BUDGET_MS = 8
// Initial build (see wall-build-lifecycle) has no interactive gesture to protect:
// the frame is dominated by rendering the still-unbatched scene, so every extra
// frame spent draining walls costs a full scene render. Three display frames of
// wall work per frame drains a 1,600-wall scene in ~1/6 of the frames while every
// frame stays two orders of magnitude under a perceptible freeze.
const WALL_INITIAL_BUILD_TIME_BUDGET_MS = 48
const HEAVY_WALL_OPENINGS = 6
let lastWallDirtyAtMs = 0
let unmountedFrames = 0
let stalledHydrationToken: object | null = null
function wallRebuildExitReason(
wallId: string,
nodes: Record<AnyNodeId, AnyNode>,
rebuiltThisFrame: number,
elapsedMs: number,
initialBuild = false,
): 'cap' | 'budget' | 'heavy' | null {
if (!initialBuild && rebuiltThisFrame >= MAX_WALL_REBUILDS_PER_FRAME) return 'cap'
if (rebuiltThisFrame === 0) return null
const budgetMs = initialBuild
? WALL_INITIAL_BUILD_TIME_BUDGET_MS
: WALL_PROGRESSIVE_TIME_BUDGET_MS
if (elapsedMs >= budgetMs) return 'budget'
const wall = nodes[wallId as AnyNodeId]
if (wall?.type !== 'wall') return null
let cutouts = 0
for (const childId of getEffectiveWall(wall).children ?? []) {
const child = nodes[childId]
if (
child?.type === 'door' ||
child?.type === 'window' ||
(child?.type === 'item' &&
(
sceneRegistry.nodes.get(childId)?.getObjectByName('cutout') as THREE.Mesh | undefined
)?.geometry?.getAttribute('position')?.count)
) {
cutouts++
if (cutouts >= HEAVY_WALL_OPENINGS) return 'heavy'
}
}
return null
}
export function shouldDeferWallRebuild(
wallId: string,
nodes: Record<AnyNodeId, AnyNode>,
rebuiltThisFrame: number,
elapsedMs: number,
initialBuild = false,
): boolean {
return wallRebuildExitReason(wallId, nodes, rebuiltThisFrame, elapsedMs, initialBuild) !== null
}
/** Rebuilds this system still owes — neighbours deferred during a drag. */
export function getPendingWallRebuildCount(): number {
return drainStats.pendingNeighbours
}
let placeholderSweepCountdown = WALL_PLACEHOLDER_SWEEP_INTERVAL
export const WallSystem = () => {
useScene((state) => state.dirtyNodes)
useLiveNodeOverrides((s) => s.overrides)
useEffect(() => () => clearLevelMiterCache(), [])
useFrame(runWallBuildFrame, 4)
return null
}
export function runWallBuildFrame() {
const initialBuild = isWallInitialBuildActive()
const token = useScene.getState().hydrationToken
if (token !== stalledHydrationToken) {
unmountedFrames = 0
stalledHydrationToken = token
}
drainStats.wallsConsumedThisFrame = 0
try {
consumeWallBuildFrame(initialBuild)
} finally {
publishWallDrainStats()
}
}
function consumeWallBuildFrame(initialBuild: boolean) {
const clearDirty = useScene.getState().clearDirty
// Self-heal: any registered wall still on its mount-time placeholder
// geometry with NO dirty mark gets re-marked, so a lost mark (system
// mounted late, suspense remount, mark consumed elsewhere) can never
// strand a wall as a degenerate point forever (QA f2 probe5/probe6 —
// scene loaded with the X-ray active never built any of its 24 walls).
placeholderSweepCountdown -= 1
if (placeholderSweepCountdown <= 0) {
placeholderSweepCountdown = WALL_PLACEHOLDER_SWEEP_INTERVAL
const sceneState = useScene.getState()
sweepUnbuiltWalls({
wallIds: sceneRegistry.byType.wall ?? [],
geometryOf: (wallId) =>
(sceneRegistry.nodes.get(wallId) as THREE.Mesh | undefined)?.geometry ?? null,
isDirty: (wallId) => sceneState.dirtyNodes.has(wallId as AnyNodeId),
markDirty: (wallId) => sceneState.markDirty(wallId as AnyNodeId),
})
}
const dirtyNodes = useScene.getState().dirtyNodes
const hasDirty = dirtyNodes.size > 0
const hasPending = pendingAdjacentByLevel.size > 0
if (!hasDirty && !hasPending) {
endInitialBuild()
return
}
const nodes = useScene.getState().nodes
const now = performance.now()
// Collect dirty walls and their levels
const dirtyWallsByLevel = new Map<string, Set<string>>()
let dirtyWallCount = 0
let unmountedWallCount = 0
useFrameNb += 1
if (hasDirty) {
dirtyNodes.forEach((id) => {
const node = nodes[id]
if (node?.type !== 'wall') return
dirtyWallCount += 1
if (!sceneRegistry.nodes.has(id)) unmountedWallCount++
const levelId = node.parentId
if (!levelId) return
if (!dirtyWallsByLevel.has(levelId)) {
dirtyWallsByLevel.set(levelId, new Set())
}
dirtyWallsByLevel.get(levelId)?.add(id)
})
}
const hasDirtyWalls = dirtyWallCount > unmountedWallCount
if (hasDirtyWalls) {
lastWallDirtyAtMs = now
}
const useProgressiveWallRebuilds =
initialBuild || dirtyWallCount > WALL_PROGRESSIVE_DIRTY_THRESHOLD
let rebuiltWallsThisFrame = 0
const rebuildFrameStartedAt = now
let deferWallRebuilds = false
let exitReason: 'cap' | 'budget' | 'heavy' | null = null
// Process each level that has dirty walls
for (const [levelId, dirtyWallIds] of dirtyWallsByLevel) {
if (
!initialBuild &&
useProgressiveWallRebuilds &&
rebuiltWallsThisFrame >= MAX_WALL_REBUILDS_PER_FRAME
) {
exitReason = 'cap'
break
}
const levelWalls = getLevelWalls(levelId)
const miterData = timeSpan('wall-miter', () => getCachedLevelMiters(levelId, levelWalls))
const rebuiltWallIds = new Set<string>()
// Update dirty walls — always, no throttling. The dragged wall must
// follow the cursor with full fidelity (cutouts and all). Large imports
// enter the progressive path so initial load can't lock the tab.
for (const wallId of dirtyWallIds) {
exitReason = useProgressiveWallRebuilds
? wallRebuildExitReason(
wallId,
nodes,
rebuiltWallsThisFrame,
performance.now() - rebuildFrameStartedAt,
initialBuild,
)
: null
if (exitReason) {
deferWallRebuilds = true
break
}
const mesh = sceneRegistry.nodes.get(wallId) as THREE.Mesh
if (mesh) {
timeSpan('wall-rebuild', () => updateWallGeometry(wallId, miterData), {
properties: [['node', wallId]],
})
clearDirty(wallId as AnyNodeId)
notifyWallRebuilt(wallId)
const firstBuild = !initiallyBuiltWalls.has(wallId)
if (firstBuild) {
initiallyBuiltWalls.add(wallId)
drainStats.firstBuilds++
} else {
drainStats.reinvalidationBuilds++
}
if (!initialBuild || !firstBuild) rebuiltWallIds.add(wallId)
rebuiltWallsThisFrame += 1
drainStats.wallsConsumedThisFrame++
if (initialBuild && wallRebuildExitReason(wallId, nodes, 1, 0, true) === 'heavy') {
exitReason = 'heavy'
deferWallRebuilds = true
break
}
}
// If mesh not found, keep it dirty for next frame
}
if (rebuiltWallIds.size === 0) {
if (deferWallRebuilds) break
continue
}
// First builds use the same hydrated inputs as every queued neighbour.
// Only subsequent invalidations need the adjacency scan and trailing flush.
// Adjacent walls sharing junctions — *defer* during active drag
// (dirty arrived this frame), flush on the trailing edge.
const adjacentWallIds = getAdjacentWallIds(levelWalls, rebuiltWallIds)
let pending = pendingAdjacentByLevel.get(levelId)
if (!pending) {
pending = new Set()
pendingAdjacentByLevel.set(levelId, pending)
}
for (const wallId of adjacentWallIds) {
if (!dirtyWallIds.has(wallId) && !pending.has(wallId)) {
pending.add(wallId)
drainStats.pendingNeighbours++
drainStats.neighbourEnqueues++
}
}
if (pending.size === 0) pendingAdjacentByLevel.delete(levelId)
if (deferWallRebuilds) break
}
// Trailing-edge flush: if no new dirty marks for DRAG_FLUSH_MS, the
// drag has ended — rebuild the queued neighbors so corners snap into
// their correct miter joins.
const quiet = !hasDirtyWalls && now - lastWallDirtyAtMs >= DRAG_FLUSH_MS
if (quiet && pendingAdjacentByLevel.size > 0) {
const pendingCount = getPendingWallRebuildCount()
const useProgressiveAdjacentRebuilds =
initialBuild || pendingCount > WALL_PROGRESSIVE_DIRTY_THRESHOLD
let rebuiltAdjacentThisFrame = 0
const adjacentFrameStartedAt = performance.now()
let deferAdjacentRebuilds = false
for (const [levelId, pendingIds] of pendingAdjacentByLevel) {
if (pendingIds.size === 0) continue
const levelWalls = getLevelWalls(levelId)
const miterData = timeSpan('wall-miter', () => getCachedLevelMiters(levelId, levelWalls))
for (const wallId of Array.from(pendingIds)) {
exitReason = useProgressiveAdjacentRebuilds
? wallRebuildExitReason(
wallId,
nodes,
rebuiltAdjacentThisFrame,
performance.now() - adjacentFrameStartedAt,
initialBuild,
)
: null
if (exitReason) {
deferAdjacentRebuilds = true
break
}
const mesh = sceneRegistry.nodes.get(wallId) as THREE.Mesh
if (mesh) {
timeSpan('wall-rebuild', () => updateWallGeometry(wallId, miterData), {
properties: [['node', wallId]],
})
notifyWallRebuilt(wallId)
drainStats.wallsConsumedThisFrame++
if (initiallyBuiltWalls.has(wallId)) drainStats.reinvalidationBuilds++
else {
initiallyBuiltWalls.add(wallId)
drainStats.firstBuilds++
}
}
pendingIds.delete(wallId)
drainStats.pendingNeighbours--
rebuiltAdjacentThisFrame += 1
if (initialBuild && wallRebuildExitReason(wallId, nodes, 1, 0, true) === 'heavy') {
exitReason = 'heavy'
deferAdjacentRebuilds = true
break
}
}
if (pendingIds.size === 0) {
pendingAdjacentByLevel.delete(levelId)
}
if (
deferAdjacentRebuilds ||
(!initialBuild &&
useProgressiveAdjacentRebuilds &&
rebuiltAdjacentThisFrame >= MAX_WALL_REBUILDS_PER_FRAME)
) {
break
}
}
}
if (initialBuild && drainStats.wallsConsumedThisFrame === 0 && unmountedWallCount > 0) {
unmountedFrames++
if (unmountedFrames >= WALL_PLACEHOLDER_SWEEP_INTERVAL) {
useScene.getState().invalidateHydration()
}
} else unmountedFrames = 0
if (exitReason === 'budget') drainStats.budgetExits++
else if (exitReason === 'heavy') drainStats.heavyExits++
else if (exitReason === 'cap') drainStats.capExits++
if (dirtyWallCount === rebuiltWallsThisFrame && drainStats.pendingNeighbours === 0) {
if (drainStats.wallsConsumedThisFrame > 0 || drainStats.initialBuildActive)
drainStats.drainedExits++
endInitialBuild()
}
}
/**
* Merge any live override for a wall into the scene record. Lets the
* 2D move handler publish `{ start, end, curveOffset }` to
* `useLiveNodeOverrides` and have the geometry / miter pipeline use
* those values without zustand churn during the drag. When no
* override is set, the wall is returned unchanged.
*/
function getEffectiveWall(wall: WallNode): WallNode {
const override = useLiveNodeOverrides.getState().get(wall.id)
if (!override || Object.keys(override).length === 0) return wall
return { ...wall, ...override } as WallNode
}
/**
* Gets all walls that belong to a level, with any live overrides
* merged in so miters compute against the cursor-driven positions
* (not the pre-drag scene state).
*/
function getLevelWalls(levelId: string): WallNode[] {
const { nodes } = useScene.getState()
const level = nodes[levelId as AnyNodeId]
if (level?.type !== 'level') return []
const walls: WallNode[] = []
for (const childId of level.children) {
const child = nodes[childId]
if (child?.type === 'wall') {
walls.push(getEffectiveWall(child as WallNode))
}
}
return walls
}
/**
* Updates the geometry for a single wall. Reads the effective node
* (override-merged) so a 2D drag visibly moves the 3D mesh without
* having touched `useScene` mid-drag.
*/
function updateWallGeometry(wallId: string, miterData: WallMiterData) {
const nodes = useScene.getState().nodes
const sceneNode = nodes[wallId as WallNode['id']]
if (sceneNode?.type !== 'wall') return
const node = getEffectiveWall(sceneNode as WallNode)
const mesh = sceneRegistry.nodes.get(wallId) as THREE.Mesh
if (!mesh) return
const levelId = resolveLevelId(node, nodes)
// Covering-clamped plane: a flush/thick slab on the level above shortens
// the plane-bound walls below it (explicit-height walls ignore the value).
const planeTop = getWallPlaneTop(node, levelId, nodes)
const slabSupport = spatialGridManager.getSlabSupportForWall(
levelId,
node.start,
node.end,
node.curveOffset ?? 0,
node.thickness,
node.supportSlabId,
undefined,
node.supportOffset,
)
const slabElevation = slabSupport.elevation
const terrainBottomAt = node.fillToTerrain
? (x: number, z: number) => terrainSupportLift(nodes, levelId, x, z)