123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680 |
- System.register(["__unresolved_0", "cc", "__unresolved_1", "__unresolved_2"], function (_export, _context) {
- "use strict";
- var _reporterNs, _cclegacy, __checkObsolete__, __checkObsoleteInNamespace__, _decorator, assetManager, SpriteFrame, Singleton, bundleConfig, _dec, _class, _crd, ccclass, property, BundleManager, bundleMgr;
- function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
- function _reportPossibleCrUseOfSingleton(extras) {
- _reporterNs.report("Singleton", "./Singleton", _context.meta, extras);
- }
- function _reportPossibleCrUseOfbundleConfig(extras) {
- _reporterNs.report("bundleConfig", "../configs/BundleConfig", _context.meta, extras);
- }
- return {
- setters: [function (_unresolved_) {
- _reporterNs = _unresolved_;
- }, function (_cc) {
- _cclegacy = _cc.cclegacy;
- __checkObsolete__ = _cc.__checkObsolete__;
- __checkObsoleteInNamespace__ = _cc.__checkObsoleteInNamespace__;
- _decorator = _cc._decorator;
- assetManager = _cc.assetManager;
- SpriteFrame = _cc.SpriteFrame;
- }, function (_unresolved_2) {
- Singleton = _unresolved_2.Singleton;
- }, function (_unresolved_3) {
- bundleConfig = _unresolved_3.bundleConfig;
- }],
- execute: function () {
- _crd = true;
- _cclegacy._RF.push({}, "1fa75BNI1pLj673iR8sywfM", "BundleManager", undefined);
- __checkObsolete__(['_decorator', 'Asset', 'assetManager', 'AssetManager', 'Constructor', 'SpriteFrame']);
- ({
- ccclass,
- property
- } = _decorator);
- /** wws
- * Bundle 中的单个资源定义
- */
- /** wws
- * Bundle 中的单个资源定义
- */
- /**Bundle 配置项*/
- /**Bundle 配置表类型(Map结构) Key: Bundle名称 Value: Bundle配置*/
- /**加载进度信息*/
- /**
- * 进度回调函数类型
- * @param progress 当前加载进度信息
- */
- /**
- * 调用实例
- * bundleMgr.preloadConfigAllRes((progress) => {
- const percent = Math.floor(progress.totalProgress * 100);
- this.loadUI.progressLabel.string = `加载进度: ${percent}%`;
- this.loadUI.tipLabel.string = `${progress.currentBundle} (${progress.completedSteps}/${progress.totalSteps})`;
- // 更新进度条
- this.progressBar.progress = progress.totalProgress;
- this.progressBar.progress = progress.bundleProgress;
- //调试信息(可选)
- Logger.log(`当前加载: ${progress.currentAsset}`);
- });
- */
- BundleManager = (_dec = ccclass('BundleManager'), _dec(_class = class BundleManager extends (_crd && Singleton === void 0 ? (_reportPossibleCrUseOfSingleton({
- error: Error()
- }), Singleton) : Singleton) {
- constructor() {
- super(...arguments);
- //已加载的Bundle缓存(包含引用计数)
- this._bundles = new Map();
- //资源结果缓存cache (path -> asset)
- this._assetCache = new Map();
- //Bundle配置表
- this._settings = new Map();
- //当前加载进度状态
- this._loadProgress = {
- totalSteps: 0,
- completedSteps: 0,
- currentBundle: '',
- currentAsset: '',
- bundleProgress: 0,
- totalProgress: 0
- };
- }
- /**
- * 加载配置bundle下的所有资源
- * @param onProgress 加载的进度回调
- * @example 调用事例:
- bundleMgr.preloadConfigAllRes((progress) => {
- //更新UI进度显示
- const percent = Math.floor(progress.totalProgress * 100);
- this.loadUI.progressLabel.string = `加载进度: ${percent}%`;
- this.loadUI.tipLabel.string = `${progress.currentBundle} | ${progress.currentAsset}
- (${progress.completedSteps}/${progress.totalSteps})`;
- //更新进度条
- this.progressBar.progress = progress.totalProgress;
- //this.progressBar.progress = progress.bundleProgress;
- //调试信息(可选)
- Logger.log(`当前加载: ${progress.currentBundle}` + `${progress.currentAsset}`);
- if(progress.totalProgress == 1){
- this.loadComplete = true;
- }
- });
- */
- preloadConfigAllRes(onProgress, config) {
- var _this = this;
- return _asyncToGenerator(function* () {
- if (config === void 0) {
- config = _crd && bundleConfig === void 0 ? (_reportPossibleCrUseOfbundleConfig({
- error: Error()
- }), bundleConfig) : bundleConfig;
- }
- //初始化Bundle配置
- _this._settings = config;
- yield _this._calculateTotalSteps(); //开始加载并显示进度
- yield bundleMgr.loadLaunchBundles(onProgress);
- })();
- }
- /**
- * 加载启动时必须的Bundle(根据配置表中loadAtLaunch=true的配置)
- * @param onProgress 进度回调函数(可选)
- */
- loadLaunchBundles(onProgress) {
- var _this2 = this;
- return _asyncToGenerator(function* () {
- //重置进度状态
- _this2._resetProgress(); //获取需要加载的Bundle配置
- var bundlesToLoad = Array.from(_this2._settings.entries()).filter(_ref => {
- var [_, setting] = _ref;
- return setting.loadAtLaunch;
- }); //顺序加载每个Bundle
- for (var [bundleName, setting] of bundlesToLoad) {
- _this2._loadProgress.currentBundle = bundleName;
- if (setting != null && setting.autoLoadAll) {
- yield _this2._loadAutoBundle(bundleName, setting, onProgress);
- } else if (setting != null && setting.preloadAssets) {
- yield _this2._loadConfiguredBundle(bundleName, setting.preloadAssets, onProgress);
- }
- }
- })();
- }
- getBundleAssetList(bundleName) {
- return _asyncToGenerator(function* () {
- // 远程 Bundle 路径
- var configUrl = bundleName + "/config.json"; // 使用原生 XMLHttpRequest 或 fetch 获取 config.json
- var response = yield fetch(configUrl);
- var config = yield response.json(); // 从 config.json 中提取资源路径
- if (config && config.packages && config.packages[0] && config.packages[0].pathMap) {
- return Object.keys(config.packages[0].pathMap);
- }
- return [];
- })();
- }
- /**
- * 计算总加载步骤数(用于进度计算)
- */
- _calculateTotalSteps() {
- var _this3 = this;
- return _asyncToGenerator(function* () {
- var total = 0;
- for (var [bundleName, setting] of _this3._settings) {
- if (setting != null && setting.loadAtLaunch) {
- var _bundle = yield _this3.getBundle(bundleName);
- if (setting != null && setting.autoLoadAll) {
- var _bundle$config;
- //整个bundle包下的资源
- if (_bundle && (_bundle$config = _bundle['config']) != null && (_bundle$config = _bundle$config.paths) != null && _bundle$config._map) {
- total += Object.keys(_bundle['config'].paths._map).length;
- }
- } else if (setting != null && setting.preloadAssets) {
- //只统计需要加载的资源(skipLoading=false的)
- var pathsToLoad = yield _this3._expandDirectoryAssets(_bundle, setting.preloadAssets);
- total += pathsToLoad.length;
- }
- }
- }
- _this3._loadProgress.totalSteps = total;
- })();
- }
- /**
- * 自动加载Bundle内所有资源
- */
- _loadAutoBundle(bundleName, setting, onProgress) {
- var _this4 = this;
- return _asyncToGenerator(function* () {
- //加载Bundle
- var bundle = yield _this4.getBundle(bundleName); //获取Bundle内所有资源路径(带类型信息)
- var assets = yield _this4._getBundleAssets(bundle, {
- excludeExtensions: setting.excludeExtensions
- }); //过滤时使用资源的path字段
- var filteredAssets = assets.filter(asset => {
- var _setting$excludePaths;
- return !((_setting$excludePaths = setting.excludePaths) != null && _setting$excludePaths.some(exclude => asset.path.startsWith(exclude)));
- }); //直接传递完整资源对象(包含path和type)
- yield _this4._loadBundleAssets(bundleName, filteredAssets, // 直接传递完整资源对象
- onProgress);
- })();
- }
- /**
- * 根据配置加载Bundle资源
- */
- _loadConfiguredBundle(bundleName, assets, onProgress) {
- var _this5 = this;
- return _asyncToGenerator(function* () {
- //加载Bundle 处理目录资源
- var bundle = yield _this5.getBundle(bundleName); //一个bundle下的目录资源
- var pathsToLoad = yield _this5._expandDirectoryAssets(bundle, assets); //加载资源
- yield _this5._loadBundleAssets(bundleName, pathsToLoad.map(asset => _extends({
- path: asset.path
- }, asset.type && {
- type: asset.type
- })), onProgress);
- })();
- }
- /**
- * 加载指定Bundle
- * @param bundleName Bundle名称
- * @param onComplete 加载完成回调
- */
- loadBundle(bundleName, onComplete) {
- //检查是否已加载
- var bundleInfo = this._bundles.get(bundleName);
- if (bundleInfo) {
- bundleInfo.refCount++;
- onComplete == null || onComplete(null, bundleInfo.bundle);
- return;
- } //加载新Bundle
- assetManager.loadBundle(bundleName, (err, bundle) => {
- if (err) {
- console.error("\u52A0\u8F7DBundle\u5931\u8D25 [" + bundleName + "]:", err);
- onComplete == null || onComplete(err);
- return;
- } //缓存Bundle并设置引用计数
- this._bundles.set(bundleName, {
- bundle: bundle,
- refCount: 1
- });
- onComplete == null || onComplete(null, bundle);
- });
- }
- /**
- * 获取Bundle内资源路径列表
- */
- _getBundleAssets(bundle, options) {
- var _bundle$_config;
- if (options === void 0) {
- options = {};
- }
- var {
- excludeFolders = true,
- excludeExtensions = []
- } = options;
- var assets = []; //更安全的类型断言和路径过滤
- var pathMap = (_bundle$_config = bundle['_config']) == null || (_bundle$_config = _bundle$_config.assetInfos) == null ? void 0 : _bundle$_config._map;
- if (pathMap) {
- //过滤无效路径和带的衍生资源
- Object.values(pathMap).forEach(info => {
- if (info.path && !info.path.includes('@')) {
- assets.push({
- path: info.path,
- type: info.ctor
- });
- }
- });
- } //过滤处理 排除文件夹路径
- var result = assets.filter(asset => {
- //排除文件夹
- if (excludeFolders && asset.path.endsWith('/')) return false; //排除指定扩展名
- if (excludeExtensions != null && excludeExtensions.length && excludeExtensions.some(ext => asset.path.endsWith(ext))) return false;
- return true;
- });
- return result;
- }
- /**
- * 加载Bundle内的多个资源
- */
- _loadBundleAssets(bundleName, assets, onProgress) {
- var _this6 = this;
- return _asyncToGenerator(function* () {
- var totalAssets = assets.length;
- if (totalAssets == 0) return;
- var loadedAssets = 0; //创建所有资源的加载Promise数组
- var loadPromises = assets.map(asset => {
- return new Promise((resolve, reject) => {
- _this6.loadAsset(bundleName, asset.path, asset.type, err => {
- if (err) {
- console.error("[" + bundleName + "] \u52A0\u8F7D\u8D44\u6E90\u5931\u8D25: " + asset.path, err);
- reject(err);
- return;
- }
- loadedAssets++;
- _this6._loadProgress.completedSteps++;
- _this6._loadProgress.currentBundle = bundleName;
- _this6._loadProgress.currentAsset = asset.path;
- _this6._loadProgress.bundleProgress = loadedAssets / totalAssets;
- _this6._loadProgress.totalProgress = Math.min(_this6._loadProgress.completedSteps / _this6._loadProgress.totalSteps, 1 // 避免提前显示100%
- );
- _this6._updateProgress(onProgress);
- resolve();
- });
- });
- }); //等待所有资源加载完成
- yield Promise.all(loadPromises).catch(err => {
- console.error("[" + bundleName + "] \u90E8\u5206\u8D44\u6E90\u52A0\u8F7D\u5931\u8D25", err);
- throw err; // 重新抛出错误让上层处理
- });
- })();
- }
- /**调用事例
- await this.loadMultipleAssets("levels",
- [{ path: "map", type: Prefab },
- { path: "textures/trees", type: SpriteFrame },
- ],
- (progress) => {//直接更新UI进度条(0~1)
- this.loadingBar.progress = progress;
- }
- (err, asset, path) => {
- if (err) {
- Logger.error(`资源 ${path} 加载失败:`, err);
- } else {
- Logger.log(`资源 ${path} 加载成功:`, asset);
- }
- }
- );
- * 加载Bundle内的多个资源(仅计算当前Bundle的进度)
- * @param bundleName Bundle名称
- * @param assets 资源列表
- * @param onProgress 进度回调(当前Bundle的进度,范围0~1)
- */
- loadMultipleAssets(bundleName, assets, onProgress, onComplete) {
- var _this7 = this;
- return _asyncToGenerator(function* () {
- var totalAssets = assets.length;
- var loadedAssets = 0;
- var _loop = function* _loop(_asset) {
- yield new Promise(resolve => {
- _this7.loadAsset(bundleName, _asset.path, _asset.type, (err, loadedAsset) => {
- if (err) {
- console.error("\u52A0\u8F7D\u8D44\u6E90\u5931\u8D25 [" + bundleName + "] " + _asset.path + ":", err);
- onComplete == null || onComplete(err, undefined, _asset.path);
- } else {
- loadedAssets++;
- var bundleProgress = loadedAssets / totalAssets;
- onProgress == null || onProgress(bundleProgress);
- onComplete == null || onComplete(null, loadedAsset, _asset.path);
- }
- resolve();
- });
- });
- };
- for (var _asset of assets) {
- yield* _loop(_asset);
- }
- })();
- }
- /**调用事例
- await bundleMgr.loadAsset(bundleName,path,AudioClip,(err: Error, clip: AudioClip) => {
- if(err) {
- Logger.error("加载资源失败:", err);
- return;
- }});
- * 加载Bundle内的指定资源
- * @param bundleName Bundle名称
- * @param assetPath 资源路径
- * @param type 资源类型(可选)
- * @param onComplete 加载完成回调
- */
- loadAsset(bundleName, assetPath, type, onComplete) {
- var cacheKey = assetPath + "-" + (type == null ? void 0 : type.name); //从资源缓存中caches取
- var cachedAsset = this._assetCache.get(cacheKey);
- if (cachedAsset) {
- //console.log(`[Cache Hit] Using cached asset: ${cacheKey}`);
- onComplete == null || onComplete(null, cachedAsset);
- return Promise.resolve(cachedAsset);
- }
- return new Promise((resolve, reject) => {
- this.loadBundle(bundleName, (err, bundle) => {
- if (err) {
- onComplete == null || onComplete(err);
- reject(err);
- return;
- } //特殊处理SpriteFrame的路径提示
- var isSpriteFrame = type && type.name === 'SpriteFrame';
- if (isSpriteFrame && !assetPath.endsWith('/spriteFrame')) {
- console.warn("SpriteFrame\u8DEF\u5F84\u5EFA\u8BAE: " + assetPath + " -> " + assetPath + "/spriteFrame", "\n(\u8BF7\u786E\u8BA4\u662F\u5426\u4F7F\u7528\u5B8C\u6574SpriteFrame\u8DEF\u5F84)");
- }
- bundle.load(assetPath, type, (err, asset) => {
- if (err || !asset) {
- console.error("\u52A0\u8F7D\u5931\u8D25 [" + bundleName + "] " + assetPath + ":", err.message);
- var warning = isSpriteFrame ? "\n\u53EF\u80FD\u539F\u56E0:\n1. \u4F7F\u7528\u5B8C\u6574\u8DEF\u5F84\u5982 " + assetPath + "/spriteFrame \u7C7B\u578B\u4E3ASpriteFrame\n2. \u6216\u8005\u52A0\u8F7DTexture: " + assetPath + "/texture \u7C7B\u578B\u4E3ATexture" : "\n\u8BF7\u68C0\u67E5\u8D44\u6E90\u8DEF\u5F84\u662F\u5426\u6B63\u786E";
- console.warn("\u7A7A\u8D44\u6E90 [" + bundleName + "] " + assetPath, warning);
- onComplete == null || onComplete(err);
- reject(err != null ? err : new Error("Asset is null"));
- return;
- }
- this._assetCache.set(cacheKey, asset);
- console.log("\u52A0\u8F7D\u8D44\u6E90 " + assetPath + " \u6210\u529F: " + cacheKey + " + \u7C7B\u578B\u4E3A: " + (asset == null ? void 0 : asset.constructor.name));
- onComplete == null || onComplete(err, asset);
- resolve(asset);
- });
- });
- });
- }
- /**
- * 释放Bundle
- * @param bundleName Bundle名称
- * @param force 是否强制释放(即使还有引用)
- */
- releaseBundle(bundleName, force) {
- if (force === void 0) {
- force = false;
- }
- var bundleInfo = this._bundles.get(bundleName);
- if (!bundleInfo) return; //减少引用计数
- bundleInfo.refCount--; // 当引用计数归零或强制释放时
- if (bundleInfo.refCount <= 0 || force) {
- assetManager.removeBundle(bundleInfo.bundle);
- this._bundles.delete(bundleName);
- console.log("\u5DF2\u91CA\u653EBundle: " + bundleName);
- }
- }
- /**
- * 获取已加载的Bundle实例
- * @param bundleName Bundle名称
- * @returns Bundle实例或null
- */
- getBundle(bundleName) {
- var _this8 = this;
- return _asyncToGenerator(function* () {
- var _this8$_bundles$get;
- //先从缓存中查找
- var cachedBundle = (_this8$_bundles$get = _this8._bundles.get(bundleName)) == null ? void 0 : _this8$_bundles$get.bundle;
- if (cachedBundle) {
- return cachedBundle;
- }
- try {
- //如果缓存中没有,则加载bundle
- var _bundle2 = yield new Promise((resolve, reject) => {
- assetManager.loadBundle(bundleName, (err, bundle) => {
- err ? reject(err) : resolve(bundle);
- });
- });
- return _bundle2;
- } catch (error) {
- console.error("\u52A0\u8F7DBundle " + bundleName + " \u5931\u8D25:", error);
- return null;
- }
- })();
- }
- /**
- * 检查Bundle是否已加载
- * @param bundleName Bundle名称
- */
- hasBundle(bundleName) {
- return this._bundles.has(bundleName);
- }
- /**
- * 释放所有Bundle
- * @param force 是否强制释放
- */
- releaseAll(force) {
- if (force === void 0) {
- force = false;
- }
- this._bundles.forEach((_, name) => this.releaseBundle(name, force));
- }
- /**
- * 展开目录资源为具体资源列表
- * @param bundle Bundle实例
- * @param assets 原始资源列表
- */
- _expandDirectoryAssets(bundle, assets) {
- var _this9 = this;
- return _asyncToGenerator(function* () {
- var result = [];
- var _loop2 = function* _loop2() {
- var asset = assets[idx];
- if (!(asset != null && asset.isDirectory)) {
- if (!(asset != null && asset.skipLoading)) {
- result.push(asset);
- }
- } else {
- //获取目录下所有资源路径
- var dirPath = asset.path.endsWith('/') ? asset.path : asset.path + "/"; //获取带类型信息的资源列表
- var allPaths = yield _this9._getBundleAssets(bundle, {
- excludeFolders: true,
- excludeExtensions: ['.meta']
- }); //保留原始类型信息
- var dirResources = allPaths.filter(res => res.path.startsWith(dirPath) && !res.path.substring(dirPath.length).includes('/')); //转换时携带类型信息
- dirResources.forEach(res => {
- result.push({
- path: res.path,
- type: res.type,
- // 保留类型信息
- skipLoading: false
- });
- });
- }
- };
- for (var idx = 0; idx < assets.length; idx++) {
- yield* _loop2();
- }
- result = result.filter(asset => !(asset != null && asset.skipLoading));
- return result;
- })();
- }
- /**
- * 触发进度回调
- */
- _updateProgress(onProgress) {
- //传递进度状态的副本,避免外部修改
- onProgress == null || onProgress(_extends({}, this._loadProgress));
- }
- /**
- * 重置加载进度状态
- */
- _resetProgress() {
- this._loadProgress = {
- totalSteps: this._loadProgress.totalSteps,
- // 保持总步骤数
- completedSteps: 0,
- currentBundle: '',
- currentAsset: '',
- bundleProgress: 0,
- totalProgress: 0
- };
- }
- /**
- * 明确指定元组类型
- * @param asset 未使用这个方法 之前在测试
- * { path: 'texture/msg_hint/spriteFrame', type: SpriteFrame },
- { path: 'texture/test_01/texture', type: Texture2D },
- 这两种的时候有写到
- */
- _getLoadArguments(asset) {
- // 返回元组类型
- if (asset.type === SpriteFrame) {
- return [asset.path, asset.type];
- }
- return asset.type ? [asset.path, asset.type] : [asset.path];
- }
- }) || _class); //全局单例
- _export("bundleMgr", bundleMgr = BundleManager.ins());
- _cclegacy._RF.pop();
- _crd = false;
- }
- };
- });
- //# sourceMappingURL=a3ceb9baa9ec92dce895d8c30568a194aeb574e7.js.map
|