在 Babylon.js 中实现智能异步资源加载队列管理
在 3D 应用开发中,资源加载是核心问题之一。特别是在 Babylon.js 开发中,当我们需要加载大量 3D 模型时,如何高效管理这些异步加载的资源,避免重复加载,同时处理好并发请求,是一个常见挑战。本文将介绍一种基于 Promise 和状态管理的解决方案。
问题场景
假设我们正在开发一个 3D 场景编辑器,需要动态加载各种模型资源。我们可能会遇到以下问题:
-
同一资源被多次请求加载
-
并发加载导致资源重复下载
-
无法跟踪资源加载状态
-
内存管理困难
解决方案核心
我们设计一个 AssetContainerManager
类,它将:
-
使用 Map 存储加载状态
-
统一处理并发请求
-
提供内存管理接口
-
支持进度跟踪
完整实现
class AssetContainerManager {private containerMap = new Map<string, Promise<AssetContainer> | AssetContainer>();private refCounts = new Map<string, number>();private loadEvents = new EventEmitter();public async load(scene: Scene,url: string,onProgress?: (event: ISceneLoaderProgressEvent) => void): Promise<AssetContainer> {const existing = this.containerMap.get(url);if (existing) return existing;const loadPromise = AssetContainer.LoadFromFileAsync(url,scene,onProgress).then(container => {this.containerMap.set(url, container);this.refCounts.set(url, 0);this.loadEvents.emit(`loaded:${url}`, container);return container;}).catch(err => {this.containerMap.delete(url);throw err;});this.containerMap.set(url, loadPromise);return loadPromise;}public get(url: string): AssetContainer | null {const entry = this.containerMap.get(url);return entry instanceof AssetContainer ? entry : null;}public async use(scene: Scene, url: string): Promise<AssetContainer> {const container = await this.load(scene, url);this.refCounts.set(url, (this.refCounts.get(url) || 0) + 1);return container;}public release(url: string): void {const count = (this.refCounts.get(url) || 1) - 1;if (count <= 0) {const container = this.get(url);container?.dispose();this.containerMap.delete(url);this.refCounts.delete(url);} else {this.refCounts.set(url, count);}}
}
关键设计解析
1. 状态统一管理
我们使用一个 Map 来存储两种状态:
private containerMap = new Map<string,Promise<AssetContainer> | AssetContainer
>();
-
Promise 表示资源正在加载中
-
AssetContainer 表示已加载完成
2. 并发请求处理
当多个地方同时请求同一个资源时:
typescript
复制
// 第一次请求 const promise1 = manager.load(scene, "model.glb");// 第二次请求(返回同一个Promise) const promise2 = manager.load(scene, "model.glb");console.log(promise1 === promise2); // true
3. 引用计数
通过引用计数管理资源生命周期:
使用示例
基本加载
const manager = new AssetContainerManager();// 加载模型
const container = await manager.load(scene, "https://example.com/model.glb",progress => {console.log(`加载进度: ${progress.loaded}/${progress.total}`);}
);// 添加到场景
container.addAllToScene();
批量预加载
async function preloadAssets(scene: Scene, urls: string[]) {await Promise.all(urls.map(url => manager.load(scene, url)));console.log("所有资源预加载完成");
}
带引用计数的使用
class ModelComponent {constructor(private manager: AssetContainerManager, private url: string) {}private container?: AssetContainer;async show(scene: Scene) {this.container = await this.manager.use(scene, this.url);this.container.addAllToScene();}hide() {this.container?.removeAllFromScene();this.manager.release(this.url);}
}
高级功能扩展
1. 加载优先级队列
interface LoadTask {url: string;priority: number;
}class PriorityLoader {private queue: LoadTask[] = [];addTask(task: LoadTask) {this.queue.push(task);this.queue.sort((a, b) => b.priority - a.priority);}async process(manager: AssetContainerManager, scene: Scene) {while (this.queue.length) {const task = this.queue.shift()!;await manager.load(scene, task.url);}}
}
2. 缓存控制
class AssetContainerManager {private maxCacheSize = 10;private checkCache() {if (this.containerMap.size > this.maxCacheSize) {// 找到最久未使用的资源const lruKey = this.getLRUKey(); this.release(lruKey);}}// ...其他代码
}
3. 加载失败重试
private async loadWithRetry(scene: Scene,url: string,retries = 3
): Promise<AssetContainer> {try {return await this.load(scene, url);} catch (err) {if (retries > 0) {console.warn(`加载 ${url} 失败,剩余重试次数 ${retries}`);await new Promise(res => setTimeout(res, 1000));return this.loadWithRetry(scene, url, retries - 1);}throw err;}
}
性能优化建议
-
并行加载限制:
import pLimit from 'p-limit';private limit = pLimit(4); // 最多4个并行加载async load(scene: Scene, url: string) {return this.limit(() => this._load(scene, url)); }
-
内存预警:
private checkMemory() {if (performance.memory && performance.memory.usedJSHeapSize > SOME_THRESHOLD) {this.clearUnusedAssets();} }
-
加载超时处理:
private async loadWithTimeout(scene: Scene, url: string, timeout = 10000) {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), timeout);try {return await AssetContainer.LoadFromFileAsync(url, scene,undefined,undefined,controller.signal);} finally {clearTimeout(timeoutId);} }
总结
本文介绍的 AssetContainerManager
提供了以下优势:
-
避免重复加载:相同URL的资源只会加载一次
-
并发请求合并:多个同时请求会共享同一个Promise
-
内存管理:通过引用计数自动释放资源
-
可扩展性:支持进度通知、优先级队列等扩展功能
-
类型安全:完整的TypeScript类型定义
这种模式不仅适用于Babylon.js的资源加载,也可以推广到其他类似的异步资源管理场景。开发者可以根据实际需求,进一步扩展或简化这个基础实现。