Files
blitzkit/packages/website/src/hooks/useDispose.ts
T

63 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-05-12 18:08:02 -05:00
import { useLoader, type ObjectMap } from "@react-three/fiber";
2026-05-12 17:54:50 -05:00
import { useEffect } from "react";
2026-05-12 18:08:02 -05:00
import { Cache, Group, Mesh, MeshStandardMaterial, Object3D } from "three";
import { GLTFLoader, type GLTF } from "three-stdlib";
2026-05-12 17:54:50 -05:00
const users: Record<string, number> = {};
2026-05-12 18:08:02 -05:00
export function useDispose(gltf: GLTF & ObjectMap, path: string) {
2026-05-12 17:54:50 -05:00
useEffect(() => {
if (path in users) {
users[path]++;
} else {
users[path] = 1;
}
2026-05-12 17:54:50 -05:00
return () => {
if (--users[path] > 0) return;
2026-05-12 18:08:02 -05:00
gltf.scene.traverse((object) => {
if (object instanceof Mesh) {
if (object.material instanceof MeshStandardMaterial) {
const maps = [
object.material.map,
object.material.aoMap,
object.material.envMap,
object.material.bumpMap,
object.material.alphaMap,
object.material.lightMap,
object.material.normalMap,
object.material.emissiveMap,
object.material.roughnessMap,
object.material.metalnessMap,
object.material.displacementMap,
];
2026-05-12 17:54:50 -05:00
2026-05-12 18:08:02 -05:00
for (const map of maps) {
if (!map) continue;
2026-05-12 17:54:50 -05:00
2026-07-11 17:16:52 -05:00
if (map.source.data instanceof ImageBitmap) {
2026-07-10 21:30:21 +12:00
map.source.data.close();
}
2026-07-11 17:16:52 -05:00
2026-05-12 18:08:02 -05:00
map.dispose();
2026-05-12 17:54:50 -05:00
}
2026-05-12 18:08:02 -05:00
object.material.dispose();
} else {
throw new TypeError(
`Unexpected material type: ${object.material.type}`,
);
}
} else if (object instanceof Group || object instanceof Object3D) {
// traverse will get children
} else {
throw new TypeError(`Unexpected object type: ${object}`);
2026-05-12 17:54:50 -05:00
}
});
useLoader.clear(GLTFLoader, path);
Cache.remove(path);
};
}, [gltf, path]);
}