From 9a57fd674307317a319bdc0b7f2c7d7ff4443a54 Mon Sep 17 00:00:00 2001 From: npmrun <1549469775@qq.com> Date: Sun, 19 Apr 2026 12:07:20 +0800 Subject: [PATCH] feat: add AssetManager core module with ref counting --- src/core/AssetManager.ts | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/core/AssetManager.ts diff --git a/src/core/AssetManager.ts b/src/core/AssetManager.ts new file mode 100644 index 0000000..9622a2f --- /dev/null +++ b/src/core/AssetManager.ts @@ -0,0 +1,64 @@ +import { Assets, type AssetsBundle } from "pixi.js"; +import { logger } from "./Logger"; + +class AssetManager { + private referenceCounts: Map = new Map(); + + async init(): Promise { + await Assets.init({ manifest: "/manifest.json" }); + logger.debug("AssetManager initialized"); + } + + async loadBundle( + name: string, + onProgress?: (progress: number) => void + ): Promise { + // 已经加载过,增加引用计数 + if (this.referenceCounts.has(name)) { + const count = this.referenceCounts.get(name)! + 1; + this.referenceCounts.set(name, count); + logger.debug(`AssetManager: reuse bundle "${name}", refCount = ${count}`); + onProgress?.(1); + return Assets.getBundle(name); + } + + // 首次加载 + logger.debug(`AssetManager: loading bundle "${name}"`); + const bundle = await Assets.loadBundle(name, onProgress); + this.referenceCounts.set(name, 1); + return bundle; + } + + async unloadBundle(name: string): Promise { + if (!this.referenceCounts.has(name)) { + logger.warn(`AssetManager: unloading unloaded bundle "${name}"`); + return; + } + + const count = this.referenceCounts.get(name)! - 1; + this.referenceCounts.set(name, count); + + if (count <= 0) { + logger.debug(`AssetManager: unloading bundle "${name}"`); + await Assets.unloadBundle(name); + this.referenceCounts.delete(name); + } else { + logger.debug(`AssetManager: decrease refCount for "${name}" to ${count}`); + } + } + + isLoaded(name: string): boolean { + return this.referenceCounts.has(name) && this.referenceCounts.get(name)! > 0; + } + + getRefCount(name: string): number { + return this.referenceCounts.get(name) ?? 0; + } + + clearAll(): void { + this.referenceCounts.clear(); + } +} + +export const assetManager = new AssetManager(); +export default assetManager; \ No newline at end of file