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
|
|
|
|
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(() => {
|
|
|
|
|
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-05-12 18:08:02 -05:00
|
|
|
map.source.data.close();
|
|
|
|
|
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]);
|
|
|
|
|
}
|