找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/resource/loader/ResourceBundleLoader.ts
1import { Asset, AssetManager, assetManager } from 'cc';
2import { Framework } from "../../../Framework";
3import { ResourceBundleInfo } from "../ResourceBundleInfo";
4import { ResourceBundleLoadConfig, ResourceMode, ResourceRetryConfig } from "../ResourceFrameConfig";
5import { ResourceInfo } from "../ResourceInfo";
6
7/**
8 * AssetBundle资源加载器
9 */
10export class ResourceBundleLoader {
11 /** 可选的加载器初始化;通用实现不注册任何专用下载器。 */
12 public Init(): void {}
13
14 /** 与 Init 配对,供专项加载器撤销全局适配。 */
15 public DeInit(): void {}
16
17 // 已加载的 AssetBundle 缓存(key: bundle名称, value: BundleInfo)
18 protected bundleCache: Map<string, ResourceBundleInfo> = new Map();
19
20 /**
21 * 从缓存中获取Bundle
22 * @param bundleName Bundle名称
23 * @constructor
24 * @private
25 */
26 protected GetBundleFromCache(bundleName: string) {
27 if (this.bundleCache.has(bundleName)) {
28 return this.bundleCache.get(bundleName);
29 }
30 return null;
31 }
32
33 /**
34 * 添加Bundle到缓存
35 * @param bundleName Bundle名称
36 * @constructor
37 * @private
38 */
39 private AddBundleCache(bundleName: string): ResourceBundleInfo {
40 // Framework.Log.Error(Framework.Res.Name + " ResourceBundleLoader", "AddBundleCache", `添加Bundle到缓存: ${bundleName}`);
41 // 2. 初始化 BundleInfo(防止重复下载)
42 const bundleInfo: ResourceBundleInfo = {
43 Name: bundleName,
44 Bundle: null,
45 IsDownloaded: false,
46 DownloadPromise: null
47 };
48 this.bundleCache.set(bundleName, bundleInfo);
49
50 return bundleInfo;
51 }
52
53 /**
54 * 删除Bundle缓存
55 * @param bundleName Bundle名称
56 * @constructor
57 * @private
58 */
59 private DeleteBundleCache(bundleName: string) {
60 // Framework.Log.Error(Framework.Res.Name + " ResourceBundleLoader", "DeleteBundleCache", `删除Bundle缓存: ${bundleName}`);
61 this.bundleCache.delete(bundleName);
62 }
63
64 /** 清单以外的名称规则由专项实现提供,通用加载器不推导资源路径。 */
65 public ResolveResourceInfoByName(assetName: string): ResourceInfo | null {
66 return null;
67 }
68
69 /** 默认把配置地址作为 Bundle 根目录,不识别项目目录结构。 */
70 protected GetRemoteBundlePath(bundleName: string): string {
71 return Framework.Res.Config.RemoteUrl + bundleName;
72 }
73
74 /** 默认不覆盖调用方的版本;专项实现可提供非空版本。 */
75 protected GetBundleVersion(bundleName: string): string {
76 return "";
77 }
78
79 /** 通用模拟模式适用于所有包,专项实现可缩小范围。 */
80 protected IsSimulatedBundle(bundleName: string): boolean {
81 return true;
82 }
83
84 // ======================================== 加载Bundle资源 ========================================
85 /**
86 * 加载Bundle包
87 * @param bundleName Bundle名称
88 * @constructor
89 */
90 /**
91 * 加载 Bundle
92 * @param bundleName Bundle 名称
93 * @param options 引擎原生 loadBundle 选项
94 * @param traceId 日志链路 id(可选,不传则内部自动生成)
95 */
96 public async LoadBundle(opt: {
97 bundleName: string,
98 options: { [k: string]: any; version?: string; } | null,
99 traceId?: number,
100 maxCount?: number,
101 retryTime?: number,
102 preloadAllBundleAssets?: boolean
103 }) {
104 // 如果外部没有传入 TraceId,则在这里生成一个新的
105 const traceId = opt.traceId ?? Framework.Log.NextTraceId();
106 const moduleName = `${Framework.Res.Name}_ResourceBundleLoader`;
107 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `请求加载 Bundle: ${opt.bundleName}`);
108
109 let cachedBundle = this.GetBundleFromCache(opt.bundleName);
110 // 1. 检查缓存,已加载直接返回
111 if (cachedBundle?.Bundle) {
112 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `缓存命中,直接返回 Bundle: ${opt.bundleName}`);
113 return cachedBundle.Bundle;
114 }
115
116 // 2. 如果已有加载中的 Promise,则等待同一份结果
117 if (cachedBundle?.DownloadPromise != null) {
118 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `已有加载任务,等待完成: ${opt.bundleName}`);
119 await cachedBundle.DownloadPromise;
120 return cachedBundle.Bundle;
121 }
122
123 // 3. 新建 BundleInfo 并开始真正的加载流程
124 let bundleInfo = this.AddBundleCache(opt.bundleName);
125
126 try {
127 // 远程模式:下载 Bundle
128 if (Framework.Res.Config.ResourceMode == ResourceMode.Remote) {
129 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `资源模式: 远程(Remote)`);
130 await this.LoadBundleFromRemote({
131 bundleName: opt.bundleName, bundleInfo, options: opt.options, traceId,
132 MaxRetryCount: opt.maxCount, RetryInterval: opt.retryTime, preloadAllBundleAssets: opt.preloadAllBundleAssets,
133 });
134 } else if (Framework.Res.Config.ResourceMode == ResourceMode.LocalSimulateRemote) {
135 // 由选用的加载器决定模拟范围,不在通用流程中识别资源名称。
136 if (this.IsSimulatedBundle(opt.bundleName)) {
137 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `资源模式: 本地模拟远程(LocalSimulateRemote) - Bundle走模拟服务器`);
138 await this.LoadBundleFromSimulateRemote({
139 bundleName: opt.bundleName, bundleInfo, options: opt.options, traceId,
140 MaxRetryCount: opt.maxCount, RetryInterval: opt.retryTime, preloadAllBundleAssets: opt.preloadAllBundleAssets,
141 });
142 } else {
143 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `资源模式: 本地模拟远程(LocalSimulateRemote) - Bundle走本地`);
144 await this.LoadBundleFromLocal({
145 bundleName: opt.bundleName, bundleInfo: bundleInfo, options: opt.options, traceId,
146 MaxRetryCount: opt.maxCount, RetryInterval: opt.retryTime, preloadAllBundleAssets: opt.preloadAllBundleAssets,
147 });
148 }
149 } else { // 本地模式:直接加载本地 Bundle
150 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `资源模式: 本地(Local)`);
151 await this.LoadBundleFromLocal({
152 bundleName: opt.bundleName, bundleInfo: bundleInfo, options: opt.options, traceId,
153 MaxRetryCount: opt.maxCount, RetryInterval: opt.retryTime, preloadAllBundleAssets: opt.preloadAllBundleAssets,
154 });
155 }
156
157 Framework.Log.TraceLog(traceId, moduleName, "LoadBundle", `加载流程结束,返回 Bundle: ${opt.bundleName}`);
158
159 const shouldPreloadAll = opt.preloadAllBundleAssets ?? ResourceBundleLoadConfig.preloadAllBundleAssets;
160 if (shouldPreloadAll && bundleInfo.Bundle) {
161 this.PreloadAllBundleAssets(bundleInfo.Bundle, opt.bundleName, traceId);
162 }
163
164 return bundleInfo.Bundle;
165
166 } catch (e) {
167 Framework.Log.TraceError(traceId, moduleName, "LoadBundle", `Bundle 加载失败: ${opt.bundleName}`, e);
168 this.DeleteBundleCache(bundleInfo.Name); // 删除失败的 Bundle 缓存
169 return null;
170 }
171 }
172
173 /**
174 * 加载本地Bundle包
175 * @param bundleName Bundle名称
176 * @param bundleInfo Bundle信息
177 * @constructor
178 * @private
179 */
180 private async LoadBundleFromLocal(opt: {
181 bundleName: string,
182 bundleInfo: ResourceBundleInfo,
183 options: { [k: string]: any; version?: string; } | null,
184 traceId?: number,
185 MaxRetryCount?: number,
186 RetryInterval?: number,
187 preloadAllBundleAssets?: boolean,
188 }): Promise<AssetManager.Bundle | null> {
189 const localBundlePath = `${opt.bundleName}`;
190 // 这里不再单独打印日志,由 LoadBundleByPath 统一输出
191 return this.LoadBundleByPath({
192 bundlePath: localBundlePath, bundleInfo: opt.bundleInfo, isRemote: false, options: opt.options, traceId: opt.traceId,
193 MaxRetryCount: opt.MaxRetryCount, RetryInterval: opt.RetryInterval, preloadAllBundleAssets: opt.preloadAllBundleAssets,
194 }); // 第三个参数标记为本地加载
195 }
196
197 /**
198 * 加载远程Bundle包
199 * @param bundleName Bundle名称
200 * @param bundleInfo Bundle信息
201 * @constructor
202 * @private
203 */
204 private async LoadBundleFromRemote(
205 opt: {
206 bundleName: string,
207 bundleInfo: ResourceBundleInfo,
208 options: { [k: string]: any; version?: string; } | null,
209 traceId?: number,
210 MaxRetryCount?: number,
211 RetryInterval?: number,
212 preloadAllBundleAssets?: boolean,
213 }): Promise<AssetManager.Bundle | null> {
214 const remoteBundleURL = this.GetRemoteBundlePath(opt.bundleName);
215 let loadOptions = opt.options;
216 const version = this.GetBundleVersion(opt.bundleName);
217 // 仅在专项版本有效时创建参数副本;其余情况保留调用方 options。
218 if (version.length > 0) {
219 loadOptions = { ...(opt.options ?? {}), version };
220 }
221
222 return this.LoadBundleByPath({
223 bundlePath: remoteBundleURL, bundleInfo: opt.bundleInfo, isRemote: true, options: loadOptions, traceId: opt.traceId,
224 MaxRetryCount: opt.MaxRetryCount, RetryInterval: opt.RetryInterval, preloadAllBundleAssets: opt.preloadAllBundleAssets
225 });
226 }
227
228 /**
229 * 本地模拟远程加载 Bundle
230 */
231 private async LoadBundleFromSimulateRemote(
232 opt: {
233 bundleName: string,
234 bundleInfo: ResourceBundleInfo,
235 options: { [k: string]: any; version?: string; } | null,
236 traceId?: number,
237 MaxRetryCount?: number,
238 RetryInterval?: number,
239 preloadAllBundleAssets?: boolean,
240 }): Promise<AssetManager.Bundle | null> {
241 const remoteBundleURL = `${Framework.Res.Config.LocalSimulateUrl}${opt.bundleName}`;
242 let loadOptions = opt.options;
243 // 模拟服务不读版本表,不修改调用方选项。
244 if (loadOptions?.version !== undefined) {
245 loadOptions = { ...loadOptions };
246 delete loadOptions.version;
247 }
248 return this.LoadBundleByPath({
249 bundlePath: remoteBundleURL, bundleInfo: opt.bundleInfo, isRemote: true, options: loadOptions, traceId: opt.traceId,
250 MaxRetryCount: opt.MaxRetryCount, RetryInterval: opt.RetryInterval, preloadAllBundleAssets: opt.preloadAllBundleAssets
251 });
252 }
253
254 /**
255 * 通用 Bundle 加载方法(合并本地/远程加载逻辑,内置失败重试)
256 * @param bundlePath Bundle 路径(本地路径或远程 URL)
257 * @param bundleInfo Bundle 信息对象
258 * @param isRemote 是否为远程加载
259 */
260 private async LoadBundleByPath(opt: {
261 bundlePath: string,
262 bundleInfo: ResourceBundleInfo,
263 isRemote: boolean,
264 options: { [k: string]: any; version?: string; } | null,
265 traceId?: number,
266 MaxRetryCount?: number,
267 RetryInterval?: number,
268 preloadAllBundleAssets?: boolean,
269 }
270 ): Promise<AssetManager.Bundle | null> {
271 const loadType = opt.isRemote ? "远程" : "本地";
272 const moduleName = `${Framework.Res.Name}_ResourceBundleLoader`;
273 const maxRetry = opt.MaxRetryCount ?? ResourceRetryConfig.maxRetryCount;
274 const interval = opt.RetryInterval ?? ResourceRetryConfig.retryInterval;
275
276 Framework.Log.TraceLog(opt.traceId ?? null, moduleName, "LoadBundleByPath", `开始加载${loadType} Bundle: ${opt.bundleInfo.Name}(路径: ${opt.bundlePath})`);
277
278 opt.bundleInfo.DownloadPromise = (async () => {
279 for (let attempt = 0; attempt <= maxRetry; attempt++) {
280 if (attempt > 0) {
281 Framework.Log.TraceLog(opt.traceId ?? null, moduleName, "LoadBundleByPath",
282 `重试第 ${attempt}/${opt.MaxRetryCount ?? maxRetry} 次加载 Bundle: ${opt.bundleInfo.Name}`);
283 await new Promise<void>(r => setTimeout(r, interval));
284 }
285
286 const ok = await new Promise<boolean>((resolve) => {
287 assetManager.loadBundle(opt.bundlePath, opt.options, (err, bundle) => {
288 if (err) {
289 Framework.Log.TraceError(opt.traceId ?? null, moduleName, "LoadBundleByPath",
290 `${loadType} Bundle 第 ${attempt + 1} 次加载失败: ${opt.bundlePath}`, err.message);
291 opt.bundleInfo.IsDownloaded = false;
292 opt.bundleInfo.Bundle = null;
293 resolve(false);
294 return;
295 }
296 opt.bundleInfo.IsDownloaded = true;
297 opt.bundleInfo.Bundle = bundle;
298 resolve(true);
299 });
300 });
301
302 if (ok) {
303 Framework.Log.TraceLog(opt.traceId ?? null, moduleName, "LoadBundleByPath", `${loadType} Bundle 加载完成: ${opt.bundleInfo.Name}`);
304 return;
305 }
306 }
307
308 Framework.Log.TraceError(opt.traceId ?? null, moduleName, "LoadBundleByPath",
309 `${loadType} Bundle 加载最终失败(已重试 ${maxRetry} 次): ${opt.bundlePath}`);
310 opt.bundleInfo.IsDownloaded = false;
311 opt.bundleInfo.Bundle = null;
312 this.DeleteBundleCache(opt.bundleInfo.Name);
313 })();
314
315 await opt.bundleInfo.DownloadPromise;
316 return opt.bundleInfo.Bundle;
317 }
318
319 /**
320 * 强制重新加载 Bundle(先释放再下载,用于 downloadFullBundleOnFail 场景)
321 */
322 public async ForceReloadBundle(bundleName: string, traceId?: number): Promise<AssetManager.Bundle | null> {
323 const moduleName = `${Framework.Res.Name}_ResourceBundleLoader`;
324 Framework.Log.TraceLog(traceId ?? null, moduleName, "ForceReloadBundle", `强制重新加载 Bundle: ${bundleName}`);
325 this.ReleaseBundle(bundleName);
326 return this.LoadBundle({ bundleName: bundleName, options: null, traceId });
327 }
328
329 /**
330 * 全量预加载 Bundle 内所有资源(非阻塞)
331 */
332 private PreloadAllBundleAssets(bundle: AssetManager.Bundle, bundleName: string, traceId?: number): void {
333 const moduleName = `${Framework.Res.Name}_ResourceBundleLoader`;
334 Framework.Log.TraceLog(traceId ?? null, moduleName, "PreloadAllBundleAssets", `开始全量预加载 Bundle: ${bundleName}`);
335 bundle.preloadDir("", Asset as any, null, (err) => {
336 if (err) {
337 Framework.Log.TraceError(traceId ?? null, moduleName, "PreloadAllBundleAssets",
338 `全量预加载 Bundle 失败: ${bundleName}`, err.message);
339 } else {
340 Framework.Log.TraceLog(traceId ?? null, moduleName, "PreloadAllBundleAssets",
341 `全量预加载 Bundle 完成: ${bundleName}`);
342 }
343 });
344 }
345
346 // ======================================== 资源释放与清理 ========================================
347
348 /**
349 * 释放Bundle
350 * @param bundleName Bundle名称
351 * @constructor
352 */
353 public ReleaseBundle(bundleName: string) {
354 if (this.bundleCache.has(bundleName)) {
355 let bundleInfo = this.bundleCache.get(bundleName)!;
356 bundleInfo.Bundle?.releaseAll();
357 assetManager.removeBundle(bundleInfo.Bundle!);
358
359 this.DeleteBundleCache(bundleName);
360
361 Framework.Log.Log(`${Framework.Res.Name}_ResourceLoader`, "ReleaseBundle", `释放Bundle: ${bundleName} 成功`);
362 } else {
363 Framework.Log.Error(`${Framework.Res.Name}_ResourceLoader`, "ReleaseBundle", `释放Bundle: ${bundleName} 失败,Bundle不存在`);
364 }
365 }
366
367 /**
368 * 释放所有Bundle
369 * @constructor
370 */
371 public ReleaseAllBundle() {
372 // 释放所有 Bundle
373 this.bundleCache.forEach((info, name) => {
374 info.Bundle?.releaseAll();
375 });
376 this.bundleCache.clear();
377 }
378}
讲解379 行
Bundle 加载器人工通读

ResourceBundleLoader.ts

Bundle 层加载器,维护包名到 ResourceBundleInfo 的缓存,把本地、远程、模拟远程三种模式统一成按路径加载并重试。它决定版本是否覆盖与失败后是否清缓存,Asset 加载器每次加载前都先向它要 Bundle。

先看 LoadBundle 的三段缓存判断,再看三种模式的路径与版本处理,最后看 LoadBundleByPath 与释放方法。

特殊处理与易错点

10注释ResourceBundleLoader:AssetBundle资源加载器
12方法空实现,通用加载器不安装任何专用下载器。
15方法空实现,与 Init 配对,供寻物子类撤销全局下载适配。
18属性包名到 ResourceBundleInfo 的缓存表,LoadBundle 写入,ReleaseBundle
26方法按包名查缓存表,命中返回 Bundle 信息对象,未命中返回空。
39方法创建 Bundle 为空、未下载且无 Promise 的条目写入缓存并返回。
42注释Framework.Log.Error(Framework.Res.Name + " ResourceBundleLoader", "AddBundleCache", `添加Bundle到缓存: ${bundleName}`); 2. 初始化 BundleInfo(防止重复下载)
59方法从缓存表删除指定包名的条目,未命中时不做任何处理。
61注释Framework.Log.Error(Framework.Res.Name + " ResourceBundleLoader", "DeleteBundleCache", `删除Bundle缓存: ${bundleName}`);
65方法通用加载器不推导项目命名规则,任何资源名都返回空。
70方法默认把远程根地址与包名直接拼接,不识别项目目录结构。
75方法默认返回空串,表示不覆盖调用方传入的版本。
80方法通用实现下所有包都返回真,模拟远程模式全部走模拟服务器。
96方法先查缓存与进行中的 Promise,未命中则建条目并按资源模式分流,成功后可选全量预加载。
105注释如果外部没有传入 TraceId,则在这里生成一个新的
111注释1. 检查缓存,已加载直接返回
117注释2. 如果已有加载中的 Promise,则等待同一份结果
124注释3. 新建 BundleInfo 并开始真正的加载流程
128注释远程模式:下载 Bundle
136注释由选用的加载器决定模拟范围,不在通用流程中识别资源名称。
180方法以包名本身作为本地路径,转交统一按路径加载。
191注释这里不再单独打印日志,由 LoadBundleByPath 统一输出
204方法取远程路径与版本,版本非空时复制选项并写入版本后转交按路径加载。
218注释仅在专项版本有效时创建参数副本;其余情况保留调用方 options。
231方法拼模拟服务器地址,若有版本则复制选项并删除 version 后转交加载。
244注释模拟服务不读版本表,不修改调用方选项。
260方法用 DownloadPromise 包住 loadBundle 重试循环,成功写包,失败删缓存。
322方法先释放指定 Bundle,再以空选项重新调用加载。
332方法对 Bundle 根目录调用 preloadDir 预加载全部资源,回调只记录成功或失败。
353方法缓存命中则 releaseAll 并 removeBundle 后删缓存,未命中只打错误日志。
371方法遍历缓存对每个 Bundle 调用 releaseAll,然后清空缓存表。
373注释释放所有 Bundle