import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import { draco, textureCompress } from '@gltf-transform/functions';
import draco3d from 'draco3dgltf';
/**
 * 3D 模型压缩 Vite 插件
 * 使用 gltf-transform 压缩 GLB/GLTF 模型
 */
export function viteModelCompressionPlugin(options = {}) {
    const { quality = 0.8, method = 'draco', enabled = true } = options;
    if (!enabled) {
        return {
            name: 'vite-plugin-model-compression',
            // 返回空插件
        };
    }
    return {
        name: 'vite-plugin-model-compression',
        async transform(code, id) {
            // 只处理 GLB/GLTF 文件
            if (!id.match(/\.(glb|gltf)$/i)) {
                return null;
            }
            try {
                // 初始化 gltf-transform
                const io = new NodeIO()
                    .registerExtensions(ALL_EXTENSIONS)
                    .registerDependencies({
                    'draco3d.decoder': await draco3d.createDecoderModule(),
                    'draco3d.encoder': await draco3d.createEncoderModule(),
                });
                // 读取模型
                const document = await io.read(id);
                // 应用压缩
                if (method === 'draco') {
                    await document.transform(draco({
                        quantizePosition: 14,
                        quantizeNormal: 10,
                        quantizeTexcoord: 12,
                        quantizeColor: 8,
                    }));
                }
                // 纹理压缩
                await document.transform(textureCompress({
                    targetFormat: 'webp',
                    quality: quality,
                }));
                // 转换为 Base64 data URL
                const glb = await io.writeBinary(document);
                const base64 = Buffer.from(glb).toString('base64');
                return {
                    code: `export default "data:model/gltf-binary;base64,${base64}"`,
                    map: null,
                };
            }
            catch (error) {
                console.warn(`警告: 无法压缩模型文件 ${id}: ${error instanceof Error ? error.message : String(error)}`);
                // 如果压缩失败，返回原始内容
                return null;
            }
        },
    };
}
