import { Loader } from "three"; // or https://cdn.jsdelivr.net/npm/three/build/three.module.js'; // WASM module of TinyUSDZ. import initTinyUSDZNative from "./tinyusdz.js"; class FetchAssetResolver { constructor() { this.assetCache = new Map(); } async resolveAsync(uri) { try { const response = await fetch(uri); if (!response.ok) { throw new Error(`Failed to fetch asset: ${uri}`); } const data = await response.arrayBuffer(); //console.log(`Fetched asset ${uri} successfully, size: ${data.byteLength} bytes`); this.assetCache.set(uri, data); return Promise.resolve([uri, data]); } catch (error) { console.error(`Error resolving asset ${uri}:`, error); throw error; } } getAsset(uri) { if (this.assetCache.has(uri)) { return this.assetCache.get(uri); } else { console.warn(`Asset not found in cache: ${uri}`); return null; } } hasAsset(uri) { return this.assetCache.has(uri); } setAsset(uri, data) { this.assetCache.set(uri, data); } clearCache() { this.assetCache.clear(); } } // TODO // // Polish API // class TinyUSDZLoader extends Loader { constructor(manager) { super(manager); this.native_ = null; this.assetResolver_ = null; this.imageCache = {}; this.textureCache = {}; } // 初始化 native 模块(直接用普通 wasm,不用压缩) async init(options = {}) { if (!this.native_) { console.log("Initializing TinyUSDZ native module..."); // 直接 import,不传 wasmBinary(让 Emscripten 自己 fetch /tinyusdz.wasm) this.native_ = await initTinyUSDZNative(); if (!this.native_) { throw new Error("Failed to initialize TinyUSDZ native module."); } console.log("Native module initialized"); } return this; } // load 方法保持不变(内部会调用 init) load(url, onLoad, onProgress, onError) { const scope = this; const initPromise = this.native_ ? Promise.resolve() : this.init(); initPromise .then(() => fetch(url)) .then((response) => response.arrayBuffer()) .then((usd_data) => { const usd_binary = new Uint8Array(usd_data); scope.parse(usd_binary, url, onLoad, onError); }) .catch((error) => { console.error("TinyUSDZLoader error:", error); if (onError) onError(error); }); } // parse 方法保持不变 parse(binary, filePath, onLoad, onError) { if (!this.native_) { const err = new Error("Native module not initialized"); console.error(err); if (onError) onError(err); return; } const usd = new this.native_.TinyUSDZLoaderNative(); const ok = usd.loadFromBinary(binary, filePath); if (!ok) { const err = new Error("Failed to load USD from binary", { cause: usd.error() }); if (onError) onError(err); } else { onLoad(usd); } } // 其他方法(如 loadAsLayer)可以保留或根据需要删减 } export { TinyUSDZLoader, FetchAssetResolver };