Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
59 changes: 59 additions & 0 deletions packages/viewer/src/lib/deferred-dispose.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { BufferGeometry } from 'three'

/**
* WebGPU dispose-race mitigation.
*
* Disposing a `BufferGeometry` that is *still referenced by a live, rendered
* mesh* synchronously inside a `useFrame` rebuild loop is unsafe on the
* WebGPU backend. Three's WebGPU renderer keeps a `RenderObject` that holds
* the geometry's attributes; `BufferGeometry.dispose()` synchronously fires
* the `dispose` event, and the renderer's handler later reads `.id` / `.count`
* off attributes that have already been freed by the time the render pass
* unwinds — throwing `Cannot read properties of undefined (reading 'id')`
* (Sentry MONOREPO-EDITOR-DK / EG / EH).
*
* The renderer releases its `RenderObject` for a geometry once that geometry
* is no longer drawn (i.e. after the frame in which we swapped in the new
* geometry). So instead of disposing the *outgoing* live geometry mid-frame,
* we hand it to this queue and flush it at the START of the next frame, after
* the render pass that dropped it has completed. Behavior is identical —
* every geometry is still freed, just one frame later, after the renderer has
* let go of it.
*
* This is deliberately module-global (not per-system): every geometry system
* shares one flush point, and the queue is drained wholesale each frame. Only
* use `queueGeometryDispose` for geometries that were attached to a *rendered*
* mesh. Transient CSG intermediates that never entered the scene graph should
* still be disposed synchronously — the renderer never held a RenderObject for
* them, so there is no race.
*/
const pendingGeometryDisposals = new Set<BufferGeometry>()

/**
* Queue a live geometry for disposal after the current render. Safe to call
* with the same geometry more than once (Set-deduped). The mesh should already
* have been detached / reassigned to a fresh geometry before calling this.
*/
export function queueGeometryDispose(geometry: BufferGeometry | null | undefined): void {
if (!geometry) return
if (typeof (geometry as { dispose?: () => void }).dispose !== 'function') return
pendingGeometryDisposals.add(geometry)
}

/**
* Dispose everything queued since the last flush. Call once at the top of a
* `useFrame` callback, before any rebuild work runs, so the renderer has had a
* full frame to release the outgoing geometries' RenderObjects.
*/
export function flushGeometryDisposals(): void {
if (pendingGeometryDisposals.size === 0) return
for (const geometry of pendingGeometryDisposals) {
try {
geometry.dispose()
} catch {
// A geometry may already be torn down (scene unload, HMR); freeing it
// twice is harmless and must never break the frame loop.
}
}
pendingGeometryDisposals.clear()
}
15 changes: 12 additions & 3 deletions packages/viewer/src/systems/geometry/geometry-system.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
} from '@pascal-app/core'
import { useFrame } from '@react-three/fiber'
import { useEffect, useRef } from 'react'
import { FrontSide, type Group, type Material, type Mesh } from 'three'
import { type BufferGeometry, FrontSide, type Group, type Material, type Mesh } from 'three'
import { flushGeometryDisposals, queueGeometryDispose } from '../../lib/deferred-dispose'
import {
type ColorPreset,
createSurfaceRoleMaterial,
Expand Down Expand Up @@ -105,6 +106,12 @@ export const GeometrySystem = () => {
}, [sceneMaterials])

useFrame(() => {
// Free any geometries queued for disposal on a previous frame. Doing this
// at the START of the frame (before rebuild) guarantees the WebGPU renderer
// has already released its RenderObject for the outgoing geometry, avoiding
// the mid-frame dispose race (Sentry MONOREPO-EDITOR-DK/EG/EH).
flushGeometryDisposals()

if (dirtyNodes.size === 0) return
const nodes = useScene.getState().nodes

Expand Down Expand Up @@ -308,8 +315,10 @@ function disposeChildren(group: Group) {
?.__fromGeometry
if (!fromGeometry) continue
group.remove(child)
const mesh = child as Partial<Mesh> & { geometry?: { dispose?: () => void } }
if (mesh.geometry?.dispose) mesh.geometry.dispose()
const mesh = child as Partial<Mesh> & { geometry?: BufferGeometry }
// Defer the outgoing geometry's dispose to the next frame — the WebGPU
// renderer still holds a RenderObject for it during this frame's render.
if (mesh.geometry) queueGeometryDispose(mesh.geometry)
if ('material' in mesh) {
const m = (mesh as { material: unknown }).material
if (Array.isArray(m)) {
Expand Down
19 changes: 15 additions & 4 deletions packages/viewer/src/systems/roof/roof-system.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { mergeGeometries, mergeVertices } from 'three/examples/jsm/utils/BufferG
import { ADDITION, Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg'
import { computeBoundsTree } from 'three-mesh-bvh'
import { ensureRenderableGeometryAttributes } from '../../lib/csg-utils'
import { flushGeometryDisposals, queueGeometryDispose } from '../../lib/deferred-dispose'

function csgGeometry(brush: Brush): THREE.BufferGeometry {
return brush.geometry as unknown as THREE.BufferGeometry
Expand Down Expand Up @@ -168,6 +169,12 @@ export const RoofSystem = () => {
useLiveNodeOverrides((s) => s.overrides)

useFrame(() => {
// Free geometries queued for disposal on a previous frame before doing any
// rebuild work. Flushing at frame start guarantees the WebGPU renderer has
// already released the RenderObject for each outgoing geometry, avoiding the
// mid-frame dispose race (Sentry MONOREPO-EDITOR-DK/EG/EH).
flushGeometryDisposals()
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated

// Clear stale pending updates when the scene is unloaded
if (rootNodeIds.length === 0) {
pendingRoofUpdates.clear()
Expand Down Expand Up @@ -240,7 +247,7 @@ export const RoofSystem = () => {
// while roofMaterials only has 4 entries. Three.js raycasts into invisible groups,
// so MeshBVH hits groups[4].materialIndex → undefined.side → crash.
if (mesh.geometry.type === 'BoxGeometry') {
mesh.geometry.dispose()
queueGeometryDispose(mesh.geometry)
mesh.geometry = createDegenerateRoofPlaceholder()
}
mesh.position.set(
Expand Down Expand Up @@ -305,7 +312,9 @@ function updateRoofSegmentGeometry(
) {
const newGeo = generateRoofSegmentGeometry(node, nodes)

mesh.geometry.dispose()
// Defer the outgoing live geometry's dispose — the WebGPU renderer still
// references it this frame (Sentry MONOREPO-EDITOR-DK/EG/EH).
queueGeometryDispose(mesh.geometry)
mesh.geometry = newGeo
computeGeometryBoundsTree(newGeo)

Expand Down Expand Up @@ -496,7 +505,8 @@ function updateMergedRoofGeometry(
.filter((n): n is RoofSegmentNode => n !== undefined && !hasSegmentMaterialOverride(n))

if (children.length === 0) {
mergedMesh.geometry.dispose()
// Defer the outgoing live geometry's dispose (Sentry MONOREPO-EDITOR-DK/EG/EH).
queueGeometryDispose(mergedMesh.geometry)
// Not BoxGeometry: its 6 groups against the merged mesh's 4-material array
// crash GLTFExporter (materials[4] → undefined) when the roof bakes.
mergedMesh.geometry = createDegenerateRoofPlaceholder()
Expand Down Expand Up @@ -612,7 +622,8 @@ function updateMergedRoofGeometry(

finalGeo.computeVertexNormals()
ensureRenderableGeometryAttributes(finalGeo)
mergedMesh.geometry.dispose()
// Defer the outgoing live geometry's dispose (Sentry MONOREPO-EDITOR-DK/EG/EH).
queueGeometryDispose(mergedMesh.geometry)
mergedMesh.geometry = finalGeo

finalWallTrimmed.geometry.dispose()
Expand Down
Loading