Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions packages/core/src/agent-operations/move-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,25 +269,29 @@ function planOpeningMove(
: target.y === undefined
? node.position[1]
: target.y + node.height / 2
const { clampedX, clampedY, fits } =
// Fold transomHeight into cutout.height on purpose so clampDoorToWall slides the full opening instead of shrinking the transom.
const doorClamp =
node.type === 'door'
? clampDoorToWall(
wall,
rawX,
node.width,
node.height,
node,
cutout.height,
{ ...node, transomHeight: undefined },
nodes as Record<AnyNodeId, AnyNode>,
)
: clampWindowToWall(
wall,
rawX,
rawY,
node.width,
node.height,
nodes as Record<AnyNodeId, AnyNode>,
)
if (!fits) refuseOpeningAboveSlope(wall, nodes, node.type, node.width, node.height)
: null
const { clampedX, clampedY, fits } = doorClamp
? { clampedX: doorClamp.clampedX, clampedY: rawY, fits: doorClamp.fits }
: clampWindowToWall(
wall,
rawX,
rawY,
node.width,
node.height,
nodes as Record<AnyNodeId, AnyNode>,
)
if (!fits) refuseOpeningAboveSlope(wall, nodes, node.type, cutout.width, cutout.height)
// Checked where the clamp put the door: under a sloped top it may have slid to the high end.
if (node.type === 'door') {
const wallHeight =
Expand Down
41 changes: 41 additions & 0 deletions packages/core/src/building/wall-openings-slope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,45 @@ describe('agents refuse an opening no stretch of a sloped wall can take', () =>
expect(refusal(() => move(withOpening(sloped, door), 'door_slope'))).toBe('wall_too_low')
expect(refusal(() => move(withOpening({}, door), 'door_slope'))).toBeNull()
})

test('moving a door with a transom along a sloped wall slides until the full opening fits (#1252)', () => {
// 1 m at start rising to 3 m at x = 4 m: a 2.1 m door with a 0.4 m transom (2.5 m cutout)
// needs ceiling >= 2.5 m, which starts at x = 3.0 m (opening centre >= 3.45 m).
const rising = { height: 1, endHeightOffset: 2 }
const transomDoor = DoorNode.parse({
...door,
position: [2.6, 1.05, 0],
width: 0.9,
height: 2.1,
transomHeight: 0.4,
})
const moved = move(withOpening(rising, transomDoor), 'door_slope')
expect(moved.result.clamped).toBe(true)
expect(moved.result.position[0]).toBeCloseTo(3.45, 4)
expect(moved.result.position[1]).toBeCloseTo(1.05, 6)

// With sidelightLeft = 0.2 and transomHeight = 0.2 (1.1 m x 2.3 m cutout, leafOffsetX = +0.1 m):
// ceiling >= 2.3 m starts at x = 2.6 m, so cutout centre clamps to 3.15 m and leaf X lands at 3.25 m.
const sidelightTransomDoor = DoorNode.parse({
...door,
position: [2.6, 1.05, 0],
width: 0.9,
height: 2.1,
sidelightLeft: 0.2,
transomHeight: 0.2,
})
const movedSidelight = move(withOpening(rising, sidelightTransomDoor), 'door_slope')
expect(movedSidelight.result.clamped).toBe(true)
expect(movedSidelight.result.position[0]).toBeCloseTo(3.25, 4)
expect(movedSidelight.result.position[1]).toBeCloseTo(1.05, 6)

// Refused only when no stretch of the sloped wall clears door + transom (2.7 m cutout needs x >= 3.4 m, width 0.9 m needs 3.4 + 0.9 = 4.3 m > 4 m)
const tooTallTransom = DoorNode.parse({
...transomDoor,
transomHeight: 0.6,
})
expect(refusal(() => move(withOpening(rising, tooTallTransom), 'door_slope'))).toBe(
'wall_too_low',
)
})
})
203 changes: 203 additions & 0 deletions packages/editor/src/lib/glb-export-wall-t-junctions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { afterEach, describe, expect, test } from 'bun:test'
import {
type AnyNode,
BuildingNode,
LevelNode,
SiteNode,
sceneRegistry,
useScene,
WallNode,
WindowNode,
} from '@pascal-app/core'
import { runWallBuildFrame } from '@pascal-app/viewer'
import * as THREE from 'three'
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { prepareSceneForExport } from './glb-export'

function triangles(geometry: THREE.BufferGeometry): THREE.Vector3[][] {
const position = geometry.getAttribute('position')
const index = geometry.index
const count = index?.count ?? position.count
const out: THREE.Vector3[][] = []
for (let offset = 0; offset < count; offset += 3) {
out.push(
[0, 1, 2].map((corner) =>
new THREE.Vector3().fromBufferAttribute(
position,
index ? index.getX(offset + corner) : offset + corner,
),
),
)
}
return out
}

function countTJunctions(geometry: THREE.BufferGeometry): number {
const tris = triangles(geometry)
const vertices = tris.flat()
const line = new THREE.Line3()
const closest = new THREE.Vector3()
let count = 0
for (const tri of tris) {
for (let k = 0; k < 3; k += 1) {
line.set(tri[k]!, tri[(k + 1) % 3]!)
const length = line.distance()
if (length < 1e-4) continue
for (const vertex of vertices) {
const t = line.closestPointToPointParameter(vertex, false)
if (t * length < 1e-4 || (1 - t) * length < 1e-4) continue
line.at(t, closest)
if (closest.distanceTo(vertex) < 1e-6) count += 1
}
}
}
return count
}

function area(geometry: THREE.BufferGeometry): number {
return triangles(geometry).reduce(
(sum, [a, b, c]) => sum + new THREE.Triangle(a, b, c).getArea(),
0,
)
}

async function exportGlb(scene: THREE.Object3D): Promise<ArrayBuffer> {
const originalFileReader = globalThis.FileReader
class ExportFileReader {
result: ArrayBuffer | null = null
onloadend: (() => void) | null = null
readAsArrayBuffer(blob: Blob) {
void blob.arrayBuffer().then((buffer) => {
this.result = buffer
this.onloadend?.()
})
}
}
globalThis.FileReader = ExportFileReader as unknown as typeof FileReader
try {
return (await new GLTFExporter().parseAsync(scene, { binary: true })) as ArrayBuffer
} finally {
globalThis.FileReader = originalFileReader
}
}

async function parseGlb(buffer: ArrayBuffer): Promise<THREE.Group> {
const gltf = await new GLTFLoader().parseAsync(buffer, '')
return gltf.scene
}

afterEach(() => {
sceneRegistry.clear()
})

describe('deferred wall T-junction repair on export (#1273)', () => {
test('live walls stay deferred while exported GLB repairs T-junctions without touching the live mesh', async () => {
const previousScene = useScene.getState()
const level = LevelNode.parse({ id: 'level_tj', level: 0, parentId: 'building_tj' })
const windowNode = WindowNode.parse({
id: 'window_tj',
wallId: 'wall_tj_main',
parentId: 'wall_tj_main',
position: [2.5, 1.4, 0],
width: 1.2,
height: 1.2,
})
const mainWall = WallNode.parse({
id: 'wall_tj_main',
parentId: level.id,
children: [windowNode.id],
start: [0, 0],
end: [6, 0],
height: 2.6,
thickness: 0.2,
})
const crossWall = WallNode.parse({
id: 'wall_tj_cross',
parentId: level.id,
start: [3, 0],
end: [3, 4],
height: 2.6,
thickness: 0.2,
})
const building = BuildingNode.parse({
id: 'building_tj',
parentId: 'site_tj',
children: [level.id],
})
const site = SiteNode.parse({
id: 'site_tj',
children: [building.id],
})
const nodes: Record<string, AnyNode> = {
[site.id]: site,
[building.id]: building,
[level.id]: { ...level, children: [mainWall.id, crossWall.id] },
[mainWall.id]: mainWall,
[crossWall.id]: crossWall,
[windowNode.id]: windowNode,
}

const root = new THREE.Group()
const wallMaterial = [
new THREE.MeshStandardMaterial({ color: '#cccccc', name: 'base' }),
new THREE.MeshStandardMaterial({ color: '#dddddd', name: 'front' }),
new THREE.MeshStandardMaterial({ color: '#eeeeee', name: 'back' }),
]
const mainMesh = new THREE.Mesh(new THREE.BufferGeometry(), wallMaterial)
mainMesh.name = mainWall.id
const crossMesh = new THREE.Mesh(new THREE.BufferGeometry(), wallMaterial)
crossMesh.name = crossWall.id
root.add(mainMesh, crossMesh)
sceneRegistry.nodes.set(mainWall.id, mainMesh)
sceneRegistry.nodes.set(crossWall.id, crossMesh)

useScene.setState({
nodes: nodes as never,
dirtyNodes: new Set([mainWall.id, crossWall.id] as never),
})

let prepared: ReturnType<typeof prepareSceneForExport> | null = null
try {
runWallBuildFrame()

// Live wall mesh defers T-junction repair.
expect(mainMesh.geometry.userData.wallTJunctions).toBe('deferred')
const liveTJunctions = countTJunctions(mainMesh.geometry)
expect(liveTJunctions).toBeGreaterThan(0)
const liveArea = area(mainMesh.geometry)

// Export preparation repairs the cloned wall meshes without mutating the live mesh.
prepared = prepareSceneForExport(root, nodes, { onlyVisible: false })
expect(mainMesh.geometry.userData.wallTJunctions).toBe('deferred')
expect(countTJunctions(mainMesh.geometry)).toBe(liveTJunctions)

const exportedMain = prepared.scene.getObjectByName(mainWall.id) as THREE.Mesh
expect(exportedMain).toBeDefined()
expect(exportedMain.geometry.userData.wallTJunctions).toBeUndefined()
expect(countTJunctions(exportedMain.geometry)).toBe(0)
expect(area(exportedMain.geometry)).toBeCloseTo(liveArea, 5)
expect(exportedMain.geometry.getAttribute('normal')).toBeDefined()
expect(exportedMain.geometry.getAttribute('uv')).toBeDefined()
expect(exportedMain.geometry.getAttribute('uv2')).toBeDefined()

// Round-trip through GLTFExporter and GLTFLoader: exported GLB has 0 T-junctions.
const glb = await exportGlb(prepared.scene)
const loaded = await parseGlb(glb)
let loadedMeshCount = 0
loaded.traverse((obj) => {
if (obj instanceof THREE.Mesh && obj.geometry) {
loadedMeshCount += 1
expect(countTJunctions(obj.geometry)).toBe(0)
}
})
expect(loadedMeshCount).toBeGreaterThanOrEqual(2)
} finally {
prepared?.dispose()
mainMesh.geometry.dispose()
crossMesh.geometry.dispose()
for (const m of wallMaterial) m.dispose()
useScene.setState(previousScene)
}
})
})
23 changes: 23 additions & 0 deletions packages/editor/src/lib/glb-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
isViewerPresentationTextureBorrowed,
poseDoorMovingParts,
poseWindowMovingParts,
repairDeferredWallTJunctions,
restoreWindowRollerShutter,
SCENE_LAYER,
snapLevelsToTruePositions,
Expand Down Expand Up @@ -596,6 +597,27 @@ async function completeSceneExportPreparation(
}
}

function repairDeferredWallMeshesInScene(scene: THREE.Object3D): void {
const deferredWallMeshes: THREE.Mesh[] = []
const geometryRefCounts = new Map<THREE.BufferGeometry, number>()
scene.traverse((object) => {
const mesh = object as THREE.Mesh
if (mesh.isMesh !== true || !mesh.geometry) return
geometryRefCounts.set(mesh.geometry, (geometryRefCounts.get(mesh.geometry) ?? 0) + 1)
if (mesh.geometry.userData.wallTJunctions === 'deferred') {
deferredWallMeshes.push(mesh)
}
})
for (const mesh of deferredWallMeshes) {
const sharedCount = geometryRefCounts.get(mesh.geometry) ?? 1
if (sharedCount > 1) {
geometryRefCounts.set(mesh.geometry, sharedCount - 1)
mesh.geometry = mesh.geometry.clone()
}
repairDeferredWallTJunctions(mesh)
}
}

function finishSceneExportPreparation(preparation: SceneExportPreparation): GlbExport {
const { scene, cloneByOriginal, nodes, options, registryEntries } = preparation
const identityNodes = new Set<THREE.Object3D>()
Expand All @@ -605,6 +627,7 @@ function finishSceneExportPreparation(preparation: SceneExportPreparation): GlbE
}

const warnings = pruneNonRenderableMeshes(scene, identityNodes)
repairDeferredWallMeshesInScene(scene)
sanitizeMaterialGroups(scene, identityNodes)
convertMaterials(scene, options.textures ?? 'embed', options.purpose ?? 'viewer')

Expand Down
2 changes: 2 additions & 0 deletions packages/viewer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -589,10 +589,12 @@ export {
generateExtrudedWall,
getPendingWallRebuildCount,
isWallInitialBuildActive,
repairDeferredWallTJunctions,
runWallBuildFrame,
type WallGeometryAdapter,
type WallGeometryAdapterContext,
WallSystem,
type WallTJunctionMode,
} from './systems/wall/wall-system'
export {
advanceWindowAnimations,
Expand Down
Loading
Loading