From 5c55f2c7f418e31f31ecdf0f08a98da2b266f72c Mon Sep 17 00:00:00 2001 From: Tom Boullay Date: Thu, 14 May 2026 00:15:23 +0200 Subject: [PATCH] feat: add disposeObject3D utility for GPU memory cleanup --- src/utils/three/dispose.ts | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/utils/three/dispose.ts diff --git a/src/utils/three/dispose.ts b/src/utils/three/dispose.ts new file mode 100644 index 0000000..3530c11 --- /dev/null +++ b/src/utils/three/dispose.ts @@ -0,0 +1,42 @@ +import * as THREE from "three"; + +export function disposeObject3D(object: THREE.Object3D): void { + object.traverse((child) => { + if (child instanceof THREE.Mesh) { + child.geometry?.dispose(); + + if (Array.isArray(child.material)) { + for (const material of child.material) { + disposeMaterial(material); + } + } else if (child.material) { + disposeMaterial(child.material); + } + } + }); +} + +function disposeMaterial(material: THREE.Material): void { + material.dispose(); + + for (const key of Object.keys(material)) { + const value = (material as Record)[key]; + if (value instanceof THREE.Texture) { + value.dispose(); + } + } +} + +export function disposeInstancedMesh(mesh: THREE.InstancedMesh): void { + mesh.geometry?.dispose(); + + if (Array.isArray(mesh.material)) { + for (const material of mesh.material) { + disposeMaterial(material); + } + } else if (mesh.material) { + disposeMaterial(mesh.material); + } + + mesh.dispose(); +}