From cd019cf805924ca3f6c35ff652f4e5199901dfc5 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 6 Jun 2019 13:34:17 +0800 Subject: [PATCH] CCloader Doc (#4560) --- cocos/load-pipeline/CCLoader.ts | 434 +++++++++++++++++++------------- cocos/load-pipeline/pipeline.js | 78 +++--- 2 files changed, 306 insertions(+), 206 deletions(-) diff --git a/cocos/load-pipeline/CCLoader.ts b/cocos/load-pipeline/CCLoader.ts index e856016c01..107eeb5cb7 100644 --- a/cocos/load-pipeline/CCLoader.ts +++ b/cocos/load-pipeline/CCLoader.ts @@ -24,6 +24,7 @@ THE SOFTWARE. ****************************************************************************/ +import { Asset, RawAsset } from '../assets'; import { createMap, getClassName, isChildClassOf } from '../core/utils/js'; import { callInNextTick } from '../core/utils/misc'; import AssetLoader from './asset-loader'; @@ -45,8 +46,15 @@ function getXMLHttpRequest () { const _info = { url: null, raw: false }; -// Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url -// So we gurantee there will be url in result +/** + * @en + * Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url
+ * So we gurantee there will be url in result + * @zh + * 通过使用 uuid 查找资源的真实 url 来转换资源,否则将使用 uuid 或原始 url 作为其 url
+ * 所以可以保证结果中会有 url + * @param res + */ function getResWithUrl (res) { let id; let result; @@ -81,7 +89,10 @@ const _sharedResources: any = []; const _sharedList: any = []; /** + * @en * Loader for resource loading process. It's a singleton object. + * @zh + * 资源加载程序,这是一个单例对象。 * @class loader * @extends Pipeline * @static @@ -89,15 +100,57 @@ const _sharedList: any = []; class CCLoader extends Pipeline { /** + * @en * Gets a new XMLHttpRequest instance. + * @zh + * 获取一个新的 XMLHttpRequest 的实例。 * @method getXMLHttpRequest * @returns {XMLHttpRequest} */ - public getXMLHttpRequest; + public getXMLHttpRequest: Function; + /** + * @en + * The asset loader in cc.loader's pipeline, it's by default the first pipe.
+ * It's used to identify an asset's type, and determine how to download it. + * @zh + * cc.loader 中的资源加载器,默认情况下是最先加载的。
+ * 用于标识资源的类型,并确定如何加载此资源。 + */ public assetLoader: AssetLoader; + + /** + * @en + * The md5 pipe in cc.loader's pipeline, it could be absent if the project isn't build with md5 option.
+ * It's used to modify the url to the real downloadable url with md5 suffix. + * @zh + * cc.loader 中的 md5 加载管道,如果项目没有使用 md5 构建,则此项可能不存在。
+ * 用于修改带有 md5 后缀的真实可下载的 URL 。 + */ public md5Pipe: null; + + /** + * @en + * The downloader in cc.loader's pipeline, it's by default the second pipe.
+ * It's used to download files with several handlers: pure text, image, script, audio, font, uuid.
+ * You can add your own download function with addDownloadHandlers + * @zh + * cc.loader 中的资源下载程序,默认情况下是第二个加载的。
+ * 它用于下载带有多个处理程序的文件:纯文本,图像,脚本,音频,字体,uuid。
+ * 您可以使用 addDownloadHandlers 来添加自己的下载函数 + */ public downloader: Downloader; + + /** + * @en + * The loader in cc.loader's pipeline, it's by default the third pipe.
+ * It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid.
+ * You can add your own download function with addLoadHandlers + * @zh + * cc.loader 中的资源下载程序,默认情况下是第三个加载的。
+ * 它用于解析下载的内容及多个处理程序的文件:纯文本,图像,脚本,音频,字体,uuid。
+ * 您可以使用 addLoadHandlers 来添加自己的下载函数 + */ public loader: Loader; public onProgress: null; public _assetTables: any; @@ -120,38 +173,12 @@ class CCLoader extends Pipeline { this.getXMLHttpRequest = getXMLHttpRequest; - /** - * The asset loader in cc.loader's pipeline, it's by default the first pipe. - * It's used to identify an asset's type, and determine how to download it. - * @property assetLoader - * @type {Object} - */ this.assetLoader = assetLoader; - /** - * The md5 pipe in cc.loader's pipeline, it could be absent if the project isn't build with md5 option. - * It's used to modify the url to the real downloadable url with md5 suffix. - * @property md5Pipe - * @type {Object} - */ this.md5Pipe = null; - /** - * The downloader in cc.loader's pipeline, it's by default the second pipe. - * It's used to download files with several handlers: pure text, image, script, audio, font, uuid. - * You can add your own download function with addDownloadHandlers - * @property downloader - * @type {Object} - */ this.downloader = downloader; - /** - * The loader in cc.loader's pipeline, it's by default the third pipe. - * It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid. - * You can add your own download function with addLoadHandlers - * @property loader - * @type {Object} - */ this.loader = loader; this.onProgress = null; @@ -175,42 +202,59 @@ class CCLoader extends Pipeline { } /** + * @en * Add custom supported types handler or modify existing type handler for download process. + * @zh + * 为下载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。 * @example + * ```typescript * cc.loader.addDownloadHandlers({ * // This will match all url with `.scene` extension or all url with `scene` type * 'scene' : function (url, callback) {} * }); - * @method addDownloadHandlers - * @param {Object} extMap Custom supported types with corresponded handler + * ``` + * @param extMap 具有相应处理程序的自定义支持类型 */ - public addDownloadHandlers (extMap: any) { + public addDownloadHandlers (extMap: Object) { this.downloader.addHandlers(extMap); } /** + * @en * Add custom supported types handler or modify existing type handler for load process. + * @zh + * 为加载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。 * @example + * ```typescript * cc.loader.addLoadHandlers({ * // This will match all url with `.scene` extension or all url with `scene` type * 'scene' : function (url, callback) {} * }); + * ``` * @method addLoadHandlers - * @param {Object} extMap Custom supported types with corresponded handler + * @param extMap 具有相应处理程序的自定义支持类型 */ - public addLoadHandlers (extMap) { + public addLoadHandlers (extMap: Object) { this.loader.addHandlers(extMap); } // tslint:disable: max-line-length + // load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void + // load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: Function|null): void /** - * Load resources with a progression callback and a complete callback. - * The progression callback is the same as Pipeline's {{#crossLink "LoadingItems/onProgress:method"}}onProgress{{/crossLink}} - * The complete callback is almost the same as Pipeline's {{#crossLink "LoadingItems/onComplete:method"}}onComplete{{/crossLink}} + * @en + * Load resources with a progression callback and a complete callback.
+ * The progression callback is the same as Pipeline's [[LoadingItems.onProgress]]
+ * The complete callback is almost the same as Pipeline's [[LoadingItems.onComplete]]
* The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter. - * + * @zh + * 使用进度回调和完整回调加载资源。
+     * 进度回调与 Pipeline 的 [[LoadingItems.onProgress]] 相同
+     * 完整的回调与 Pipeline 的 [[LoadingItems.onComplete]] 几乎相同
+     * 唯一的区别是当用户将单个 URL 作为资源传递时,完整的回调将其结果直接设置为第二个参数。 * @example + * ```TypeScript * cc.loader.load('a.png', function (err, tex) { * cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); * }); @@ -232,17 +276,14 @@ class CCLoader extends Pipeline { * var aTex = results.getContent('a.png'); * var bJsonObj = results.getContent('b.json'); * }); - * + * ``` * @method load - * @param {String|String[]|Object} resources - Url list in an array - * @param {Function} [progressCallback] - Callback invoked when progression change + * @param {String|String[]|Object} resources - Url 列表数组 + * @param {Function} progressCallback - 当进度改变时调用的回调函数 * @param {Number} progressCallback.completedCount - The number of the items that are already completed * @param {Number} progressCallback.totalCount - The total number of the items * @param {Object} progressCallback.item - The latest item which flow out the pipeline - * @param {Function} [completeCallback] - Callback invoked when all resources loaded - * @typescript - * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void - * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: Function|null): void + * @param {Function} completeCallback - 当所有资源加载完毕后调用的回调函数 */ public load (resources, progressCallback, completeCallback) { if (CC_DEV && !resources) { @@ -306,6 +347,12 @@ class CCLoader extends Pipeline { _sharedResources.length = 0; } + /** + * @en + * See: [[Pipeline.flowInDeps]] + * @zh + * 参考:[[Pipeline.flowInDeps]] + */ public flowInDeps (owner, urlList, callback) { _sharedList.length = 0; // tslint:disable-next-line: prefer-for-of @@ -346,25 +393,37 @@ class CCLoader extends Pipeline { return accepted; } + // @typescript + // loadRes(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void + // loadRes(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any) => void): void + // loadRes(url: string, type: typeof cc.Asset): void + // loadRes(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void + // loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void + // loadRes(url: string): void + /** + * @en * Load resources from the "resources" folder inside the "assets" folder of your project.
*
* Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. - * + * @zh + * 从项目的 “assets” 文件夹下的 “resources” 文件夹中加载资源
+ *
+ * 注意:Creator 中的所有资源 URL 都使用正斜杠,使用反斜杠的 URL 将不起作用。 * @method loadRes - * @param {String} url - Url of the target resource. - * The url is relative to the "resources" folder, extensions must be omitted. - * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. - * @param {Function} [progressCallback] - Callback invoked when progression change. + * @param {String} url - 目标资源的 URL
+ * URl 相对于 “resources” 文件夹,必须省略文件扩展名。 + * @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。 + * @param {Function} progressCallback - 当进度改变时调用的回调函数 * @param {Number} progressCallback.completedCount - The number of the items that are already completed. * @param {Number} progressCallback.totalCount - The total number of the items. * @param {Object} progressCallback.item - The latest item which flow out the pipeline. - * @param {Function} [completeCallback] - Callback invoked when the resource loaded. + * @param {Function} completeCallback - 当所有资源加载完毕后调用的回调函数 * @param {Error} completeCallback.error - The error info or null if loaded successfully. * @param {Object} completeCallback.resource - The loaded resource if it can be found otherwise returns null. * * @example - * + * ```typescript * // load the prefab (project/assets/resources/misc/character/cocos) from resources folder * cc.loader.loadRes('misc/character/cocos', function (err, prefab) { * if (err) { @@ -382,15 +441,9 @@ class CCLoader extends Pipeline { * } * cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame)); * }); - * @typescript - * loadRes(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void - * loadRes(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any) => void): void - * loadRes(url: string, type: typeof cc.Asset): void - * loadRes(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void - * loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void - * loadRes(url: string): void + * ``` */ - public loadRes (url, type, mount, progressCallback, completeCallback) { + public loadRes (url: String, type: Function, mount, progressCallback: Function, completeCallback: Function) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -424,20 +477,32 @@ class CCLoader extends Pipeline { } } + // @typescript + // loadResDir(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void + // loadResDir(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void + // loadResDir(url: string, type: typeof cc.Asset): void + // loadResDir(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void + // loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void + // loadResDir(url: string): void + /** + * @en * Load all assets in a folder inside the "assets/resources" folder of your project.
*
* Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. - * + * @zh + * 将所有资产加载到项目 “assets / resources” 文件夹中 +     *
+ * 注意:Creator 中的所有资源 URL 都使用正斜杠,使用反斜杠的 URL 将不起作用。 * @method loadResDir - * @param {String} url - Url of the target folder. - * The url is relative to the "resources" folder, extensions must be omitted. - * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. - * @param {Function} [progressCallback] - Callback invoked when progression change. + * @param {String} url - 目标文件夹的 URL
+ * URl 相对于 “resources” 文件夹,必须省略文件扩展名。 + * @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。 + * @param {Function} progressCallback - 当进度改变时调用的回调函数 * @param {Number} progressCallback.completedCount - The number of the items that are already completed. * @param {Number} progressCallback.totalCount - The total number of the items. * @param {Object} progressCallback.item - The latest item which flow out the pipeline. - * @param {Function} [completeCallback] - A callback which is called when all assets have been loaded, or an error occurs. + * @param {Function} completeCallback - 当所有资源加载完毕后或者发生错误时调用的回调函数 * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called * with the error. If all assets are loaded successfully, error will be null. * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. @@ -445,7 +510,7 @@ class CCLoader extends Pipeline { * @param {String[]} completeCallback.urls - An array that lists all the URLs of loaded assets. * * @example - * + * ```typescript * // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame * cc.loader.loadResDir('imgs/cocos', function (err, assets) { * if (err) { @@ -467,15 +532,9 @@ class CCLoader extends Pipeline { * var data = objects[0]; * var url = urls[0]; * }); - * @typescript - * loadResDir(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void - * loadResDir(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void - * loadResDir(url: string, type: typeof cc.Asset): void - * loadResDir(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void - * loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void - * loadResDir(url: string): void + * ``` */ - public loadResDir (url, type, mount, progressCallback, completeCallback) { + public loadResDir (url: String, type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -514,27 +573,37 @@ class CCLoader extends Pipeline { }, urls); } + // * @typescript + // * loadResArray(url: string[], type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void + // * loadResArray(url: string[], type: typeof cc.Asset, completeCallback: (error: Error, resource: any[]) => void): void + // * loadResArray(url: string[], type: typeof cc.Asset): void + // * loadResArray(url: string[], progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void + // * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void + // * loadResArray(url: string[]): void /** - * This method is like {{#crossLink "loader/loadRes:method"}}{{/crossLink}} except that it accepts array of url. + * @en + * This method is like [[loadRes]] except that it accepts array of url. + * @zh + * 此方法除了接受 URL 数组参数外,与 [[loadRes]] 方法相同。 * * @method loadResArray - * @param {String[]} urls - Array of URLs of the target resource. - * The url is relative to the "resources" folder, extensions must be omitted. - * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. - * @param {Function} [progressCallback] - Callback invoked when progression change. + * @param {String[]} urls - 目标资源的 URL 数组。 + * URl 为相对于 “resources” 文件夹的,且必须省略文件扩展名。 + * @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。 + * @param {Function} progressCallback - 当进度改变时调用的回调函数 * @param {Number} progressCallback.completedCount - The number of the items that are already completed. * @param {Number} progressCallback.totalCount - The total number of the items. * @param {Object} progressCallback.item - The latest item which flow out the pipeline. - * @param {Function} [completeCallback] - A callback which is called when all assets have been loaded, or an error occurs. + * @param {Function} completeCallback - 当所有资源加载完毕后或者发生错误时调用的回调函数 * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called * with the error. If all assets are loaded successfully, error will be null. * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. * If nothing to load, assets will be an empty array. * @example - * + * ```typescript * // load the SpriteFrames from resources folder - * var spriteFrames; - * var urls = ['misc/characters/character_01', 'misc/weapons/weapons_01']; + * let spriteFrames; + * let urls = ['misc/characters/character_01', 'misc/weapons/weapons_01']; * cc.loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) { * if (err) { * cc.error(err); @@ -543,15 +612,9 @@ class CCLoader extends Pipeline { * spriteFrames = assets; * // ... * }); - * @typescript - * loadResArray(url: string[], type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void - * loadResArray(url: string[], type: typeof cc.Asset, completeCallback: (error: Error, resource: any[]) => void): void - * loadResArray(url: string[], type: typeof cc.Asset): void - * loadResArray(url: string[], progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void - * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void - * loadResArray(url: string[]): void + * ``` */ - public loadResArray (urls, type, mount, progressCallback, completeCallback) { + public loadResArray (urls: String[], type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -580,17 +643,22 @@ class CCLoader extends Pipeline { } /** + * @en * Get resource data by id.
- * When you load resources with {{#crossLink "loader/load:method"}}{{/crossLink}} or {{#crossLink "loader/loadRes:method"}}{{/crossLink}}, + * When you load resources with [[load]] or [[loadRes]], * the url will be the unique identity of the resource. * After loaded, you can acquire them by passing the url to this API. - * + * @zh + * 根据 ID 获取资源数据。
+ * 当使用 [[load]] 或 [[loadRes]] 来加载资源时,
+ * URL 将是资源的唯一标识。
+ * 在完成加载之后,你可以通过将 URL 传递给此 API 来获取它们。 * @method getRes * @param {String} url - * @param {Function} [type] - Only asset of type will be returned if this argument is supplied. + * @param {Function} type - 如果提供此参数,则将仅返回此类型的资源。 * @returns {*} */ - public getRes (url, type) { + public getRes (url: string, type?: Function) { let item = this._cache[url]; if (!item) { const uuid = this._getResUuid(url, type, null, true); @@ -609,43 +677,49 @@ class CCLoader extends Pipeline { } /** + * @en * Get total resources count in loader. - * @returns {Number} + * @zh + * 获取加载的总资源数量 */ public getResCount (): Number { return Object.keys(this._cache).length; } /** - * @en Get all resource dependencies of the requested asset in an array, including itself. + * @en + * Get all resource dependencies of the requested asset in an array, including itself.
* The owner parameter accept the following types: 1. The asset itself; 2. The resource url; 3. The asset's uuid.
- * The returned array stores the dependencies with their uuids, after retrieve dependencies, - * you can release them, access dependent assets by passing the uuid to {{#crossLink "loader/getRes:method"}}{{/crossLink}}, or other stuffs you want.
- * For release all dependencies of an asset, please refer to {{#crossLink "loader/release:method"}}{{/crossLink}} + * The returned array stores the dependencies with their uuids, after retrieve dependencies,
+ * you can release them, access dependent assets by passing the uuid to [[getRes]], or other stuffs you want.
+ * For release all dependencies of an asset, please refer to [[release]] * Here is some examples: - * @zh 获取一个指定资源的所有依赖资源,包含它自身,并保存在数组中返回。owner 参数接收以下几种类型:1. 资源 asset 对象;2. 资源目录下的 url;3. 资源的 uuid。
- * 返回的数组将仅保存依赖资源的 uuid,获取这些 uuid 后,你可以从 loader 释放这些资源;通过 {{#crossLink "loader/getRes:method"}}{{/crossLink}} 获取某个资源或者进行其他你需要的操作。
- * 想要释放一个资源及其依赖资源,可以参考 {{#crossLink "loader/release:method"}}{{/crossLink}}。下面是一些示例代码: - * + * @zh + * 获取一个指定资源的所有依赖资源,包含它自身,并保存在数组中返回。
+ * owner 参数接收以下几种类型:1. 资源 asset 对象;2. 资源目录下的 url;3. 资源的 uuid。
+ * 返回的数组将仅保存依赖资源的 uuid,获取这些 uuid 后,你可以从 loader 释放这些资源;通过 [[getRes]] 获取某个资源或者进行其他你需要的操作。
+ * 想要释放一个资源及其依赖资源,可以参考 [[release]]。
+ * 下面是一些示例代码: * @example + * ```typescript * // Release all dependencies of a loaded prefab - * var deps = cc.loader.getDependsRecursively(prefab); + * let deps = cc.loader.getDependsRecursively(prefab); * cc.loader.release(deps); * // Retrieve all dependent textures - * var deps = cc.loader.getDependsRecursively('prefabs/sample'); - * var textures = []; - * for (var i = 0; i < deps.length; ++i) { - * var item = cc.loader.getRes(deps[i]); + * let deps = cc.loader.getDependsRecursively('prefabs/sample'); + * let textures = []; + * for (let i = 0; i < deps.length; ++i) { + * let item = cc.loader.getRes(deps[i]); * if (item instanceof cc.Texture2D) { * textures.push(item); * } * } - * + * ``` * @method getDependsRecursively - * @param {Asset|RawAsset|String} owner - The owner asset or the resource url or the asset's uuid - * @returns {Array} + * @param {Asset|RawAsset|String} owner - 资源本身或者是资源的 url 或者是资源的 uuid + * @return {Array} */ - public getDependsRecursively (owner) { + public getDependsRecursively (owner: Asset|RawAsset|String) { if (owner) { const key = this._getReferenceKey(owner); const assets = getDependsRecursively(key); @@ -659,37 +733,38 @@ class CCLoader extends Pipeline { /** * @en - * Release the content of an asset or an array of assets by uuid. - * Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content. - * For example, if you release a texture, the texture asset and its gl texture data will be freed up. - * In complexe project, you can use this function with {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} to free up memory in critical circumstances. - * Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors. - * If you only want to remove the cache of an asset, please use {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} + * Release the content of an asset or an array of assets by uuid.
+ * Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content.
+ * For example, if you release a texture, the texture asset and its gl texture data will be freed up.
+ * In complexe project, you can use this function with [[getDependsRecursively]] to free up memory in critical circumstances.
+ * Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors.
+ * If you only want to remove the cache of an asset, please use [[pipeline.removeItem]] * @zh - * 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。 - * 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。 - * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 - * 在复杂项目中,我们建议你结合 {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。 - * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 - * 如果你只想删除一个资源的缓存引用,请使用 {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} + * 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。
+ * 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。
+ * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。
+ * 在复杂项目中,我们建议你结合 [[getDependsRecursively]] 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。
+ * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。
+ * 如果你只想删除一个资源的缓存引用,请使用 [[pipeline.removeItem]] * * @example + * ```typescript * // Release a texture which is no longer need * cc.loader.release(texture); * // Release all dependencies of a loaded prefab - * var deps = cc.loader.getDependsRecursively('prefabs/sample'); + * let deps = cc.loader.getDependsRecursively('prefabs/sample'); * cc.loader.release(deps); * // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up. * // If you have some other nodes share a texture in this prefab, you can skip it in two ways: * // 1. Forbid auto release a texture before release * cc.loader.setAutoRelease(texture2d, false); * // 2. Remove it from the dependencies array - * var deps = cc.loader.getDependsRecursively('prefabs/sample'); - * var index = deps.indexOf(texture2d._uuid); + * let deps = cc.loader.getDependsRecursively('prefabs/sample'); + * let index = deps.indexOf(texture2d._uuid); * if (index !== -1) * deps.splice(index, 1); * cc.loader.release(deps); - * + * ``` * @method release * @param {Asset|RawAsset|String|Array} asset */ @@ -721,13 +796,13 @@ class CCLoader extends Pipeline { } /** - * @en Release the asset by its object. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * @zh 通过资源对象自身来释放资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * @en Release the asset by its object. Refer to [[release]] for detailed informations. + * @zh 通过资源对象自身来释放资源。详细信息请参考 [[release]] * * @method releaseAsset * @param {Asset} asset */ - public releaseAsset (asset) { + public releaseAsset (asset: Asset) { const uuid = asset._uuid; if (uuid) { this.release(uuid); @@ -735,14 +810,16 @@ class CCLoader extends Pipeline { } /** - * @en Release the asset loaded by {{#crossLink "loader/loadRes:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * @zh 释放通过 {{#crossLink "loader/loadRes:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * @en + * Release the asset loaded by [[loadRes]]. Refer to [[release]] for detailed informations. + * @zh + * 释放通过 [[loadRes]] 加载的资源。详细信息请参考 [[release]] * * @method releaseRes * @param {String} url - * @param {Function} [type] - Only asset of type will be released if this argument is supplied. + * @param {Function} type - 如果提供此参数,则将仅释放此类型的资源。 */ - public releaseRes (url, type, mount) { + public releaseRes (url: String, type?: Function, mount?) { const uuid = this._getResUuid(url, type, mount, true); if (uuid) { this.release(uuid); @@ -753,14 +830,16 @@ class CCLoader extends Pipeline { } /** - * @en Release the all assets loaded by {{#crossLink "loader/loadResDir:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * @zh 释放通过 {{#crossLink "loader/loadResDir:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * @en + * Release the all assets loaded by [[loadResDir]]. Refer to [[release]] for detailed informations. + * @zh + * 释放通过 [[loadResDir]] 加载的资源。详细信息请参考 [[release]] * * @method releaseResDir * @param {String} url - * @param {Function} [type] - Only asset of type will be released if this argument is supplied. + * @param {Function} type - 如果提供此参数,则将仅释放此类型的资源。 */ - public releaseResDir (url, type, mount) { + public releaseResDir (url: String, type?: Function, mount?) { mount = mount || 'assets'; if (!assetTables[mount]) { return; } @@ -772,8 +851,8 @@ class CCLoader extends Pipeline { } /** - * @en Resource all assets. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * @zh 释放所有资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * @en Resource all assets. Refer to [[release]] for detailed informations. + * @zh 释放所有资源。详细信息请参考 [[release]] * * @method releaseAll */ @@ -795,34 +874,35 @@ class CCLoader extends Pipeline { /** * @en * Indicates whether to release the asset when loading a new scene.
- * By default, when loading a new scene, all assets in the previous scene will be released or preserved - * according to whether the previous scene checked the "Auto Release Assets" option. - * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` + * By default, when loading a new scene, all assets in the previous scene will be released or preserved
+ * according to whether the previous scene checked the "Auto Release Assets" option.
+ * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir`
* will not be affected by that option, remain not released by default.
* Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.
*
- * See: {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * See: [[setAutoReleaseRecursively]], [[isAutoRelease]] * @zh * 设置当场景切换时是否自动释放资源。
- * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 + * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
* 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
* 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
*
- * 参考:{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * 参考:[[setAutoReleaseRecursively]],[[isAutoRelease]] * * @example + * ```typescript * // auto release the texture event if "Auto Release Assets" disabled in current scene * cc.loader.setAutoRelease(texture2d, true); * // don't release the texture even if "Auto Release Assets" enabled in current scene * cc.loader.setAutoRelease(texture2d, false); * // first parameter can be url * cc.loader.setAutoRelease(audioUrl, false); - * + * ``` * @method setAutoRelease - * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid - * @param {Boolean} autoRelease - indicates whether should release automatically + * @param {Asset|String} assetOrUrlOrUuid - 资源对象或原始资源的 URL 或是 UUID + * @param {Boolean} autoRelease - 表示是否自动释放 */ - public setAutoRelease (assetOrUrlOrUuid, autoRelease) { + public setAutoRelease (assetOrUrlOrUuid: Asset|String, autoRelease: Boolean) { const key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { this._autoReleaseSetting[key] = !!autoRelease; @@ -835,34 +915,35 @@ class CCLoader extends Pipeline { /** * @en * Indicates whether to release the asset and its referenced other assets when loading a new scene.
- * By default, when loading a new scene, all assets in the previous scene will be released or preserved - * according to whether the previous scene checked the "Auto Release Assets" option. - * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` + * By default, when loading a new scene, all assets in the previous scene will be released or preserved
+ * according to whether the previous scene checked the "Auto Release Assets" option.
+ * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir`
* will not be affected by that option, remain not released by default.
* Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.
*
- * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * See: [[setAutoRelease]], [[isAutoRelease]] * @zh * 设置当场景切换时是否自动释放资源及资源引用的其它资源。
- * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 + * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
* 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
* 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
*
- * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * 参考:[[setAutoRelease]],[[isAutoRelease]] * * @example + * ```typescript * // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene * cc.loader.setAutoReleaseRecursively(spriteFrame, true); * // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene * cc.loader.setAutoReleaseRecursively(spriteFrame, false); * // don't release the Prefab and all the referenced assets * cc.loader.setAutoReleaseRecursively(prefab, false); - * + * ``` * @method setAutoReleaseRecursively - * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid - * @param {Boolean} autoRelease - indicates whether should release automatically + * @param {Asset|String} assetOrUrlOrUuid - 资源对象或原始资源的 URL 或是 UUID + * @param {Boolean} autoRelease - 表示是否自动释放 */ - public setAutoReleaseRecursively (assetOrUrlOrUuid, autoRelease) { + public setAutoReleaseRecursively (assetOrUrlOrUuid: Asset|String, autoRelease: Boolean) { autoRelease = !!autoRelease; const key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { @@ -883,17 +964,17 @@ class CCLoader extends Pipeline { * @en * Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
*
- * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} + * See: [[setAutoRelease]], [[setAutoReleaseRecursively]] * * @zh * 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
*
- * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} + * 参考:[[setAutoRelease]],[[setAutoReleaseRecursively]] * @method isAutoRelease * @param {Asset|String} assetOrUrl - asset object or the raw asset's url * @returns {Boolean} */ - public isAutoRelease (assetOrUrl) { + public isAutoRelease (assetOrUrl: Asset|String): Boolean{ const key = this._getReferenceKey(assetOrUrl); if (key) { return !!this._autoReleaseSetting[key]; @@ -901,6 +982,10 @@ class CCLoader extends Pipeline { return false; } + /** + * @zh + * 获取资源的 uuid + */ public _getResUuid (url, type, mount, quiet) { mount = mount || 'assets'; const assetTable = assetTables[mount]; @@ -927,8 +1012,13 @@ class CCLoader extends Pipeline { return uuid; } - // Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url - private _getReferenceKey (assetOrUrlOrUuid) { + /** + * @en + * Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url + * @zh + * 在 laoder 中找到资源的引用 id ,参数可以是资源对象、资源的 uuid 或者是资源的 url + */ + public _getReferenceKey (assetOrUrlOrUuid) { let key; if (typeof assetOrUrlOrUuid === 'object') { key = assetOrUrlOrUuid._uuid || null; @@ -944,6 +1034,10 @@ class CCLoader extends Pipeline { return this._cache[_info.url!] ? _info.url : key; } + /** + * @zh + * 当 url 未找到时的操作 + */ private _urlNotFound (url, type, completeCallback) { callInNextTick(() => { url = cc.url.normalize(url); @@ -989,6 +1083,10 @@ class CCLoader extends Pipeline { }; } + /** + * @zh + * 通过uuids 加载资源 + */ private _loadResUuids (uuids, progressCallback, completeCallback, urls ?) { if (uuids.length > 0) { const self = this; diff --git a/cocos/load-pipeline/pipeline.js b/cocos/load-pipeline/pipeline.js index 3d6c0bcd51..7b39ac3f6e 100644 --- a/cocos/load-pipeline/pipeline.js +++ b/cocos/load-pipeline/pipeline.js @@ -91,14 +91,14 @@ function flow (pipe, item) { } /** - * !#en + * @en * A pipeline describes a sequence of manipulations, each manipulation is called a pipe.
* It's designed for loading process. so items should be urls, and the url will be the identity of each item during the process.
* A list of items can flow in the pipeline and it will output the results of all pipes.
* They flow in the pipeline like water in tubes, they go through pipe by pipe separately.
* Finally all items will flow out the pipeline and the process is finished. * - * !#zh + * @zh * pipeline 描述了一系列的操作,每个操作都被称为 pipe。
* 它被设计来做加载过程的流程管理。所以 item 应该是 url,并且该 url 将是在处理中的每个 item 的身份标识。
* 一个 item 列表可以在 pipeline 中流动,它将输出加载项经过所有 pipe 之后的结果。
@@ -110,13 +110,13 @@ export default class Pipeline { static ItemState = ItemState; /** - * !#en + * @en * Constructor, pass an array of pipes to construct a new Pipeline, * the pipes will be chained in the given order.
* A pipe is an object which must contain an `id` in string and a `handle` function, * the id must be unique in the pipeline.
* It can also include `async` property to identify whether it's an asynchronous process. - * !#zh + * @zh * 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。
* 一个 pipe 就是一个对象,它包含了字符串类型的 ‘id’ 和 ‘handle’ 函数,在 pipeline 中 id 必须是唯一的。
* 它还可以包括 ‘async’ 属性以确定它是否是一个异步过程。 @@ -150,10 +150,10 @@ export default class Pipeline { } /** - * !#en + * @en * Insert a new pipe at the given index of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. - * !#zh + * @zh * 在给定的索引位置插入一个新的 pipe。
* 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 * @method insertPipe @@ -193,9 +193,9 @@ export default class Pipeline { } /** - * !en + * @en * Insert a pipe to the end of an existing pipe. The existing pipe must be a valid pipe in the pipeline. - * !zh + * @zh * 在当前 pipeline 的一个已知 pipe 后面插入一个新的 pipe。 * @method insertPipeAfter * @param {Object} refPipe An existing pipe in the pipeline. @@ -210,10 +210,10 @@ export default class Pipeline { } /** - * !#en + * @en * Add a new pipe at the end of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. - * !#zh + * @zh * 添加一个新的 pipe 到 pipeline 尾部。
* 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 * @method appendPipe @@ -234,14 +234,14 @@ export default class Pipeline { } /** - * !#en + * @en * Let new items flow into the pipeline.
* Each item can be a simple url string or an object, * if it's an object, it must contain `id` property.
* You can specify its type by `type` property, by default, the type is the extension name in url.
* By adding a `skips` property including pipe ids, you can skip these pipe.
* The object can contain any supplementary property as you want.
- * !#zh + * @zh * 让新的 item 流入 pipeline 中。
* 这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象, * 如果它是一个对象的话,他必须要包含 ‘id’ 属性。
@@ -251,6 +251,7 @@ export default class Pipeline { * @method flowIn * @param {Array} items * @example + * ``` * pipeline.flowIn([ * 'res/Background.png', * { @@ -260,6 +261,7 @@ export default class Pipeline { * skips: ['Downloader'] * } * ]); + * ``` */ flowIn (items) { var i, pipe = this._pipes[0], item; @@ -281,24 +283,24 @@ export default class Pipeline { } } - /* - * !#en - * Let new items flow into the pipeline and give a callback when the list of items are all completed.
- * This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
- * For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
- * after all its dependencies are loaded, then you will need to use function to flow in all dependencies
- * found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback). - * !#zh - * 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。
- * 这个 API 的使用通常是为了加载依赖项。
- * 例如:
- * 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 - * @method flowInDeps - * @deprecated since v1.3 - * @param {Array} urlList - * @param {Function} callback - * @return {Array} Items accepted by the pipeline - */ + /** + * @en + * Let new items flow into the pipeline and give a callback when the list of items are all completed.
+ * This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
+ * For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
+ * after all its dependencies are loaded, then you will need to use function to flow in all dependencies
+ * found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback). + * @zh + * 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。
+ * 这个 API 的使用通常是为了加载依赖项。
+ * 例如:
+ * 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 + * @method flowInDeps + * @deprecated since v1.3 + * @param {Array} urlList + * @param {Function} callback + * @return {Array} Items accepted by the pipeline + */ flowInDeps (owner, urlList, callback) { var deps = LoadingItems.create(this, function (errors, items) { callback(errors, items); @@ -319,7 +321,7 @@ export default class Pipeline { } /** - * !#en + * @en * Copy the item states from one source item to all destination items.
* It's quite useful when a pipe generate new items from one source item,
* then you should flowIn these generated items into pipeline,
@@ -327,7 +329,7 @@ export default class Pipeline { * you can achieve it with this API.
*
* For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again. - * !#zh + * @zh * 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。
* 当一个源 item 生成了一系列新的 items 时很有用,
* 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,
@@ -348,8 +350,8 @@ export default class Pipeline { } /** - * !#en Returns an item in pipeline. - * !#zh 根据 id 获取一个 item + * @en Returns an item in pipeline. + * @zh 根据 id 获取一个 item * @method getItem * @param {Object} id The id of the item * @return {Object} @@ -368,11 +370,11 @@ export default class Pipeline { } /** - * !#en Removes an completed item in pipeline. + * @en Removes an completed item in pipeline. * It will only remove the cache in the pipeline or loader, its dependencies won't be released. * cc.loader provided another method to completely cleanup the resource and its dependencies, * please refer to {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} - * !#zh 移除指定的已完成 item。 + * @zh 移除指定的已完成 item。 * 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。 * cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} * @method removeItem @@ -400,8 +402,8 @@ export default class Pipeline { } /** - * !#en Clear the current pipeline, this function will clean up the items. - * !#zh 清空当前 pipeline,该函数将清理 items。 + * @en Clear the current pipeline, this function will clean up the items. + * @zh 清空当前 pipeline,该函数将清理 items。 * @method clear */ clear () {