import type { Material, Texture, Object3D, Mesh, Line, Points } from "three";

/** 深度释放材质和纹理 */
export function disposeMaterial(material: Material | Material[]): void {
    if (Array.isArray(material)) {
        material.forEach(mat => disposeSingleMaterial(mat));
    } else if (material) { // 确保 material 不是 undefined 或 null
        disposeSingleMaterial(material);
    }
}

export function disposeSingleMaterial(material: Material): void {
    material.dispose();
    // 遍历材质的属性，查找并释放纹理
    for (const key in material) {
        const value = (material as any)[key] as unknown; // 使用 unknown 来进行更安全的类型检查
        if (value && typeof value === 'object' && 'isTexture' in value && (value as Texture).isTexture) {
            (value as Texture).dispose();
        }
    }
}

/** 释放节点的几何体、材质和纹理 */
export function disposeNode(node: Object3D): void {
    // 类型守卫，检查节点是否为 Mesh, Line, 或 Points
    if ((node as Mesh).isMesh || (node as Line).isLine || (node as Points).isPoints) {
        const obj = node as Mesh | Line | Points;

        if (obj.geometry) {
            obj.geometry.dispose();
            // console.log("Disposed geometry:", obj.geometry.uuid);
        }

        if (obj.material) {
            disposeMaterial(obj.material);
            // console.log("Disposed material(s) for node:", obj.uuid);
        }
    }
}
