Merge branch 'v3.7.2' into develop

# Conflicts:
#	cocos/core/global-exports.ts
#	cocos/core/math/quat.ts
#	native/cocos/cocos-version.h
#	package.json
This commit is contained in:
pandamicro
2023-02-13 18:00:41 +08:00
443 changed files with 15846 additions and 8597 deletions
+4 -3
View File
@@ -26,6 +26,10 @@ jobs:
# Checks out a copy of your repository on the ubuntu-latest machine
- name: Checkout code
uses: actions/checkout@v2
- name: Install CMake & Clang Tidy
run: |
sudo apt update --fix-missing
sudo apt install -y cmake llvm clang-tidy-11
- name: Download external
run: |
EXT_VERSION=`node ./.github/workflows/get-native-external-version.js`
@@ -71,9 +75,6 @@ jobs:
skipedDebug:
- added|modified|deleted: '**'
- exclude: 'native/cocos/editor-support/**'
- name: Install CMake & Clang Tidy
run: |
sudo apt install -y cmake llvm clang-tidy-11
- name: Generate Compile database
shell: bash
+9 -1
View File
@@ -1939,6 +1939,10 @@ Can not add a page without UITransform.
Can not set the scroll view content when it hasn't UITransform or its parent hasn't UITransform.
### 4303
The %s scrollBar on the '%s' node is not available, please check it.
### 4400
Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas!
@@ -3323,4 +3327,8 @@ The asset replacing failed, can not found override asset('%s') for '%s'
### 16301
node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first
node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first
### 16302
There is no reflection probe in the scene or no probe is near the current object. No reflection probe will take effect on this object. Please create a new reflection probe or move existing ones closer.
@@ -27,8 +27,6 @@ import { IAssemblerManager } from '../../../renderer/base';
import { Graphics } from '../../../components';
import { graphicsAssembler as graphics } from './graphics-assembler';
export { earcut } from './earcut';
const graphicsAssemblerManager: IAssemblerManager = {
getAssembler (sprite: UIRenderer) {
return graphics;
-2
View File
@@ -26,7 +26,6 @@ import { BitmapFont } from '../../assets';
import { Label } from '../../components';
import { IAssemblerManager } from '../../renderer/base';
import { bmfont } from './bmfont';
import { CanvasPool } from './font-utils';
import { letter } from './letter';
import { ttf } from './ttf';
@@ -54,7 +53,6 @@ export {
ttf,
bmfont,
letter,
CanvasPool,
};
Label.Assembler = labelAssembler;
+10 -10
View File
@@ -23,7 +23,7 @@
*/
import { JSB } from 'internal:constants';
import { IUV, SpriteFrame } from '../../assets';
import { IUV, SpriteFrame } from '../../assets/sprite-frame';
import { Mat4, Vec3, Color } from '../../../core';
import { IRenderData, RenderData } from '../../renderer/render-data';
import { IBatcher } from '../../renderer/i-batcher';
@@ -34,13 +34,13 @@ import { StaticVBChunk } from '../../renderer/static-vb-accessor';
const m = new Mat4();
let origin:IUV;
let leftInner:IUV;
let rightInner:IUV;
let rightOuter:IUV;
let bottomInner:IUV;
let topInner:IUV;
let topOuter:IUV;
let origin: IUV;
let leftInner: IUV;
let rightInner: IUV;
let rightOuter: IUV;
let bottomInner: IUV;
let topInner: IUV;
let topOuter: IUV;
let tempRenderDataLength = 0;
const tempRenderData: IRenderData[] = [];
let QUAD_INDICES;
@@ -357,8 +357,8 @@ export const tiled: IAssembler = {
let coefV = 0;
const hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
const vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
const tempXVerts :any = [];
const tempYVerts :any = [];
const tempXVerts: any = [];
const tempYVerts: any = [];
for (let yIndexUV = 0; yIndexUV < row; ++yIndexUV) {
if (sizableHeight > centerHeight) {
+9 -3
View File
@@ -102,19 +102,22 @@ export class FontAtlas {
*/
@ccclass('cc.BitmapFont')
export class BitmapFont extends Font {
/**
* @deprecated since v3.7.0, Useless Code.
*/
@serializable
@editable
public fntDataStr = '';
/**
* @en [[SpriteFrame]] of the bitmap font
* @en [[SpriteFrame]] of the bitmap font.
* @zh 位图字体所使用的精灵。
*/
@type(SpriteFrame)
public spriteFrame: SpriteFrame | null = null;
/**
* @en The font size
* @en The font size.
* @zh 文字尺寸。
*/
@serializable
@@ -122,13 +125,16 @@ export class BitmapFont extends Font {
public fontSize = -1;
/**
* @en Font configuration
* @en Font configuration.
* @zh 字体配置。
*/
@serializable
@editable
public fntConfig: IConfig | null = null;
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public declare fontDefDictionary: FontAtlas;
onLoaded () {
-2
View File
@@ -22,8 +22,6 @@
THE SOFTWARE.
*/
export * from './sprite-frame';
export { SpriteAtlas } from './sprite-atlas';
export { TTFFont } from './ttf-font';
+9 -5
View File
@@ -46,14 +46,18 @@ interface ISpriteFrameList {
*/
@ccclass('cc.SpriteAtlas')
export class SpriteAtlas extends Asset {
/**
* @en All sprite frames in the sprite atlas.
* @zh 精灵图集中的所有精灵。
*/
@serializable
@editable
public spriteFrames: ISpriteFrameList = js.createMap();
/**
* @en Get the [[Texture2D]] asset of the atlas.
* @zh 获取精灵图集的贴图。请注意,由于结构调整优化,在 v1.1 版本之前,此函数的返回值为 imageAsset,在 v1.1 版本之后修正为 texture,想要获取 imageAsset 可使用 getTexture().image 获取
* @returns The texture2d asset
* @zh 获取精灵图集的贴图。
* @returns @en The texture2d asset. @zh 二维贴图资源。
*/
public getTexture () {
const keys = Object.keys(this.spriteFrames);
@@ -69,8 +73,8 @@ export class SpriteAtlas extends Asset {
* @en Gets the [[SpriteFrame]] correspond to the given key in sprite atlas.
* @zh 根据键值获取精灵。
*
* @param key The SpriteFrame name
* @returns The SpriteFrame asset
* @param key @en The SpriteFrame name. @zh 精灵名字。
* @returns @en The SpriteFrame asset. @zh 精灵资源。
*/
public getSpriteFrame (key: string) {
const sf = this.spriteFrames[key];
@@ -86,7 +90,7 @@ export class SpriteAtlas extends Asset {
/**
* @en Returns all sprite frames in the sprite atlas.
* @zh 获取精灵图集所有精灵。
* @returns All sprite frames
* @returns @en All sprite frames. @zh 所有的精灵资源。
*/
public getSpriteFrames () {
const frames: Array<SpriteFrame | null> = [];
+125 -73
View File
@@ -50,6 +50,9 @@ enum MeshType {
POLYGON = 1, // Todo: Polygon mode need add
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
export interface IUV {
u: number;
v: number;
@@ -99,22 +102,22 @@ interface ISpriteFrameOriginal {
}
/**
* @en Information object interface for initialize a [[SpriteFrame]] asset
* @zh 用于初始化 [[SpriteFrame]] 资源的对象接口描述
* @en Information object interface for initialize a [[SpriteFrame]] asset.
* @zh 用于初始化 [[SpriteFrame]] 资源的对象接口描述。
*/
interface ISpriteFrameInitInfo {
/**
* @en The texture of the sprite frame, could be `TextureBase`
* @zh 贴图对象资源,可以是 `TextureBase` 类型
* @en The texture of the sprite frame, could be `TextureBase`.
* @zh 贴图对象资源,可以是 `TextureBase` 类型。
*/
texture?: TextureBase;
/**
* @en The original size of the sprite frame
* @en The original size of the sprite frame.
* @zh 精灵帧原始尺寸。
*/
originalSize?: Size;
/**
* @en The rect of the sprite frame in atlas texture
* @en The rect of the sprite frame in atlas texture.
* @zh 精灵帧裁切矩形。
*/
rect?: Rect;
@@ -156,7 +159,7 @@ interface ISpriteFrameInitInfo {
*/
isRotate?: boolean;
/**
* @en Whether the uv is flipped
* @en Whether the uv is flipped.
* @zh 是否转置 UV。
*/
isFlipUv?: boolean;
@@ -166,17 +169,17 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0,
/**
* @en
* A `SpriteFrame` support several types
* A `SpriteFrame` support several types.
* 1. Rectangle sprite frame
* 2. Sliced 9 sprite frame
* 3. Mesh sprite frame
* It mainly contains:<br/>
* - texture: A `TextureBase` that will be used by render process<br/>
* - rectangle: A rectangle of the texture
* - Sliced 9 border insets: The distance of each side from the internal rect to the sprite frame rect
* - vertices: Vertex list for the mesh type sprite frame
* - uv: The quad uv
* - uvSliced: The sliced 9 uv
* - texture: A `TextureBase` that will be used by render process.<br/>
* - rectangle: A rectangle of the texture.
* - Sliced 9 border insets: The distance of each side from the internal rect to the sprite frame rect.
* - vertices: Vertex list for the mesh type sprite frame.
* - uv: The quad uv.
* - uvSliced: The sliced 9 uv.
*
* @zh
* 精灵帧资源。
@@ -187,10 +190,10 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0,
* 它主要包含下列数据:<br/>
* - 纹理:会被渲染流程使用的 `TextureBase` 资源。<br/>
* - 矩形:在纹理中的矩形区域。
* - 九宫格信息:九宫格的内部矩形四个边距离 SpriteFrame 外部矩形的距离
* - 网格信息:网格类型精灵帧的所有顶点列表
* - uv: 四边形 UV
* - uvSliced: 九宫格 UV
* - 九宫格信息:九宫格的内部矩形四个边距离 SpriteFrame 外部矩形的距离。
* - 网格信息:网格类型精灵帧的所有顶点列表。
* - uv: 四边形 UV。
* - uvSliced: 九宫格 UV。
* 可通过 `SpriteFrame` 获取该组件。
*
* @example
@@ -240,9 +243,11 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0,
@ccclass('cc.SpriteFrame')
export class SpriteFrame extends Asset {
/**
* @en Create a SpriteFrame object by an image asset or an native image asset
* @zh 通过 Image 资源或者平台相关 Image 对象创建一个 SpriteFrame 对象
* @param imageSourceOrImageAsset ImageAsset or ImageSource, ImageSource support HTMLCanvasElement HTMLImageElement IMemoryImageSource
* @en Create a SpriteFrame object by an image asset or an native image asset.
* @zh 通过 Image 资源或者平台相关 Image 对象创建一个 SpriteFrame 资源。
* @param imageSourceOrImageAsset @en ImageAsset or ImageSource, ImageSource could be HTMLCanvasElement, HTMLImageElement, IMemoryImageSource.
* @zh 图像资源或图像原始图像源,图像原始图像源支持 HTMLCanvasElement HTMLImageElement IMemoryImageSource 三种资源。
* @returns @en SpriteFrame asset. @zh 精灵资源。
*/
public static createWithImage (imageSourceOrImageAsset: ImageSource | ImageAsset) {
const img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset);
@@ -254,8 +259,8 @@ export class SpriteFrame extends Asset {
}
/**
* @en uv update event
* @zh uv 更新事件
* @en uv update event.
* @zh uv 更新事件。
*/
public static EVENT_UV_UPDATED = 'uv_updated';
public static MeshType = MeshType;
@@ -414,8 +419,8 @@ export class SpriteFrame extends Asset {
}
/**
* @en The texture of the sprite frame, could be `TextureBase`
* @zh 贴图对象资源,可以是 `TextureBase` 类型
* @en The texture of the sprite frame, could be `TextureBase`.
* @zh 贴图对象资源,可以是 `TextureBase` 类型。
*/
get texture () {
return this._texture;
@@ -435,7 +440,7 @@ export class SpriteFrame extends Asset {
}
/**
* @en The uuid of the atlas asset, if exist
* @en The uuid of the atlas asset, if exists.
* @zh 图集资源的 uuid。
*/
get atlasUuid () {
@@ -447,21 +452,24 @@ export class SpriteFrame extends Asset {
}
/**
* @en The pixel width of the sprite frame
* @zh 精灵帧的像素宽度
* @en The pixel width of the sprite frame.
* @zh 精灵帧的像素宽度。
*/
get width () {
return this._texture.width;
}
/**
* @en The pixel height of the sprite frame
* @zh 精灵帧的像素高度
* @en The pixel height of the sprite frame.
* @zh 精灵帧的像素高度。
*/
get height () {
return this._texture.height;
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
set _textureSource (value: TextureBase) {
// Optimization for build
if (globalThis.Build) {
@@ -475,8 +483,8 @@ export class SpriteFrame extends Asset {
}
/**
* @en Whether flip the uv in X direction
* @zh 延 X 轴方向, 翻转 UV
* @en Whether flip the uv in X direction.
* @zh 沿 X 轴方向, 翻转 UV。
*/
get flipUVX () {
return this._isFlipUVX;
@@ -488,8 +496,8 @@ export class SpriteFrame extends Asset {
}
/**
* @en Whether flip the uv in Y direction
* @zh 延 Y 轴方向, 翻转 UV
* @en Whether flip the uv in Y direction.
* @zh 沿 Y 轴方向, 翻转 UV。
*/
get flipUVY () {
return this._isFlipUVY;
@@ -500,6 +508,10 @@ export class SpriteFrame extends Asset {
this._calculateUV();
}
/**
* @en Sets whether sprite can be packed into dynamic atlas.
* @zh 设置精灵是否允许参与自动合图。
*/
get packable () {
return this._packable;
}
@@ -507,57 +519,64 @@ export class SpriteFrame extends Asset {
this._packable = value;
}
/**
* @en Original information before packed to dynamic atlas, includes texture, width, height. It's null before being packed to dynamic atlas.
* @zh 精灵自动合图之前的原始 texture 和宽高信息。在参与自动合图之前此值为 null。
*/
get original () {
return this._original;
}
/**
* @en Number of pixels corresponding to unit size in world space (pixels per meter)
* @zh 世界空间中的单位大小对应的像素数量(像素每米)
* @en Number of pixels corresponding to unit size in world space (pixels per unit).
* @zh 世界空间中的单位大小对应的像素数量(像素每单位)。
*/
get pixelsToUnit () {
return this._pixelsToUnit;
}
/**
* @en Local origin position when generating the mesh
* @zh 生成 mesh 时本地坐标原点位置
* @en Local origin position when generating the mesh.
* @zh 生成 mesh 时本地坐标原点位置。
*/
get pivot () {
return this._pivot;
}
/**
* @en mesh information, you should call the [[ensureMeshData]] function before using it
* @zh mesh 信息,你应该在使用它之前调用 [[ensureMeshData]] 函数来确保其可用
* @en mesh information, you should call the [[ensureMeshData]] function before using it.
* @zh mesh 信息,你应该在使用它之前调用 [[ensureMeshData]] 函数来确保其可用。
*/
get mesh () {
return this._mesh;
}
/**
* @internal
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get trimmedBorder () {
return this._trimmedBorder;
}
/**
* @en Vertex list for the mesh type sprite frame
* @zh 网格类型精灵帧的所有顶点列表
* @en Vertex list for the mesh type sprite frame.
* @zh 网格类型精灵帧的所有顶点列表。
*/
public vertices: IVertices | null = null;
/**
* @en UV for quad vertices
* @zh 矩形的顶点 UV
* @en UV for quad vertices.
* @zh 矩形的顶点 UV。
*/
public uv: number[] = [];
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public unbiasUV: number[] = [];
/**
* @en UV for sliced 9 vertices
* @en UV for sliced 9 vertices.
* @zh 九宫格的顶点 UV。
*/
public uvSliced: IUV[] = [];
@@ -631,7 +650,7 @@ export class SpriteFrame extends Asset {
* @zh
* 返回是否已加载精灵帧。
*
* @deprecated since v3.3
* @deprecated since v3.3, Useless Code.
*/
public textureLoaded () {
return !!this.texture;
@@ -642,7 +661,7 @@ export class SpriteFrame extends Asset {
* Returns whether the sprite frame is rotated in the texture.
* @zh
* 获取 SpriteFrame 是否旋转。
* @deprecated since v1.2, please use [[rotated]] instead
* @deprecated since v1.2, please use [[rotated]] instead.
*/
public isRotated () {
return this._rotated;
@@ -653,8 +672,8 @@ export class SpriteFrame extends Asset {
* Set whether the sprite frame is rotated in the texture.
* @zh
* 设置 SpriteFrame 是否旋转。
* @param value
* @deprecated since v1.2, please use [[rotated]] instead
* @param rotated @en rotated. @zh 是否旋转。
* @deprecated since v1.2, please use [[rotated]] instead.
*/
public setRotated (rotated: boolean) {
this.rotated = rotated;
@@ -665,7 +684,9 @@ export class SpriteFrame extends Asset {
* If it's an atlas texture, a transparent pixel area is proposed for the actual mapping of the current texture.
* @zh 获取 SpriteFrame 的纹理矩形区域。
* 如果是一个 atlas 的贴图,则为当前贴图的实际剔除透明像素区域。
* @deprecated since v1.2, please use [[rect]]
* @param out @en The output rect. @zh 输出的矩形区域。
* @returns @en The rect. @zh 矩形区域。
* @deprecated since v1.2, please use [[rect]].
*/
public getRect (out?: Rect) {
if (out) {
@@ -679,7 +700,8 @@ export class SpriteFrame extends Asset {
/**
* @en Sets the rect of the sprite frame in the texture.
* @zh 设置 SpriteFrame 的纹理矩形区域。
* @deprecated since v1.2, please use [[rect]]
* @param rect @en The new rect. @zh 想要设置的 rect。
* @deprecated since v1.2, please use [[rect]].
*/
public setRect (rect: Rect) {
this.rect = rect;
@@ -688,7 +710,9 @@ export class SpriteFrame extends Asset {
/**
* @en Returns the original size before trimmed.
* @zh 获取修剪前的原始大小。
* @deprecated since v1.2, please use [[originalSize]]
* @param out @en The output original size. @zh 输出的原始大小。
* @returns @en The original size. @zh 原始大小。
* @deprecated since v1.2, please use [[originalSize]].
*/
public getOriginalSize (out?: Size) {
if (out) {
@@ -702,17 +726,18 @@ export class SpriteFrame extends Asset {
/**
* @en Sets the original size before trimmed.
* @zh 设置修剪前的原始大小。
* @param size The new original size
* @deprecated since v1.2, please use [[originalSize]]
* @param size @en The new original size. @zh 新设置的原始大小。
* @deprecated since v1.2, please use [[originalSize]].
*/
public setOriginalSize (size: Size) {
this.originalSize = size;
}
/**
* @en Returns the offset of the frame
* @en Gets the offset of the frame.
* @zh 获取偏移量。
* @param out The output offset object
* @param out @en The output offset object. @zh 输出的偏移量。
* @returns @en The offset object. @zh 偏移量。
* @deprecated since v1.2, please use [[offset]]
*/
public getOffset (out?: Vec2) {
@@ -725,9 +750,9 @@ export class SpriteFrame extends Asset {
}
/**
* @en Sets the offset of the frame
* @en Sets the offset of the frame.
* @zh 设置偏移量。
* @param offset The new offset
* @param offset @en The new offset. @zh 新设置的偏移量。
* @deprecated since v1.2, please use [[offset]]
*/
public setOffset (offset: Vec2) {
@@ -735,41 +760,46 @@ export class SpriteFrame extends Asset {
}
/**
* @en Gets the related GFX [[gfx.Texture]] resource
* @zh 获取渲染贴图的 GFX 资源
* @en Gets the related GFX [[gfx.Texture]] resource.
* @zh 获取渲染贴图的 GFX 资源。
* @returns @en Gfx Texture resource. @zh GFX 贴图资源。
*/
public getGFXTexture () {
return this._texture.getGFXTexture();
}
/**
* @en Gets the sampler resource of its texture
* @zh 贴图资源的采样器
* @en Gets the GFX sampler of its texture.
* @zh 贴图资源的采样器。
* @returns @en The GFX sampler resource. @zh GFX贴图采样器。
*/
public getGFXSampler () {
return this._texture.getGFXSampler();
}
/**
* @en Gets the hash of its texture
* @zh 贴图资源的哈希值
* @en Gets the hash of its texture.
* @zh 贴图资源的哈希值。
* @returns @en Texture`s hash. @zh 贴图哈希值。
*/
public getHash () {
return this._texture.getHash();
}
/**
* @en Gets the sampler hash of its texture
* @zh 贴图资源的采样器哈希值
* @en Gets the sampler hash of its texture.
* @zh 贴图资源的采样器哈希值。
* @returns @en Sampler`s hash. @zh 采样器哈希值。
*/
public getSamplerInfo () {
return this._texture.getSamplerInfo();
}
/**
* @en Resets the sprite frame data
* @en Resets the sprite frame data.
* @zh 重置 SpriteFrame 数据。
* @param info SpriteFrame initialization information
* @param info @en SpriteFrame initialization information. @zh SpriteFrame 初始化信息。
* @param clearData @en Clear Data before initialization. @zh 是否在初始化前清空原有数据。
*/
public reset (info?: ISpriteFrameInitInfo, clearData = false) {
let calUV = false;
@@ -837,9 +867,10 @@ export class SpriteFrame extends Asset {
}
/**
* @en Check whether the rect of the sprite frame is out of the texture boundary
* @en Check whether the rect of the sprite frame is out of the texture boundary.
* @zh 判断精灵计算的矩形区域是否越界。
* @param texture
* @param texture @en Texture resources for sprite frame. @zh SpriteFrame 的贴图资源。
* @returns @en Out of the texture boundary or not. @zh 矩形区域是否越界。
*/
public checkRect (texture: TextureBase) {
const rect = this._rect;
@@ -884,8 +915,8 @@ export class SpriteFrame extends Asset {
}
/**
* @en Make sure the mesh is available, you should call it before using the mesh
* @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它
* @en Make sure the mesh is available, you should call it before using the mesh.
* @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它。
*/
public ensureMeshData () {
if (this._mesh) return;
@@ -1375,6 +1406,10 @@ export class SpriteFrame extends Asset {
}
}
/**
* @en clone a sprite frame.
* @zh 克隆当前 sprite frame。
*/
public clone (): SpriteFrame {
const sp = new SpriteFrame();
const v = this.vertices;
@@ -1434,10 +1469,21 @@ export class SpriteFrame extends Asset {
}
}
/**
* @en complete loading callback.
* @zh 加载完成回调。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public onLoaded () {
this._calcTrimmedBorder();
}
/**
* @en default init.
* @zh 默认初始化。
* @param uuid @en Asset uuid. @zh 资源 uuid。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public initDefault (uuid?: string) {
super.initDefault(uuid);
const texture = new Texture2D();
@@ -1446,6 +1492,12 @@ export class SpriteFrame extends Asset {
this._calculateUV();
}
/**
* @en Check whether the sprite frame is validate.
* @zh 检查当前 sprite frame 对象是否是有效的。
* @returns @en validate or not. @zh 是否有效。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public validate () {
return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0;
}
+6
View File
@@ -59,6 +59,12 @@ export class TTFFont extends Font {
return { uuid: this._uuid, __nativeName__: this._native, ext: path.extname(this._native), __isNative__: true };
}
/**
* @en default init.
* @zh 默认初始化。
* @param uuid @en Asset uuid. @zh 资源 uuid。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public initDefault (uuid?: string) {
this._fontFamily = 'Arial';
super.initDefault(uuid);
+12 -17
View File
@@ -53,7 +53,7 @@ const stride = getAttributeStride(attributes);
* Graphics component.
*
* @zh
* 自定义图形类
* 自定义图形类。
*/
@ccclass('cc.Graphics')
@help('i18n:cc.Graphics')
@@ -200,20 +200,6 @@ export class Graphics extends UIRenderer {
this._color.set(value);
}
get srcBlendFactor () {
return this._srcBlendFactor;
}
set srcBlendFactor (value) {
}
get dstBlendFactor () {
return this._dstBlendFactor;
}
set dstBlendFactor (value) {
}
public static LineJoin = LineJoin;
public static LineCap = LineCap;
public impl: Impl | null = null;
@@ -240,7 +226,10 @@ export class Graphics extends UIRenderer {
private _graphicsUseSubMeshes: RenderingSubMesh[] = [];
//nativeObj
protected declare _graphicsNativeProxy:NativeUIModelProxy;
protected declare _graphicsNativeProxy: NativeUIModelProxy;
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get graphicsNativeProxy () {
return this._graphicsNativeProxy;
}
@@ -280,7 +269,7 @@ export class Graphics extends UIRenderer {
public onDestroy () {
this._sceneGetter = null;
if (JSB) {
this.graphicsNativeProxy.destroy();
this._graphicsNativeProxy.destroy();
this.model = null;
} else {
if (this.model) {
@@ -632,6 +621,9 @@ export class Graphics extends UIRenderer {
}
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public activeSubModel (idx: number) {
if (!this.model) {
warnID(4500, this.node.name);
@@ -730,6 +722,9 @@ export class Graphics extends UIRenderer {
}
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public updateRenderer () {
super.updateRenderer();
if (JSB) {
+5 -5
View File
@@ -29,8 +29,8 @@ import { Color, Vec2 } from '../../core';
import { Label } from './label';
/**
* @en Shadow effect for Label component, only for system fonts or TTF fonts
* @zh 用于给 Label 组件添加阴影效果,只能用于系统字体或 ttf 字体
* @en Shadow effect for Label component, only for system fonts or TTF fonts.
* @zh 用于给 Label 组件添加阴影效果,只能用于系统字体或 ttf 字体。
* @example
* import { Node, Label, LabelShadow } from 'cc';
* // Create a new node and add label components.
@@ -82,7 +82,7 @@ export class LabelShadow extends Component {
/**
* @en
* Offset between font and shadow
* Offset between font and shadow.
*
* @zh
* 字体与阴影的偏移。
@@ -105,10 +105,10 @@ export class LabelShadow extends Component {
/**
* @en
* A non-negative float specifying the level of shadow blur
* A non-negative float specifying the level of shadow blur.
*
* @zh
* 阴影的模糊程度
* 阴影的模糊程度。
*
* @example
* ```ts
+42 -19
View File
@@ -97,7 +97,7 @@ ccenum(VerticalTextAlignment);
/**
* @en Enum for Overflow.
*
* @zh 文本超载类型。
* @zh 文本溢出行为类型。
*/
export enum Overflow {
/**
@@ -160,23 +160,6 @@ export enum CacheMode {
ccenum(CacheMode);
/**
* @zh
* Type 类型。
*/
/**
* @zh
* TTF字体。
*/
/**
* @zh
* 位图字体。
*/
/**
* @zh
* 系统字体。
*/
/**
* @en
* The Label Component.
@@ -189,12 +172,32 @@ ccenum(CacheMode);
@executionOrder(110)
@menu('2D/Label')
export class Label extends UIRenderer {
/**
* @en Enum for horizontal text alignment.
*
* @zh 文本横向对齐类型。
*/
public static HorizontalAlign = HorizontalTextAlignment;
/**
* @en Enum for vertical text alignment.
*
* @zh 文本垂直对齐类型。
*/
public static VerticalAlign = VerticalTextAlignment;
/**
* @en Enum for label overflow mode.
*
* @zh 文本溢出行为类型。
*/
public static Overflow = Overflow;
/**
* @en Enum for cache mode.
*
* @zh 文本图集缓存类型。
*/
public static CacheMode = CacheMode;
/**
* @internal
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public static _canvasPool = CanvasPool.getInstance();
@@ -597,18 +600,30 @@ export class Label extends UIRenderer {
this.markForUpdateRenderData();
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get spriteFrame () {
return this._texture;
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get ttfSpriteFrame () {
return this._ttfSpriteFrame;
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get assemblerData () {
return this._assemblerData;
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get fontAtlas () {
return this._fontAtlas;
}
@@ -739,6 +754,11 @@ export class Label extends UIRenderer {
super.onDestroy();
}
/**
* @en update render data.
* @zh 更新渲染相关数据。
* @param force @en Whether to force an immediate update. @zh 是否立马强制更新渲染数据。
*/
public updateRenderData (force = false) {
if (force) {
this._flushAssembler();
@@ -762,6 +782,9 @@ export class Label extends UIRenderer {
this.markForUpdateRenderData();
}
/**
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setEntityColor (color: Color) {
if (JSB) {
if (this._font instanceof BitmapFont) {
+9 -9
View File
@@ -160,9 +160,9 @@ export class Mask extends Component {
/**
* @en
* Reverse mask
* Reverse mask.
* @zh
* 反向遮罩
* 反向遮罩。
*/
@displayOrder(14)
@tooltip('i18n:mask.inverted')
@@ -260,6 +260,10 @@ export class Mask extends Component {
}
}
/**
* @en Rendering component for providing stencil buffer information.
* @zh 用于提供 stencil buffer 信息的渲染组件。
*/
get subComp () {
return this._graphics || this._sprite;
}
@@ -299,10 +303,6 @@ export class Mask extends Component {
this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
}
/**
* @zh
* 图形内容重塑。
*/
public onRestore () {
this._changeRenderType();
this._updateGraphics();
@@ -319,9 +319,9 @@ export class Mask extends Component {
}
/**
* Hit test with point in World Space.
*
* @param worldPt point in World Space.
* @en Hit test with point in World Space.
* @zh 世界空间中的点击测试。
* @param worldPt @en point in World Space. @zh 世界空间中的点击点。
*/
public isHit (worldPt: Vec2) {
const uiTrans = this.node._uiProps.uiTransformComp!;
+12 -2
View File
@@ -234,10 +234,10 @@ export class RichText extends Component {
/**
* @en
* Custom System font of RichText
* Custom System font of RichText.
*
* @zh
* 富文本定制系统字体
* 富文本定制系统字体。
*/
@tooltip('i18n:richtext.font_family')
get fontFamily () {
@@ -425,7 +425,17 @@ export class RichText extends Component {
}
}
}
/**
* @en Enum for horizontal text alignment.
*
* @zh 文本横向对齐类型。
*/
public static HorizontalAlign = HorizontalTextAlignment;
/**
* @en Enum for vertical text alignment.
*
* @zh 文本垂直对齐类型。
*/
public static VerticalAlign = VerticalTextAlignment;
@serializable
+25 -3
View File
@@ -386,6 +386,10 @@ export class Sprite extends UIRenderer {
}
}
/**
* @en Grayscale mode.
* @zh 是否以灰度模式渲染。
*/
@editable
@displayOrder(5)
@tooltip('i18n:sprite.gray_scale')
@@ -431,9 +435,25 @@ export class Sprite extends UIRenderer {
}
}
/**
* @en Enum for fill type.
* @zh 填充类型。
*/
public static FillType = FillType;
/**
* @en Enum for sprite type.
* @zh Sprite 类型。
*/
public static Type = SpriteType;
/**
* @en Sprite's size mode, including trimmed size, raw size, and none.
* @zh 精灵尺寸调整模式。
*/
public static SizeMode = SizeMode;
/**
* @en Event types for sprite.
* @zh sprite 的事件类型。
*/
public static EventType = EventType;
@serializable
@@ -501,9 +521,8 @@ export class Sprite extends UIRenderer {
* If there is no atlas, the switch fails.
*
* @zh
* 精灵图集内的精灵替换
*
* @returns
* 选取使用精灵图集中的其他精灵。
* @param name @en Name of the spriteFrame to switch. @zh 要切换的 spriteFrame 名字。
*/
public changeSpriteFrameFromAtlas (name: string) {
if (!this._atlas) {
@@ -514,6 +533,9 @@ export class Sprite extends UIRenderer {
this.spriteFrame = sprite;
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public changeMaterialForDefine () {
let texture;
const lastInstanceMaterialType = this._instanceMaterialType;
+29
View File
@@ -61,6 +61,10 @@ export class UIMeshRenderer extends Component {
}
}
/**
* @en Get the model component on this node
* @zh 获取同节点的 model 组件
*/
public get modelComponent () {
return this._modelComponent;
}
@@ -123,6 +127,7 @@ export class UIMeshRenderer extends Component {
* @zh 渲染数据组装程序,这个方法会在所有子节点数据组装之前更新并组装当前组件的渲染数据到 UI 的顶点数据缓冲区中。
* 一般在 UI 渲染流程中调用,用于组装所有的渲染数据到顶点数据缓冲区。
* 注意:不要手动调用该函数,除非你理解整个流程。
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public _render (render: IBatcher) {
if (this._modelComponent) {
@@ -140,12 +145,18 @@ export class UIMeshRenderer extends Component {
return false;
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public fillBuffers (render: IBatcher) {
if (this.enabled) {
this._render(render);
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
// Native updateAssembler
public updateRenderer () {
if (JSB) {
@@ -221,16 +232,28 @@ export class UIMeshRenderer extends Component {
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
// interface
public markForUpdateRenderData (enable = true) {
uiRendererManager.markDirtyRenderer(this);
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public stencilStage: Stage = Stage.DISABLED;
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setNodeDirty () {
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setTextureDirty () {
}
@@ -238,6 +261,9 @@ export class UIMeshRenderer extends Component {
return (this.enabled && this._modelComponent !== null);
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get renderEntity () {
if (DEBUG) {
assert(this._renderEntity, 'this._renderEntity should not be invalid');
@@ -246,6 +272,9 @@ export class UIMeshRenderer extends Component {
}
protected _renderData: RenderData | null = null;
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get renderData () {
return this._renderData;
}
+4
View File
@@ -44,6 +44,10 @@ import { director } from '../../game';
* 该组件放在所有需要被静态合批的节点对象的根节点上,子节点放置对象必须是精灵和文本,其余对象不参与静态合批。
* 用户必须通过手动方式启用收集静态合批数据[[markAsDirty]],否则合批方式仍然采用动态合批(采集数据的流程相同)。此后渲染的内容是采用收集到的合批渲染数据,子节点的任何修改将不再有效。
* 注意:子节点下不要放置 Mask,Graphics,以及 UI 模型或者粒子之类对象,否则会在启用完静态合批后跳过渲染。
*
* @deprecated Since v3.4.1, We have adopted a new rendering batching policy in v3.4.1,
* which will result in an effective performance improvement for normal dynamic batching components,
* so manual management with the UIStaticBatch component is no longer recommended and will be removed in the future
*/
@ccclass('cc.UIStaticBatch')
@help('i18n:cc.UIStaticBatch')
+8 -6
View File
@@ -84,6 +84,10 @@ export class Canvas extends RenderRoot2D {
}
}
/**
* @en The camera component that will be aligned with this canvas
* @zh 将与此 canvas 对齐的相机组件
*/
@type(Camera)
@tooltip('i18n:canvas.camera')
get cameraComponent () {
@@ -98,6 +102,10 @@ export class Canvas extends RenderRoot2D {
this._onResizeCamera();
}
/**
* @en Align canvas with screen
* @zh 是否使用屏幕对齐画布
*/
@tooltip('i18n:canvas.align')
get alignCanvasWithScreen () {
return this._alignCanvasWithScreen;
@@ -109,12 +117,6 @@ export class Canvas extends RenderRoot2D {
this._onResizeCamera();
}
// /**
// * @zh
// * 当前激活的画布组件,场景同一时间只能有一个激活的画布。
// */
// public static instance: Canvas | null = null;
@type(Camera)
protected _cameraComponent: Camera | null = null;
@serializable
+4
View File
@@ -28,6 +28,10 @@ import { Component } from '../../scene-graph/component';
import { cclegacy } from '../../core';
import { UITransform } from './ui-transform';
/**
* @en The entry node for 2D object data collection, all 2D rendering objects need to be rendered under the RenderRoot node.
* @zh 2D 对象数据收集的入口节点,所有的 2D渲染对象需在 RenderRoot 节点下才可以被渲染。
*/
@ccclass('cc.RenderRoot2D')
@executionOrder(100)
@menu('2D/RenderRoot2D')
+4 -4
View File
@@ -50,8 +50,8 @@ enum SpriteMode {
@executeInEditMode
export class SpriteRenderer extends ModelRenderer {
/**
* @en The spriteFrame that the component should render
* @zh 该组件应渲染的 spriteFrame
* @en The spriteFrame that the component should render.
* @zh 该组件应渲染的 spriteFrame。
*/
@type(SpriteFrame)
get spriteFrame () {
@@ -78,8 +78,8 @@ export class SpriteRenderer extends ModelRenderer {
}
/**
* @en Rendering model of the component
* @zh 该组件的渲染模型
* @en Rendering model of the component.
* @zh 该组件的渲染模型。
*/
get model () {
return this._model;
+16 -3
View File
@@ -31,10 +31,10 @@ import { Stage } from '../renderer/stencil-manager';
/**
* @en Legacy 2D base class for rendering component, please use [[UIRenderer]] instead.
* This component will setup NodeUIProperties.uiComp in its owner [[Node]]
* This component will setup NodeUIProperties.uiComp in its owner [[Node]].
* @zh 旧的 2D 渲染组件基类,请使用 [[UIRenderer]] 替代。
* 这个组件会设置 [[Node]] 上的 NodeUIProperties.uiComp。
* @deprecated since v3.4.1
* @deprecated since v3.4.1, please use [[UIRenderer]] instead.
*/
@ccclass('cc.UIComponent')
@requireComponent(UITransform)
@@ -71,18 +71,31 @@ export class UIComponent extends Component {
* @zh 后置渲染数据组装程序,它会在所有子节点的渲染数据组装完成后被调用。
* 它可能会组装额外的渲染数据到顶点数据缓冲区,也可能只是重置一些渲染状态。
* 注意:不要手动调用该函数,除非你理解整个流程。
* @deprecated since v3.4.1, please use [[UIRenderer]] instead.
*/
public postUpdateAssembler (render: IBatcher) {
}
/**
* @deprecated since v3.4.1, please use [[UIRenderer]] instead.
*/
public markForUpdateRenderData (enable = true) {
}
public stencilStage : Stage = Stage.DISABLED;
/**
* @deprecated since v3.4.1, please use [[UIRenderer]] instead.
*/
public stencilStage: Stage = Stage.DISABLED;
/**
* @deprecated since v3.4.1, please use [[UIRenderer]] instead.
*/
public setNodeDirty () {
}
/**
* @deprecated since v3.4.1, please use [[UIRenderer]] instead.
*/
public setTextureDirty () {
}
}
+39 -8
View File
@@ -117,16 +117,19 @@ export class UIRenderer extends Renderer {
* @en The blend factor enums
* @zh 混合模式枚举类型
* @see [[gfx.BlendFactor]]
* @internal
*/
public static BlendState = BlendFactor;
/**
* @en The render data assembler
* @zh 渲染数据组装器
* @internal
*/
public static Assembler: IAssemblerManager = null!;
/**
* @en The post render data assembler
* @zh 后置渲染数据组装器
* @internal
*/
public static PostAssembler: IAssemblerManager | null = null;
@@ -197,21 +200,21 @@ export class UIRenderer extends Renderer {
protected _renderData: RenderData | null = null;
/**
* @internal
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get renderData () {
return this._renderData;
}
/**
* @internal
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get useVertexOpacity () {
return this._useVertexOpacity;
}
/**
* @internal
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
* @en The component stencil stage (please do not any modification directly on this object)
* @zh 组件模板缓冲状态 (注意:请不要直接修改它的值)
*/
@@ -252,18 +255,24 @@ export class UIRenderer extends Renderer {
protected _dstBlendFactorCache = BlendFactor.ONE_MINUS_SRC_ALPHA;
/**
* @internal
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public _dirtyVersion = -1;
/**
* @internal
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public _internalId = -1;
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get batcher () {
return director.root!.batcher2D;
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get renderEntity () {
if (DEBUG) {
assert(this._renderEntity, 'this._renderEntity should not be invalid');
@@ -348,7 +357,7 @@ export class UIRenderer extends Renderer {
/**
* @en Request new render data object.
* @zh 请求新的渲染数据对象。
* @return The new render data
* @return @en The new render data. @zh 新的渲染数据。
*/
public requestRenderData (drawInfoType = RenderDrawInfoType.COMP) {
const data = RenderData.add();
@@ -370,7 +379,9 @@ export class UIRenderer extends Renderer {
this._renderData = null;
}
// test code: to replace prev part updateAssembler
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public updateRenderer () {
if (this._assembler) {
this._assembler.updateRenderData(this);
@@ -379,7 +390,9 @@ export class UIRenderer extends Renderer {
this._renderEntity.enabled = this._renderFlag;
}
// test code: to replace after part updateAssembler
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public fillBuffers (render: IBatcher) {
if (this._renderFlag) {
this._render(render);
@@ -444,6 +457,9 @@ export class UIRenderer extends Renderer {
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
// for common
public static setEntityColorDirtyRecursively (node: Node, dirty: boolean) {
const render = node._uiProps.uiComp as UIRenderer;
@@ -461,18 +477,27 @@ export class UIRenderer extends Renderer {
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setEntityColor (color: Color) {
if (JSB) {
this._renderEntity.color = color;
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setEntityOpacity (opacity: number) {
if (JSB) {
this._renderEntity.localOpacity = opacity;
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setEntityEnabled (enabled: boolean) {
if (JSB) {
this._renderEntity.enabled = enabled;
@@ -554,12 +579,18 @@ export class UIRenderer extends Renderer {
protected _flushAssembler?(): void;
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setNodeDirty () {
if (this.renderData) {
this.renderData.nodeDirty = true;
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setTextureDirty () {
if (this.renderData) {
this.renderData.textureDirty = true;
+48 -12
View File
@@ -62,7 +62,6 @@ export class UITransform extends Component {
*/
@displayOrder(0)
@tooltip('i18n:ui_transform.content_size')
// @constget
get contentSize (): Readonly<Size> {
return this._contentSize;
}
@@ -87,6 +86,12 @@ export class UITransform extends Component {
this._markRenderDataDirty();
}
/**
* @en
* component width.
* @zh
* 组件宽度。
*/
get width () {
return this._contentSize.width;
}
@@ -111,6 +116,12 @@ export class UITransform extends Component {
this._markRenderDataDirty();
}
/**
* @en
* component height.
* @zh
* 组件高度。
*/
get height () {
return this._contentSize.height;
}
@@ -159,6 +170,13 @@ export class UITransform extends Component {
this._markRenderDataDirty();
}
/**
* @en
* The x-axis anchor of the node.
*
* @zh
* 锚点位置的 X 坐标。
*/
get anchorX () {
return this._anchorPoint.x;
}
@@ -173,6 +191,13 @@ export class UITransform extends Component {
this._markRenderDataDirty();
}
/**
* @en
* The y-axis anchor of the node.
*
* @zh
* 锚点位置的 Y 坐标。
*/
get anchorY () {
return this._anchorPoint.y;
}
@@ -194,7 +219,7 @@ export class UITransform extends Component {
*
* @zh
* 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。
* @deprecated
* @deprecated Since v3.1
*/
get priority () {
return this._priority;
@@ -274,7 +299,7 @@ export class UITransform extends Component {
* @zh
* 设置节点 UI Transform 的原始大小,不受该节点是否被缩放或者旋转的影响。
*
* @param size - The size of the UI transformation.
* @param size @en The size of the UI transform. @zh UI Transform 的 Size 大小。
* @example
* ```ts
* import { Size } from 'cc';
@@ -290,8 +315,8 @@ export class UITransform extends Component {
* @zh
* 设置节点 UI Transform 的原始大小,不受该节点是否被缩放或者旋转的影响。
*
* @param width - The width of the UI transformation.
* @param height - The height of the UI transformation.
* @param width @en The width of the UI transform. @zh UI Transform 的宽。
* @param height @en The height of the UI transform. @zh UI Transform 的高。
* @example
* ```ts
* import { Size } from 'cc';
@@ -443,7 +468,7 @@ export class UITransform extends Component {
* @zh 屏幕空间中的点击测试。
* @en Hit test with point in Screen Space.
*
* @param screenPoint point in Screen Space.
* @param screenPoint @en point in Screen Space. @zh 屏幕坐标中的点。
*/
public hitTest (screenPoint: Vec2, windowId = 0) {
const w = this._contentSize.width;
@@ -574,13 +599,13 @@ export class UITransform extends Component {
/**
* @en
* Returns a "local" axis aligned bounding box of the node. <br/>
* Returns an axis aligned bounding box of this node in local space coordinate. <br/>
* The returned box is relative only to its parent.
*
* @zh
* 返回父节坐标系下的轴向对齐的包围盒。
*
* @return - 节点大小的包围盒
* @returns @en An axis aligned bounding box of this node in local space coordinate. @zh 本地坐标系下的包围盒。
* @example
* ```ts
* const boundingBox = uiTransform.getBoundingBox();
@@ -602,14 +627,14 @@ export class UITransform extends Component {
/**
* @en
* Returns a "world" axis aligned bounding box of the node.<br/>
* Returns an axis aligned bounding box of this node in world space coordinate.<br/>
* The bounding box contains self and active children's world bounding box.
*
* @zh
* 返回节点在世界坐标系下的对齐轴向的包围盒(AABB)。
* 该边框包含自身和已激活的子节点的世界边框。
*
* @returns - 返回世界坐标系下包围盒。
* @returns @en An axis aligned bounding box of this node in world space coordinate. @zh 世界坐标系下包围盒。
* @example
* ```ts
* const newRect = uiTransform.getBoundingBoxToWorld();
@@ -632,7 +657,8 @@ export class UITransform extends Component {
*
* @param parentMat @en The parent node matrix.
* @zh 父节点矩阵。
* @returns
* @returns @en The minimum bounding box containing the current bounding box and its child nodes.
* @zh 包含当前节点包围盒及其子节点包围盒的最小包围盒。
*/
public getBoundingBoxTo (parentMat: Mat4) {
Mat4.fromRTS(_matrix, this.node.getRotation(), this.node.getPosition(), this.node.getScale());
@@ -674,7 +700,9 @@ export class UITransform extends Component {
* Compute the corresponding aabb in world space for raycast.
*
* @zh
* 计算出此 UI_2D 节点在世界空间下的 aabb 包围盒
* 计算出此 UI_2D 节点在世界空间下的 aabb 包围盒。
* @param out @en The out object of aabb bounding box of the node in world space. @zh 输出节点在世界空间下的 aabb 包围盒。
* @returns @en The aabb bounding box of the node in world space. @zh 节点在世界空间下的 aabb 包围盒。
*/
public getComputeAABB (out?: geometry.AABB) {
const width = this._contentSize.width;
@@ -741,6 +769,10 @@ export class UITransform extends Component {
}
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
* @engineInternal
*/
public static _sortSiblings () {
UITransform.priorityChangeNodeMap.forEach((node, ID) => {
UITransform._sortChildrenSibling(node);
@@ -750,6 +782,10 @@ export class UITransform extends Component {
UITransform.priorityChangeNodeMap.clear();
}
/**
* @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future.
* @engineInternal
*/
public static _cleanChangeMap () {
UITransform.priorityChangeNodeMap.clear();
}
+7 -11
View File
@@ -23,11 +23,9 @@
*/
import {
CanvasPool,
graphicsAssembler,
labelAssembler,
spriteAssembler,
earcut,
} from './assembler';
import { RenderData, MeshRenderData } from './renderer/render-data';
import { MeshBuffer } from './renderer/mesh-buffer';
@@ -48,18 +46,16 @@ export * from './utils';
export {
MeshBuffer,
StencilManager,
CanvasPool,
spriteAssembler,
labelAssembler,
graphicsAssembler,
earcut,
spriteAssembler, // use less
labelAssembler, // use less
graphicsAssembler, // use less
};
cclegacy.UI = {
MeshBuffer,
spriteAssembler,
graphicsAssembler,
labelAssembler,
MeshBuffer, // use less
spriteAssembler, // use less
graphicsAssembler, // use less
labelAssembler, // use less
RenderData,
MeshRenderData,
};
+6
View File
@@ -29,10 +29,16 @@
import { UIRenderer } from '../framework/ui-renderer';
/**
* @internal
*/
export interface IAssembler {
[key: string]: any;
}
/**
* @internal
*/
export interface IAssemblerManager {
getAssembler (component: UIRenderer): IAssembler;
}
+37 -28
View File
@@ -22,14 +22,14 @@
THE SOFTWARE.
*/
import { JSB } from 'internal:constants';
import { DEBUG, JSB } from 'internal:constants';
import { Camera, Model } from '../../render-scene/scene';
import type { UIStaticBatch } from '../components/ui-static-batch';
import { Material } from '../../asset/assets/material';
import { RenderRoot2D, UIRenderer } from '../framework';
import { Texture, Device, Attribute, Sampler, DescriptorSetInfo, Buffer,
BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler, deviceManager, PrimitiveMode } from '../../gfx';
import { CachedArray, Pool, Mat4, cclegacy, assertIsTrue } from '../../core';
import { CachedArray, Pool, Mat4, cclegacy, assertIsTrue, assert } from '../../core';
import { Root } from '../../root';
import { Node } from '../../scene-graph';
import { Stage, StencilManager } from './stencil-manager';
@@ -53,6 +53,8 @@ const _dsInfo = new DescriptorSetInfo(null!);
const m4_1 = new Mat4();
/**
* @en
* UI render flow
* @zh
* UI 渲染流程
*/
@@ -119,12 +121,12 @@ export class Batcher2D implements IBatcher {
// DescriptorSet Cache Map
private _descriptorSetCache = new DescriptorSetCache();
private _meshDataArray :MeshRenderData[] = [];
private _meshDataArray: MeshRenderData[] = [];
// mask use
private _maskClearModel :Model | null = null;
private _maskClearMtl :Material | null = null;
private _maskModelMesh :RenderingSubMesh | null = null;
private _maskClearModel: Model | null = null;
private _maskClearMtl: Material | null = null;
private _maskModelMesh: RenderingSubMesh | null = null;
constructor (private _root: Root) {
this.device = _root.device;
@@ -144,9 +146,9 @@ export class Batcher2D implements IBatcher {
}
this._batches.destroy();
this._bufferAccessors.forEach((accessor: StaticVBAccessor) => {
for (const accessor of this._bufferAccessors.values()) {
accessor.destroy();
});
}
this._bufferAccessors.clear();
if (this._drawBatchPool) {
@@ -276,14 +278,15 @@ export class Batcher2D implements IBatcher {
if (JSB) {
this._nativeObj.uploadBuffers();
} else if (this._batches.length > 0) {
this._meshDataArray.forEach((rd) => {
rd.uploadBuffers();
});
const length = this._meshDataArray.length;
for (let i = 0; i < length; i++) {
this._meshDataArray[i].uploadBuffers();
}
this._bufferAccessors.forEach((accessor: StaticVBAccessor) => {
for (const accessor of this._bufferAccessors.values()) {
accessor.uploadBuffers();
accessor.reset();
});
}
this._descriptorSetCache.update();
}
@@ -303,12 +306,13 @@ export class Batcher2D implements IBatcher {
this._drawBatchPool.free(batch);
}
// Reset buffer accessors
this._bufferAccessors.forEach((accessor: StaticVBAccessor) => {
for (const accessor of this._bufferAccessors.values()) {
accessor.reset();
});
this._meshDataArray.forEach((rd) => {
rd.freeIAPool();
});
}
const length = this._meshDataArray.length;
for (let i = 0; i < length; i++) {
this._meshDataArray[i].freeIAPool();
}
this._meshDataArray.length = 0;
this._staticVBBuffer = null;
@@ -411,6 +415,9 @@ export class Batcher2D implements IBatcher {
this._currDepthStencilStateStage = depthStencilStateStage;
this._currLayer = comp.node.layer;
if (frame) {
if (DEBUG) {
assert(frame.isValid, 'frame should not be invalid, it may have been released');
}
this._currTexture = frame.getGFXTexture();
this._currSampler = frame.getGFXSampler();
this._currTextureHash = frame.getHash();
@@ -928,10 +935,7 @@ export class Batcher2D implements IBatcher {
//sync mesh buffer to naive
public syncMeshBuffersToNative (accId: number, buffers: MeshBuffer[]) {
if (JSB) {
const nativeBuffers:NativeUIMeshBuffer[] = [];
buffers.forEach((x) => {
nativeBuffers.push(x.nativeObj);
});
const nativeBuffers = buffers.map((buf) => buf.nativeObj);
this._nativeObj.syncMeshBuffersToNative(accId, nativeBuffers);
}
}
@@ -1083,8 +1087,11 @@ class DescriptorSetCache {
public update () {
const caches = this._localDescriptorSetCache;
const length = caches.length;
if (length === 0) { return; }
const uselessArray: number[] = [];
caches.forEach((value) => {
for (let i = 0; i < length; i++) {
const value = caches[i];
if (value.isValid()) {
value.uploadLocalData();
} else {
@@ -1092,7 +1099,7 @@ class DescriptorSetCache {
const pos = caches.indexOf(value);
uselessArray.push(pos);
}
});
}
for (let i = uselessArray.length - 1; i >= 0; i--) {
caches.splice(uselessArray[i], 1);
}
@@ -1100,9 +1107,11 @@ class DescriptorSetCache {
public reset () {
const caches = this._localDescriptorSetCache;
caches.forEach((value) => {
const length = caches.length;
for (let i = 0; i < length; i++) {
const value = caches[i];
this._localCachePool.free(value);
});
}
this._localDescriptorSetCache.length = 0;
}
@@ -1116,9 +1125,9 @@ class DescriptorSetCache {
}
public destroy () {
this._descriptorSetCache.forEach((value, key, map) => {
for (const value of this._descriptorSetCache.values()) {
value.destroy();
});
}
this._descriptorSetCache.clear();
this._dsCacheHashByTexture.clear();
this._localDescriptorSetCache.length = 0;
+1 -1
View File
@@ -24,7 +24,7 @@
import { Attribute, Device } from '../../gfx';
import type { MeshBuffer } from './mesh-buffer';
import { getAttributeStride, getComponentPerVertex } from './vertex-format';
import { getAttributeStride } from './vertex-format';
export class BufferAccessor {
public get attributes (): Readonly<Attribute[]> { return this._attributes; }
+118 -12
View File
@@ -34,7 +34,7 @@ interface IIARef {
indexBuffer: Buffer;
}
export enum MeshBufferSharedBufferView{
enum MeshBufferSharedBufferView {
byteOffset,
vertexOffset,
indexOffset,
@@ -42,15 +42,35 @@ export enum MeshBufferSharedBufferView{
count,
}
/**
* @en Mesh buffer used for 2d rendering, used internally and not of concern to the user.
* @zh 2d 渲染使用的网格缓冲数据,内部使用,用户不须关心。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
export class MeshBuffer {
/**
* @en The vertex attributes of the buffer.
* @zh buffer 的顶点属性。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get attributes () { return this._attributes; }
/**
* @en Number of bytes in vertex format.
* @zh 顶点格式的字节数。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get vertexFormatBytes () { return this._vertexFormatBytes; }
protected _byteOffset = 0;
/**
* @en byte offset.
* @zh 字节偏移量。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get byteOffset () {
return this._byteOffset;
}
set byteOffset (val:number) {
set byteOffset (val: number) {
this._byteOffset = val;
if (JSB) {
this._sharedBuffer[MeshBufferSharedBufferView.byteOffset] = val;
@@ -58,10 +78,15 @@ export class MeshBuffer {
}
protected _vertexOffset = 0;
/**
* @en Vertexes offset.
* @zh 顶点数偏移。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get vertexOffset () {
return this._vertexOffset;
}
set vertexOffset (val:number) {
set vertexOffset (val: number) {
this._vertexOffset = val;
if (JSB) {
this._sharedBuffer[MeshBufferSharedBufferView.vertexOffset] = val;
@@ -69,10 +94,15 @@ export class MeshBuffer {
}
protected _indexOffset = 0;
/**
* @en Indices offset.
* @zh 索引偏移。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get indexOffset () {
return this._indexOffset;
}
set indexOffset (val:number) {
set indexOffset (val: number) {
this._indexOffset = val;
if (JSB) {
this._sharedBuffer[MeshBufferSharedBufferView.indexOffset] = val;
@@ -80,10 +110,15 @@ export class MeshBuffer {
}
protected _dirty = false;
/**
* @en Dirty flag.
* @zh 脏标记。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get dirty () {
return this._dirty;
}
set dirty (val:boolean) {
set dirty (val: boolean) {
this._dirty = val;
if (JSB) {
this._sharedBuffer[MeshBufferSharedBufferView.dirty] = val ? 1 : 0;
@@ -91,18 +126,28 @@ export class MeshBuffer {
}
protected _floatsPerVertex = 0;
/**
* @en Float numbers per vertex.
* @zh 每顶点的浮点数长度。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get floatsPerVertex () {
return this._floatsPerVertex;
}
set floatsPerVertex (val:number) {
set floatsPerVertex (val: number) {
this._floatsPerVertex = val;
}
protected _vData: Float32Array = null!;
/**
* @en Vertexes data.
* @zh 顶点数据。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get vData () {
return this._vData;
}
set vData (val:Float32Array) {
set vData (val: Float32Array) {
this._vData = val;
//还得看是否需要共享.buffer
if (JSB) {
@@ -111,10 +156,15 @@ export class MeshBuffer {
}
protected _iData: Uint16Array = null!;
/**
* @en Indices data.
* @zh 索引数据。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get iData () {
return this._iData;
}
set iData (val:Uint16Array) {
set iData (val: Uint16Array) {
this._iData = val;
if (JSB) {
this._nativeObj.iData = val;
@@ -132,23 +182,43 @@ export class MeshBuffer {
private _nextFreeIAHandle = 0;
//nativeObj
protected declare _nativeObj:NativeUIMeshBuffer;
protected declare _nativeObj: NativeUIMeshBuffer;
/**
* @en Native object.
* @zh 原生对象。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get nativeObj () {
return this._nativeObj;
}
//sharedBuffer
protected declare _sharedBuffer: Uint32Array;
/**
* @en Native shared buffer.
* @zh 原生共享缓冲。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get sharedBuffer () {
return this._sharedBuffer;
}
/**
* @en Initial native shared buffer.
* @zh 初始化原生共享缓冲。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public initSharedBuffer () {
if (JSB) {
this._sharedBuffer = new Uint32Array(MeshBufferSharedBufferView.count);
}
}
/**
* @en Synchronized native shared buffer.
* @zh 同步原生共享缓冲。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public syncSharedBufferToNative () {
if (JSB) {
this._nativeObj.syncSharedBufferToNative(this._sharedBuffer);
@@ -163,6 +233,15 @@ export class MeshBuffer {
this.syncSharedBufferToNative();
}
/**
* @en Initialize mesh buffer.
* @zh 初始化对象。
* @param device @en The GFX device. @zh GFX设备。
* @param attrs @en The vertex attributes of the buffer. @zh 缓冲区的顶点属性。
* @param vFloatCount @en The vertexes float count. @zh 每顶点所需的 float 数量。
* @param iCount @en The indices count. @zh 索引数量。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public initialize (device: Device, attrs: Attribute[], vFloatCount: number, iCount: number) {
this._initVDataCount = vFloatCount;
this._initIDataCount = iCount;
@@ -183,6 +262,11 @@ export class MeshBuffer {
}
}
/**
* @en Reset state.
* @zh 重置状态。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public reset () {
this._nextFreeIAHandle = 0;
this.dirty = false;
@@ -209,6 +293,11 @@ export class MeshBuffer {
this._iaPool.length = 0;
}
/**
* @en Set dirty flag.
* @zh 设置脏标签。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public setDirty () {
this.dirty = true;
}
@@ -222,7 +311,11 @@ export class MeshBuffer {
return false;
}
//有返回值暂时没写
/**
* @en require Free input assembler.
* @zh 请求可用的输入汇集器。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public requireFreeIA (device: Device) {
if (this._iaPool.length <= this._nextFreeIAHandle) {
this._iaPool.push(this.createNewIA(device));
@@ -231,7 +324,11 @@ export class MeshBuffer {
return ia;
}
//参数暂时没传
/**
* @en recycle input assembler.
* @zh 回收输入汇集器。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public recycleIA (ia: InputAssembler) {
const pool = this._iaPool;
for (let i = 0; i < this._nextFreeIAHandle; ++i) {
@@ -245,6 +342,11 @@ export class MeshBuffer {
}
}
/**
* @en check capacity.
* @zh 检查可分配余量。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public checkCapacity (vertexCount: number, indexCount: number) {
const maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex;
const maxIndex = this.indexOffset + indexCount;
@@ -254,6 +356,11 @@ export class MeshBuffer {
return true;
}
/**
* @en Upload and update buffers data.
* @zh 上传更新缓冲内容。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public uploadBuffers () {
if (this.byteOffset === 0 || !this._dirty) {
return;
@@ -292,7 +399,6 @@ export class MeshBuffer {
this.dirty = false;
}
//有返回值,暂时没原生化
private createNewIA (device: Device): IIARef {
let ia;
let vertexBuffers;
+78 -4
View File
@@ -27,7 +27,11 @@ import { Material } from '../../asset/assets';
import { UIRenderer } from '../framework/ui-renderer';
import { UIMeshRenderer } from '../components/ui-mesh-renderer';
// Stage types
/**
* @en Stencil stage types enum.
* @zh 模板状态类型枚举。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
export enum Stage {
// Stencil disabled
DISABLED = 0,
@@ -45,6 +49,11 @@ export enum Stage {
ENTER_LEVEL_INVERTED = 6,
}
/**
* @en Native stencil buffer format enum.
* @zh 原生模板缓冲格式枚举。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
export enum StencilSharedBufferView {
stencilTest,
func,
@@ -57,6 +66,11 @@ export enum StencilSharedBufferView {
count,
}
/**
* @en Stencil state manager.
* @zh 模板状态管理器。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
export class StencilManager {
public static sharedManager: StencilManager | null = null;
private _maskStack: any[] = [];
@@ -71,31 +85,61 @@ export class StencilManager {
ref: 1,
};
private _stage:Stage = Stage.DISABLED;
private _stage: Stage = Stage.DISABLED;
/**
* @en Stencil stage.
* @zh 模板缓冲阶段。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get stage () {
return this._stage;
}
set stage (val:Stage) {
set stage (val: Stage) {
this._stage = val;
}
/**
* @en Stencil pattern.
* @zh 模板缓冲样式。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
get pattern () {
return this._stencilPattern;
}
/**
* @en Add mask nesting.
* @zh 添加mask嵌套。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public pushMask (mask: any) {
this._maskStack.push(mask);
}
/**
* @en clear stencil stage.
* @zh 清空模板状态。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public clear (comp: UIRenderer | UIMeshRenderer) {
const isInverted = (comp.stencilStage !== Stage.ENTER_LEVEL);
return isInverted ? Stage.CLEAR_INVERTED : Stage.CLEAR;
}
/**
* @en Open stencil stage to enabled.
* @zh 开启模板状态。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public enableMask () {
this.stage = Stage.ENABLED;
}
/**
* @en exit stencil.
* @zh 退出模板状态。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public exitMask () {
if (this._maskStack.length === 0) {
// cc.errorID(9001);
@@ -109,15 +153,25 @@ export class StencilManager {
}
}
/**
* @en Get write mask count.
* @zh 获取写入模板缓冲的位数。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public getWriteMask () {
return 1 << (this._maskStack.length - 1);
}
/**
* @en Get write mask count when exit.
* @zh 获取退出时模板缓冲的位数。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public getExitWriteMask () {
return 1 << this._maskStack.length;
}
public getStencilRef () {
private getStencilRef () {
let result = 0;
for (let i = 0; i < this._maskStack.length; ++i) {
result += (0x00000001 << i);
@@ -125,10 +179,20 @@ export class StencilManager {
return result;
}
/**
* @en Get mask nesting count.
* @zh 获取mask嵌套数量。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public getMaskStackSize () {
return this._maskStack.length;
}
/**
* @en Reset stencil stage.
* @zh 重置模板状态。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public reset () {
// reset stack and stage
this._maskStack.length = 0;
@@ -145,6 +209,11 @@ export class StencilManager {
private stencilStateMap = new Map<number, DepthStencilState>();
private stencilStateMapWithDepth = new Map<number, DepthStencilState>();
/**
* @en Get stencil stage.
* @zh 获取模板状态。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public getStencilStage (stage: Stage, mat?: Material) {
let key = 0;
let depthTest = false;
@@ -195,6 +264,11 @@ export class StencilManager {
return depthStencilState;
}
/**
* @en Get stencil hash.
* @zh 获取模板状态的哈希值。
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
*/
public getStencilHash (stage: Stage) {
return (stage << 8) | this._maskStack.length;
}
+24 -2
View File
@@ -34,7 +34,7 @@ export const vfmt = [
];
/**
* @en Vertex format with the following layout
* @en Vertex format with the following layout.
* 1. Vector 3 position attribute (Float32)
* 2. Vector 4 color attribute (Float32)
* @zh 包含以下数据的顶点格式
@@ -62,6 +62,16 @@ export const vfmtPosUvColor = [
new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F),
];
/**
* @en Vertex format with the following layout
* 1. Vector 3 position attribute (Float32)
* 2. Vector 2 uv attribute (Float32)
* 3. Byte 4 color attribute (Byte)
* @zh 包含以下数据的顶点格式
* 1. 三维位置属性(Float32)
* 2. 二维贴图 UV 属性(Float32)
* 3. RGBA 颜色属性(Byte)
*/
export const vfmtPosUvColor4B = [
new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F),
new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F),
@@ -78,7 +88,7 @@ export const vfmtPosUvColor4B = [
* 1. 三维位置属性(Float32)
* 2. 二维贴图 UV 属性(Float32)
* 3. 第一套 RGBA 颜色属性(Float32)
* 3. 第二套 RGBA 颜色属性(Float32)
* 4. 第二套 RGBA 颜色属性(Float32)
*/
export const vfmtPosUvTwoColor = [
new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F),
@@ -87,6 +97,18 @@ export const vfmtPosUvTwoColor = [
new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F),
];
/**
* @en Vertex format with the following layout
* 1. Vector 3 position attribute (Float32)
* 2. Vector 2 uv attribute (Float32)
* 3. First byte 4 color attribute (Byte)
* 4. Second byte 4 color attribute (Byte)
* @zh 包含以下数据的顶点格式
* 1. 三维位置属性(Float32)
* 2. 二维贴图 UV 属性(Float32)
* 3. 第一套 RGBA 颜色属性(Byte)
* 4. 第二套 RGBA 颜色属性(Byte)
*/
export const vfmtPosUvTwoColor4B = [
new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F),
new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F),
@@ -273,6 +273,10 @@ export class DynamicAtlasManager extends System {
}
}
/**
* @en Dynamic Atlas Manager,use to auto merge sprite frame.
* @zh 动态合图管理器,用于引擎的自动合图功能。
*/
export const dynamicAtlasManager: DynamicAtlasManager = DynamicAtlasManager.instance = new DynamicAtlasManager();
director.registerSystem('dynamicAtlasManager', dynamicAtlasManager, 0);
+4 -5
View File
@@ -24,7 +24,6 @@
import { warnID } from '../../core';
import { safeMeasureText } from './text-utils';
import { CompleteCallback, IDownloadParseOptions } from '../../asset/asset-manager/shared';
import downloader from '../../asset/asset-manager/downloader';
import factory from '../../asset/asset-manager/factory';
import { TTFFont } from '../assets/ttf-font';
@@ -35,7 +34,7 @@ const ccdocument = ccwindow.document;
interface IFontLoadHandle {
fontFamilyName: string;
refWidth: number;
onComplete: CompleteCallback;
onComplete: ((err: Error | null, data?: any | null) => void);
startTime: number;
}
@@ -110,7 +109,7 @@ function checkFontLoaded () {
}
// refer to https://github.com/typekit/webfontloader/blob/master/src/core/nativefontwatchrunner.js
function nativeCheckFontLoaded (start: number, font: string, callback: CompleteCallback): void {
function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Error | null, data?: any | null) => void)): void {
const loader = new Promise<void>((resolve, reject) => {
const check = () => {
const now = Date.now();
@@ -151,7 +150,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: CompleteC
});
}
export function loadFont (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) {
export function loadFont (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) {
const fontFamilyName = getFontFamily(url);
// Already loaded fonts
if (_fontFaces[fontFamilyName]) {
@@ -228,7 +227,7 @@ export function getFontFamily (fontHandle: string): string {
return fontFamilyName;
}
function createFont (id: string, data: string, options: IDownloadParseOptions, onComplete: CompleteCallback<TTFFont>) {
function createFont (id: string, data: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: TTFFont | null) => void)) {
const out = new TTFFont();
out._nativeUrl = id;
out._nativeAsset = data;
+6 -1
View File
@@ -33,7 +33,8 @@ const eventRegx = /^(click)(\s)*=|(param)(\s)*=/;
const imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
/**
* A utils class for parsing HTML texts. The parsed results will be an object array.
* @en A utils class for parsing HTML texts. The parsed results will be an object array.
* @zh 一个用于解析HTML文本的工具类。解析后的结果将是一个对象数组。
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
*/
export interface IHtmlTextParserResultObj{
@@ -42,6 +43,8 @@ export interface IHtmlTextParserResultObj{
}
/**
* @en Html Text Parser Stack interface
* @zh Html 文本解析器接口
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
*/
export interface IHtmlTextParserStack{
@@ -62,6 +65,8 @@ export interface IHtmlTextParserStack{
}
/**
* @en Html Text Parser Stack
* @zh Html 文本解析器
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
*/
export class HtmlTextParser {
-1
View File
@@ -25,5 +25,4 @@
import './font-loader';
export * from './html-text-parser';
export * from './text-utils';
export { dynamicAtlasManager } from './dynamic-atlas/atlas-manager';
+7 -3
View File
@@ -147,9 +147,13 @@ Object.defineProperty(meshAssetProto, 'maxPosition', {
});
meshAssetProto.onLoaded = function () {
// might be undefined
if (this._struct != undefined) {
this.setStruct(this._struct);
// might be undefined or null
const meshStruct = this._struct;
if (meshStruct) {
// Synchronize to native if the struct contains valid values.
if (meshStruct.vertexBundles.length !== 0 || meshStruct.primitives.length !== 0) {
this.setStruct(this._struct);
}
}
// Set to null to release memory in JS
this._struct = null;
+60 -3
View File
@@ -27,7 +27,7 @@ import { displayOrder, group, range } from 'cc.decorator';
import { Texture2D, TextureCube } from '../../asset/assets';
import { Material } from '../../asset/assets/material';
import { Mesh } from '../assets/mesh';
import { Vec4, Enum, cclegacy, CCBoolean, CCFloat, assertIsTrue, _decorator, CCInteger, EventTarget } from '../../core';
import { Vec4, Enum, cclegacy, CCBoolean, CCFloat, assertIsTrue, _decorator, CCInteger, EventTarget, warnID } from '../../core';
import { scene } from '../../render-scene';
import { MorphModel } from '../models/morph-model';
import { Root } from '../../root';
@@ -300,7 +300,7 @@ export class MeshRenderer extends ModelRenderer {
@serializable
@editable
@disallowAnimation
@displayOrder(1)
@displayOrder(3)
public bakeSettings = new ModelBakeSettings(this);
@serializable
@@ -327,7 +327,7 @@ export class MeshRenderer extends ModelRenderer {
*/
@type(CCFloat)
@tooltip('i18n:model.shadow_bias')
@group({ id: 'DynamicShadow', name: 'DynamicShadowSettings', displayOrder: 0 })
@group({ id: 'DynamicShadow', name: 'DynamicShadowSettings', displayOrder: 2 })
@disallowAnimation
get shadowBias () {
return this._shadowBias;
@@ -374,6 +374,25 @@ export class MeshRenderer extends ModelRenderer {
this._updateCastShadow();
}
/**
* @en Is received direction Light.
* @zh 是否接收平行光光照。
* @param visibility @en direction light visibility. @zh 方向光的可见性。
*/
public onUpdateReceiveDirLight (visibility: number, forceClose = false) {
if (!this._model) { return; }
if (forceClose) {
this._model.receiveDirLight = false;
return;
}
if (this.node && ((visibility & this.node.layer) === this.node.layer)
|| (visibility & this._model.visFlags)) {
this._model.receiveDirLight = true;
} else {
this._model.receiveDirLight = false;
}
}
/**
* @en receive shadow.
* @zh 实时光照下是否接受阴影。
@@ -398,6 +417,7 @@ export class MeshRenderer extends ModelRenderer {
* 注意,设置时,所有形变目标的权重都将归零。
*/
@type(Mesh)
@displayOrder(1)
@tooltip('i18n:model.mesh')
get mesh () {
return this._mesh;
@@ -418,6 +438,7 @@ export class MeshRenderer extends ModelRenderer {
this._updateReceiveShadow();
this._updateUseLightProbe();
this._updateUseReflectionProbe();
this._updateReceiveDirLight();
}
/**
@@ -484,6 +505,7 @@ export class MeshRenderer extends ModelRenderer {
this._updateUseLightProbe();
this._updateBakeToReflectionProbe();
this._updateUseReflectionProbe();
this._updateReceiveDirLight();
}
// Redo, Undo, Prefab restore, etc.
@@ -499,11 +521,13 @@ export class MeshRenderer extends ModelRenderer {
this._updateUseLightProbe();
this._updateBakeToReflectionProbe();
this._updateUseReflectionProbe();
this._updateReceiveDirLight();
}
public onEnable () {
super.onEnable();
this.node.on(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this);
this.node.on(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this);
this.bakeSettings.on(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this);
this.bakeSettings.on(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this);
this.bakeSettings.on(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this);
@@ -519,6 +543,7 @@ export class MeshRenderer extends ModelRenderer {
this._updateUseReflectionProbe();
this._onUpdateLocalShadowBias();
this._updateUseLightProbe();
this._updateReceiveDirLight();
this._attachToScene();
}
@@ -527,6 +552,7 @@ export class MeshRenderer extends ModelRenderer {
this._detachFromScene();
}
this.node.off(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this);
this.node.off(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this);
this.bakeSettings.off(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this);
this.bakeSettings.off(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this);
this.bakeSettings.off(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this);
@@ -648,6 +674,7 @@ export class MeshRenderer extends ModelRenderer {
this.bakeSettings.uvParam.w = lum;
this._onUpdateLightingmap();
this._updateReceiveDirLight();
}
public updateProbeCubemap (cubeMap: TextureCube | null, useDefaultTexture?: boolean) {
@@ -718,6 +745,25 @@ export class MeshRenderer extends ModelRenderer {
this._onUpdateLightingmap();
this._onUpdateLocalShadowBias();
this._updateUseReflectionProbe();
this._updateReceiveDirLight();
}
}
protected _updateReceiveDirLight () {
if (!this._model) { return; }
const scene = this.node.scene;
if (!scene || !scene.renderScene) { return; }
const mainLight = scene.renderScene.mainLight;
if (!mainLight) { return; }
const visibility = mainLight.visibility;
if (!mainLight.node) { return; }
if (mainLight.node.mobility === MobilityMode.Static
&& (this.bakeSettings.texture || (this.node.scene.globals.lightProbeInfo.data
&& this.node.scene.globals.lightProbeInfo.data.hasCoefficients()
&& this._model.useLightProbe))) {
this.onUpdateReceiveDirLight(visibility, true);
} else {
this.onUpdateReceiveDirLight(visibility);
}
}
@@ -873,6 +919,11 @@ export class MeshRenderer extends ModelRenderer {
protected onMobilityChanged () {
this._updateUseLightProbe();
this._updateReceiveDirLight();
}
protected onLightProbeBakingChanged () {
this._updateReceiveDirLight();
}
protected onUseLightProbeChanged () {
@@ -883,8 +934,14 @@ export class MeshRenderer extends ModelRenderer {
this._updateUseReflectionProbe();
if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP) {
cclegacy.internal.reflectionProbeManager.updateUseCubeModels(this._model);
if (!cclegacy.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, ReflectionProbeType.BAKED_CUBEMAP)) {
warnID(16302);
}
} else if (this.bakeSettings.reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) {
cclegacy.internal.reflectionProbeManager.updateUsePlanarModels(this._model);
if (!cclegacy.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, ReflectionProbeType.PLANAR_REFLECTION)) {
warnID(16302);
}
}
}
+25 -14
View File
@@ -28,6 +28,8 @@ import { scene } from '../../render-scene';
import { cclegacy, clamp, warnID, CCBoolean, CCFloat, _decorator, settings, Settings, override } from '../../core';
import { Camera, PCFType, Shadows, ShadowType, CSMOptimizationMode, CSMLevel } from '../../render-scene/scene';
import { Root } from '../../root';
import { MeshRenderer } from '../framework';
import { director } from '../../game/director';
const { ccclass, menu, executeInEditMode, property, serializable, formerlySerializedAs, tooltip, help, visible, type, editable, slide, range } = _decorator;
@@ -115,20 +117,6 @@ export class DirectionalLight extends Light {
}
}
/**
* @en Turn off the function for directional light.
* @zh 方向光关闭该功能。
* @engineInternal
*/
@override
@visible(false)
set visibility (vis: number) {
this._visibility = vis;
}
get visibility (): number {
return this._visibility;
}
/**
* @en Whether activate real time shadow.
* @zh 是否启用实时阴影?
@@ -564,4 +552,27 @@ export class DirectionalLight extends Light {
this._light.csmTransitionRange = this._csmTransitionRange;
}
}
protected _onUpdateReceiveDirLight () {
if (!this._light) {
return;
}
super._onUpdateReceiveDirLight();
const scene = director.getScene();
if (!scene || !scene.renderScene) {
return;
}
if (scene.renderScene.mainLight !== this._light) {
return;
}
const models = scene.renderScene.models;
for (let i = 0; i < models.length; i++) {
const model = models[i];
if (!model.node) continue;
const meshRender = model.node.getComponent(MeshRenderer);
if (!meshRender) continue;
meshRender.onUpdateReceiveDirLight(this._visibility);
}
}
}
+5 -2
View File
@@ -221,8 +221,8 @@ export class Light extends Component {
}
/**
* @en Visibility mask of the light, declaring a set of node layers that will be visible to this light(Does not work with directional light).
* @zh 光照的可见性掩码,声明在当前光照中可见的节点层级集合(对方向光不生效)。
* @en Visibility mask of the light, declaring a set of node layers that will be visible to this light.
* @zh 光照的可见性掩码,声明在当前光照中可见的节点层级集合。
*/
@tooltip('i18n:lights.visibility')
@displayOrder(255)
@@ -230,6 +230,7 @@ export class Light extends Component {
set visibility (vis: number) {
this._visibility = vis;
if (this._light) { this._light.visibility = vis; }
this._onUpdateReceiveDirLight();
}
get visibility (): number {
return this._visibility;
@@ -315,4 +316,6 @@ export class Light extends Component {
}
}
}
protected _onUpdateReceiveDirLight () {}
}
+3
View File
@@ -362,6 +362,7 @@ export class LODGroup extends Component {
lod.screenUsagePercentage = screenUsagePercentage;
this._LODs.splice(index, 0, lod);
this._lodGroup.insertLOD(index, lod.lodData);
this._updateDataToScene();
if (this.node) {
this._emitChangeNode(this.node);
}
@@ -386,6 +387,7 @@ export class LODGroup extends Component {
}
this._LODs.splice(index, 1);
this._lodGroup.eraseLOD(index);
this._updateDataToScene();
this._emitChangeNode(this.node);
return lod;
}
@@ -418,6 +420,7 @@ export class LODGroup extends Component {
this._LODs[index] = lod;
lod.modelAddedCallback = this.onLodModelAddedCallback.bind(this);
this.lodGroup.updateLOD(index, lod.lodData);
this._updateDataToScene();
}
/**
@@ -23,7 +23,7 @@
*/
import { ccclass, executeInEditMode, menu, playOnFocus, serializable, tooltip, type, visible } from 'cc.decorator';
import { EDITOR } from 'internal:constants';
import { CCObject, Color, Enum, size, Vec3 } from '../../core';
import { cclegacy, CCObject, Color, Enum, size, Vec3 } from '../../core';
import { TextureCube } from '../../asset/assets';
import { scene } from '../../render-scene';
@@ -34,6 +34,7 @@ import { Layers } from '../../scene-graph/layers';
import { Camera } from '../../misc/camera-component';
import { Node, TransformBit } from '../../scene-graph';
import { ProbeClearFlag, ProbeType } from '../../render-scene/scene/reflection-probe';
import { absolute } from '../../physics/utils/util';
export enum ProbeResolution {
/**
@@ -105,10 +106,8 @@ export class ReflectionProbe extends Component {
* 获取或设置包围盒的大小。
*/
set size (value: Vec3) {
if (value.x < 0) value.x = 0;
if (value.y < 0) value.y = 0;
if (value.z < 0) value.z = 0;
this._size.set(value);
absolute(this._size);
this.probe.size = this._size;
if (this.probe) {
ReflectionProbeManager.probeManager.onUpdateProbes(true);
@@ -125,11 +124,11 @@ export class ReflectionProbe extends Component {
*/
@type(Enum(ProbeType))
set probeType (value: number) {
this.probe.probeType = value;
if (value !== this._probeType) {
const lastSize = this._size.clone();
const lastSizeIsNoExist = Vec3.equals(this._lastSize, Vec3.ZERO);
this._probeType = value;
this.probe.probeType = value;
if (this._probeType === ProbeType.CUBE) {
if (lastSizeIsNoExist) {
@@ -294,6 +293,7 @@ export class ReflectionProbe extends Component {
onEnable () {
if (this._probe) {
ReflectionProbeManager.probeManager.register(this._probe);
ReflectionProbeManager.probeManager.onUpdateProbes(true);
this._probe.enable();
}
}
@@ -319,7 +319,7 @@ export class ReflectionProbe extends Component {
public update (dt: number) {
if (!this.probe) return;
if (EDITOR) {
if (EDITOR && !cclegacy.GAME_VIEW) {
if (this.probeType === ProbeType.PLANAR) {
const cameraLst: scene.Camera[] | undefined = this.node.scene.renderScene?.cameras;
if (cameraLst !== undefined) {
+245 -173
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-len */
/*
Copyright (c) 2019-2023 Xiamen Yaji Software Co., Ltd.
@@ -28,33 +29,27 @@ import { error, sys, Settings, settings, path, cclegacy } from '../../core';
import Bundle from './bundle';
import Cache, { ICache } from './cache';
import CacheManager from './cache-manager';
import dependUtil from './depend-util';
import downloader from './downloader';
import dependUtil, { DependUtil } from './depend-util';
import downloader, { Downloader } from './downloader';
import factory from './factory';
import fetch from './fetch';
import * as helper from './helper';
import load from './load';
import packManager from './pack-manager';
import parser from './parser';
import { IPipe, Pipeline } from './pipeline';
import parser, { Parser } from './parser';
import { Pipeline } from './pipeline';
import preprocess from './preprocess';
import releaseManager from './release-manager';
import RequestItem from './request-item';
import {
CompleteCallbackWithData,
ProgressCallback,
IBundleOptions,
IOptions,
IRemoteOptions,
presets,
Request,
references,
IJsonAssetOptions,
assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline, assetsOverrideMap } from './shared';
assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline, assetsOverrideMap, IRequest } from './shared';
import Task from './task';
import { combine, parse, replaceOverrideAsset } from './url-transformer';
import { asyncify, parseParameters } from './utilities';
import { IAddressableInfo, IAssetInfo, IPackInfo, ISceneInfo } from './config';
/**
* @zh
@@ -74,33 +69,33 @@ export interface IAssetManagerOptions {
/**
* @zh
* 所有 bundle 的版本信息
* 所有 bundle 的版本信息。
* @en
* Version for all bundles
* Version for all bundles.
*/
bundleVers?: Record<string, string>;
/**
* @zh
* 远程服务器地址
* 远程服务器地址。
* @en
* Remote server address
* Remote server address.
*/
server?: string;
/**
* @zh
* 配置为子包的 bundle
* 配置为子包的 bundle。
* @en
* All subpackages
* All subpackages.
*/
subpackages?: string[];
/**
* @zh
* 配置为远程包的 bundle
* 配置为远程包的 bundle。
* @en
* All remote bundles
* All remote bundles.
*/
remoteBundles?: string[];
@@ -109,85 +104,90 @@ export interface IAssetManagerOptions {
/**
* @en
* This module controls asset's behaviors and information, include loading, releasing etc. it is a singleton
* All member can be accessed with `assetManager`.
* You can access it via [[assetManager]].
*
* @zh
* 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,所有成员能够通过 `assetManager` 调用
*
* 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,你能够通过 `assetManager` 访问它。
*/
export class AssetManager {
/**
* @en
* Normal loading pipeline
* Normal loading pipeline. Asset manager uses this pipeline to load all assets, it has an additional asset parsing process compared to the fetchPipeline.
*
* @zh
* 正常加载管线
*
* 正常加载管线。Asset manager 使用此管线来加载所有资源,他与 fetchPipeline 相比额外多了资源的解析过程。
*/
public pipeline: Pipeline = pipeline.append(preprocess).append(load);
/**
* @en
* Fetching pipeline
* Fetching pipeline. Asset manager uses this pipeline to preload all assets, which lacks the asset parsing process compared to the pipeline.
*
* @zh
* 下载管线
* 下载管线。Asset manager 使用此管线来预加载所有资源,他与 pipeline 相比缺少了资源的解析过程。
*
*/
public fetchPipeline: Pipeline = fetchPipeline.append(preprocess).append(fetch);
/**
* @en
* Url transformer
* Url transformer. Asset manager uses this pipeline to convert the uuid, path, etc. to the path of the final file path to be loaded.
* You can customize this pipeline to redirect the path to the path you want.
*
* @zh
* Url 转换器
* Url 转换器。Asset manager 使用此管线将 uuid, 路径等信息转换为最终要加载的文件路径。你可以自定义此管线将路径重定向到你想要的路径。
*
*/
public transformPipeline: Pipeline = transformPipeline.append(parse).append(replaceOverrideAsset).append(combine);
/**
* @en
* The collection of bundle which is already loaded, you can remove cache with [[removeBundle]]
* The collection of bundle which is already loaded, you can remove cache with [[removeBundle]].
*
* @zh
* 已加载 bundle 的集合, 你能通过 [[removeBundle]] 来移除缓存
* 已加载 bundle 的集合, 你能通过 [[removeBundle]] 来移除缓存。
*
*/
public bundles: ICache<Bundle> = bundles;
/**
* @en
* The collection of asset which is already loaded, you can remove cache with [[releaseAsset]]
* The collection of asset which is already loaded, you can remove cache with [[releaseAsset]].
*
* @zh
* 已加载资源的集合, 你能通过 [[releaseAsset]] 来移除缓存
* 已加载资源的集合, 你能通过 [[releaseAsset]] 来移除缓存。
*/
public assets: ICache<Asset> = assets;
/**
* @internal only using in L10N for now
* @internal only using in L10N for now.
*/
public readonly assetsOverrideMap = assetsOverrideMap;
/**
* @internal
*/
public generalImportBase = '';
/**
* @internal
*/
public generalNativeBase = '';
/**
* @en
* Manage relationship between asset and its dependencies
* Manage relationship between asset and its dependencies.
*
* @zh
* 管理资源依赖关系
* 管理资源间依赖关系。
*/
public dependUtil = dependUtil;
/**
* @en
* Whether or not load asset forcibly, if it is true, asset will be loaded regardless of error
* A flag indicates whether to force loading assets and ignore errors.
*
* @zh
* 是否强制加载资源, 如果为 true ,加载资源将会忽略报错
* 是否强制加载资源标志, 如果为 true,加载资源时将会忽略错误。
*
*/
public force = EDITOR || PREVIEW;
@@ -197,57 +197,58 @@ export class AssetManager {
* Whether to use image bitmap to load image first. If enabled, images loading will become faster but memory usage will increase.
*
* @zh
* 是否优先使用 image bitmap 来加载图片,启用之后,图片加载速度会更快, 但内存占用会变高,
* 是否优先使用 image bitmap 来加载图片,启用之后,图片加载速度会更快, 但内存占用会变高。
*
*/
public allowImageBitmap = !sys.isMobile;
/**
* @en
* Some useful function
* Some useful functions, such as the convert function between url and uuid.
*
* @zh
* 一些有用的方法
* 一些有用的方法, 例如 url 与 uuid 之间的转换方法。
*
*/
public utils = helper;
/**
* @en
* Manage all downloading task
* The downloader used by `assetManager`.It manages all downloading tasks.
*
* @zh
* 管理所有下载任务
* `assetManager` 所使用的下载器,管理所有下载任务。
*
*/
public downloader = downloader;
/**
* @en
* Manage all parsing task
* The parser used by `assetManager`.It manages all parsing tasks.
*
* @zh
* 管理所有解析任务
* `assetManager` 所使用的解析器,管理所有解析任务。
*
*/
public parser = parser;
/**
* @en
* Manage all packed asset
* Manage all packed assets.
*
* @zh
* 管理所有合并后的资源
* 管理所有合并后的资源。
*
* @deprecated Since v3.7, this is an engine internal interface. You usually don't need to care about how resources are merged and split.
*/
public packManager = packManager;
/**
* @en
* Whether or not cache the loaded asset
* Whether to cache loaded assets.
*
* @zh
* 是否缓存已加载的资源
* 是否缓存已加载的资源。
*
*/
public cacheAsset = true;
@@ -257,45 +258,75 @@ export class AssetManager {
* Cache manager is a module which controls all caches downloaded from server in non-web platform.
*
* @zh
* 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存
* 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存。
*
*/
public cacheManager: CacheManager | null = null;
/**
* @en
* The preset of options
* The preset of options.
*
* @zh
* 可选参数的预设集
* 可选参数的预设集。
*
*/
public presets = presets;
/**
* @internal
*/
public factory = factory;
public preprocessPipe: IPipe = preprocess;
/**
* @internal
*/
public preprocessPipe = preprocess;
public fetchPipe: IPipe = fetch;
/**
* @internal
*/
public fetchPipe = fetch;
public loadPipe: IPipe = load;
/**
* @internal
*/
public loadPipe = load;
/**
* @internal
*/
public references = references;
private _releaseManager = releaseManager;
private _files = files;
private _parsed = parsed;
private _parsePipeline = BUILD ? null : new Pipeline('parse existing json', [this.loadPipe]);
private _projectBundles: string[] = [];
private static _instance: AssetManager;
/**
* @en
* The builtin 'main' bundle
* A global singleton instance of [[AssetManager]], which you can access directly through [[assetManager]].
*
* @zh
* 内置 main 包
* [[AssetManager]] 的全局单例,你可以直接通过 [[assetManager]] 访问。
*/
static get instance () {
if (!this._instance) {
this._instance = new AssetManager();
}
return this._instance;
}
private constructor () {}
/**
* @en
* The builtin 'main' bundle.
*
* @zh
* 内置 main 包。
*/
public get main (): Bundle | null {
return bundles.get(BuiltinBundleName.MAIN) || null;
@@ -303,10 +334,10 @@ export class AssetManager {
/**
* @en
* The builtin 'resources' bundle
* The builtin 'resources' bundle.
*
* @zh
* 内置 resources 包
* 内置 resources 包。
*
*/
public get resources (): Bundle | null {
@@ -315,13 +346,14 @@ export class AssetManager {
/**
* @en
* Initialize assetManager with options
* Initializes assetManager with options.
* This method will be called automatically when the engine starts, you should not call this method manually at any time.
*
* @zh
* 初始化资源管理器
*
* @param options - the configuration
* 初始化资源管理器,引擎在启动时,将会自动调用此方法,你不应该在任何时候手动调用此方法。
*
* @param options @en The configuration of asset manager. @zh 资源管理器的配置选项。
* @internal
*/
public init (options: IAssetManagerOptions = {}) {
const server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || '';
@@ -355,13 +387,13 @@ export class AssetManager {
/**
* @en
* Get the bundle which has been loaded
* Gets the bundle which has been loaded with the name of bundle.
*
* @zh
* 获取已加载的分包
* 通过包名称获取已加载的分包。
*
* @param name - The name of bundle
* @return - The loaded bundle
* @param name @en The name of bundle. @zh 资源包的名称。
* @returns @en The loaded bundle. @zh 已加载的资源包。
*
* @example
* // ${project}/assets/test1
@@ -376,16 +408,14 @@ export class AssetManager {
/**
* @en
* Remove this bundle. NOTE: The asset within this bundle will not be released automatically,
* you can call [[AssetManager.Bundle.releaseAll]] manually before remove it if you need
* Removes this bundle. NOTE: The asset within this bundle will not be released automatically,
* you can call [[AssetManager.Bundle.releaseAll]] manually before removing it if you need.
*
* @zh
* 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 [[AssetManager.Bundle.releaseAll]] 进行释放
* 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 [[AssetManager.Bundle.releaseAll]] 进行释放。
*
* @param bundle - The bundle to be removed
* @param bundle @en The bundle to be removed. @zh 准备移除的 Bundle。
*
* @typescript
* removeBundle(bundle: AssetManager.Bundle): void
*/
public removeBundle (bundle: Bundle) {
bundle._destroy();
@@ -394,37 +424,36 @@ export class AssetManager {
/**
* @en
* General interface used to load assets with a progression callback and a complete callback. You can achieve almost all
* effect you want with combination of `requests` and `options`.It is highly recommended that you use more simple API,
* such as `load`, `loadDir` etc. Every custom parameter in `options` will be distribute to each of `requests`. if request
* already has same one, the parameter in request will be given priority. Besides, if request has dependencies, `options`
* will distribute to dependencies too. Every custom parameter in `requests` will be transferred to handler of `downloader`
* and `parser` as `options`. You can register you own handler downloader or parser to collect these custom parameters for some effect.
* General interface used to load assets with a progression callback and a complete callback.
* It is highly recommended that you use more simple API, such as `load`, `loadDir` etc. You can pass
* some additional data via the `options` parameter, and the parameters in `options` will affect this loading.
* The optional parameter will be transferred to handler of `downloader` and `parser` as `options`. You can
* register you own handler downloader or parser to collect these custom parameters for some effect.
*
* Reserved Keyword: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`,
* Reserved Keywords for additional parameters: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`,
* `bundle`, `onFileProgress`, `maxConcurrency`, `maxRequestsPerFrame`, `maxRetryCount`, `version`, `xhrResponseType`,
* `xhrWithCredentials`, `xhrMimeType`, `xhrTimeout`, `xhrHeader`, `reloadAsset`, `cacheAsset`, `cacheEnabled`,
* Please DO NOT use these words as custom options!
* Please DO NOT use these words as your own options!
*
* @zh
* 通用加载资源接口,可传入进度回调以及完成回调,通过组合 `request` 和 `options` 参数,几乎可以实现和扩展所有想要的加载效果。非常建议
* 你使用更简单的API,例如 `load`、`loadDir` 等。`options` 中的自定义参数将会分发到 `requests` 的每一项中,如果request中已存在同名的
* 参数则以 `requests` 中为准,同时如果有其他依赖资源,则 `options` 中的参数会继续向依赖项中分发。request中的自定义参数都会以 `options`
* 形式传入加载流程中的 `downloader`, `parser` 的方法中, 你可以扩展 `downloader`, `parser` 收集参数完成想实现的效果。
* 通用加载资源接口,可传入进度回调以及完成回调,建议你使用更简单的API,例如 `load`、`loadDir` 等。你可以通过 `options` 参数额外传递一些数据,`options` 中的参数将会影响本次加载。
* 额外参数会传入加载流程中的 `downloader`, `parser` 的处理方法中, 你可以扩展 `downloader`, `parser` 收集参数完成想实现的效果。
*
* 保留关键字: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, `bundle`, `onFileProgress`,
* 额外参数保留关键字: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, `bundle`, `onFileProgress`,
* `maxConcurrency`, `maxRequestsPerFrame`, `maxRetryCount`, `version`, `xhrResponseType`, `xhrWithCredentials`, `xhrMimeType`, `xhrTimeout`, `xhrHeader`,
* `reloadAsset`, `cacheAsset`, `cacheEnabled`, 请不要使用这些字段为自定义参数!
* `reloadAsset`, `cacheAsset`, `cacheEnabled`, 请不要使用这些字段为你自己的参数!
*
* @param requests - The request you want to load
* @param options - Optional parameters
* @param onProgress - Callback invoked when progression change
* @param onProgress.finished - The number of the items that are already completed
* @param onProgress.total - The total number of the items
* @param onProgress.item - The current request item
* @param onComplete - Callback invoked when finish loading
* @param onComplete.err - The error occurred in loading process.
* @param onComplete.data - The loaded content
* @param requests @en The loading requests. @zh 加载请求。
* @param options @en Optional parameters. @zh 可选参数。
* @param onProgress @en Callback invoked when the loading progress change. @zh 加载进度发生变化时执行的回调。
* @param onProgress.finished
* @en The number of request items that have finished loading.
* @zh 已经完成加载的资源数量。
* @param onProgress.total @en The number of all request items to be loaded. @zh 所有待加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的加载项。
* @param onComplete @en Callback invoked when all assets loaded. @zh 所有资源加载完成后的回调。
* @param onComplete.err @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。
* @param onComplete.data @en The loaded data, or null if an error occurred during loading. @zh 已加载的数据,如果加载过程中有错误发生,则为 null。
*
* @example
* assetManager.loadAny({url: 'http://example.com/a.png'}, (err, img) => log(img));
@@ -432,7 +461,7 @@ export class AssetManager {
* assetManager.loadAny([{ uuid: '0cbZa5Y71CTZAccaIFluuZ'}, {url: 'http://example.com/a.png'}], (err, assets) => log(assets));
* assetManager.downloader.register('.asset', (url, options, onComplete) => {
* url += '?userName=' + options.userName + "&password=" + options.password;
* assetManager.downloader.downloadFile(url, null, onComplete);
* // other logic.
* });
* assetManager.parser.register('.asset', (file, options, onComplete) => {
* var json = JSON.parse(file);
@@ -440,20 +469,20 @@ export class AssetManager {
* var model = json[options.model];
* onComplete(null, {skin, model});
* });
* assetManager.loadAny({ url: 'http://example.com/my.asset', skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' });
* assetManager.loadAny({ url: 'http://example.com/my.asset' }, { skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' });
*
*/
public loadAny (requests: Request, options: IOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void;
public loadAny (requests: Request, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void;
public loadAny (requests: Request, options: IOptions | null, onComplete?: CompleteCallbackWithData | null): void;
public loadAny<T extends Asset> (requests: string, onComplete?: CompleteCallbackWithData<T> | null): void;
public loadAny<T extends Asset> (requests: string[], onComplete?: CompleteCallbackWithData<T[]> | null): void;
public loadAny (requests: Request, onComplete?: CompleteCallbackWithData | null): void;
public loadAny (requests: string | string[] | IRequest | Array<IRequest>, options: { [key: string]: any, preset?: string } | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: any) => void) | null): void;
public loadAny (requests: string | string[] | IRequest | Array<IRequest>, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: any) => void) | null): void;
public loadAny (requests: string | string[] | IRequest | Array<IRequest>, options: { [key: string]: any, preset?: string } | null, onComplete?: ((err: Error | null, data: any) => void) | null): void;
public loadAny<T extends Asset> (requests: string, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public loadAny<T extends Asset> (requests: string[], onComplete?: ((err: Error | null, data: T[]) => void) | null): void;
public loadAny (requests: string | string[] | IRequest | Array<IRequest>, onComplete?: ((err: Error | null, data: any) => void) | null): void;
public loadAny (
requests: Request,
options?: IOptions | ProgressCallback | CompleteCallbackWithData | null,
onProgress?: ProgressCallback | CompleteCallbackWithData | null,
onComplete?: CompleteCallbackWithData | null,
requests: string | string[] | IRequest | Array<IRequest>,
options?: { [key: string]: any, preset?: string } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: any) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: any) => void) | null,
onComplete?: ((err: Error | null, data: any) => void) | null,
) {
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete);
opts.preset = opts.preset || 'default';
@@ -466,40 +495,44 @@ export class AssetManager {
* @en
* General interface used to preload assets with a progression callback and a complete callback.It is highly recommended that you use
* more simple API, such as `preloadRes`, `preloadResDir` etc. Everything about preload is just likes `assetManager.loadAny`, the
* difference is `assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `assetManager.loadAny(preloadTask)`
* difference is `assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `assetManager.loadAny()`
* to finish loading asset
*
* @zh
* 通用预加载资源接口,可传入进度回调以及完成回调,非常建议你使用更简单的 API ,例如 `preloadRes`, `preloadResDir` 等。`preloadAny` 和 `loadAny`
* 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `assetManager.loadAny(preloadTask)` 来完成资源加载。
* 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `assetManager.loadAny()` 来完成资源加载。
*
* @param requests - The request you want to preload
* @param options - Optional parameters
* @param onProgress - Callback invoked when progression change
* @param onProgress.finished - The number of the items that are already completed
* @param onProgress.total - The total number of the items
* @param onProgress.item - The current request item
* @param onComplete - Callback invoked when finish preloading
* @param onComplete.err - The error occurred in preloading process.
* @param onComplete.items - The preloaded content
* @param requests @en The preloading requests. @zh 预加载请求。
* @param options @en Optional parameters. @zh 可选参数。
* @param onProgress @en Callback invoked when the preloading progress change. @zh 预加载进度发生变化时执行的回调。
* @param onProgress.finished
* @en The number of request items that have finished preloading.
* @zh 已经完成加载的资源数量。
* @param onProgress.total @en The number of all request items to be preloaded. @zh 所有待预加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。
* @param onComplete @en Callback invoked when all assets preloaded. @zh 所有资源预加载完成后的回调。
* @param onComplete.err
* @en The error occurred in preloading process. Or null if preloaded successfully.
* @zh 预加载过程中的发生的错误,如果预加载成功则为 null。
* @param onComplete.items @en The preloaded content. @zh 完成预加载的内容。
*
* @example
* assetManager.preloadAny('0cbZa5Y71CTZAccaIFluuZ', (err) => assetManager.loadAny('0cbZa5Y71CTZAccaIFluuZ'));
*
*/
public preloadAny (
requests: Request,
options: IOptions | null,
onProgress: ProgressCallback | null,
onComplete: CompleteCallbackWithData<RequestItem[]>|null): void;
public preloadAny (requests: Request, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void;
public preloadAny (requests: Request, options: IOptions | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void;
public preloadAny (requests: Request, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void;
requests: string | string[] | IRequest | Array<IRequest>,
options: { [key: string]: any, preset?: string } | null,
onProgress: ((finished: number, total: number, item: RequestItem) => void) | null,
onComplete: ((err: Error | null, data: RequestItem[]) => void)|null): void;
public preloadAny (requests: string | string[] | IRequest | Array<IRequest>, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadAny (requests: string | string[] | IRequest | Array<IRequest>, options: { [key: string]: any, preset?: string } | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadAny (requests: string | string[] | IRequest | Array<IRequest>, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadAny (
requests: Request,
options?: IOptions | ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null,
onProgress?: ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null,
onComplete?: CompleteCallbackWithData<RequestItem[]> | null,
requests: string | string[] | IRequest | Array<IRequest>,
options?: { [key: string]: any, preset?: string } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null,
onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null,
) {
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete);
opts.preset = opts.preset || 'preload';
@@ -510,18 +543,25 @@ export class AssetManager {
/**
* @en
* Load remote asset with url, such as audio, image, text and so on.
* Loads remote asset with url, such as audio, image, text and so on.
* Note that `loadRemote` uses the extension name in the url to determine how to load the asset.
* If you pass in a url without the extension name, you need to specify the `ext` parameter
* in the `options` to indicate how you want the asset loaded. See the third example below.
*
* @zh
* 使用 url 加载远程资源,例如音频,图片,文本等等。
* 使用 url 加载远程资源,例如音频,图片,文本等等。需要注意的是 `loadRemote` 是通过 url 中的扩展名判断以何种方式加载该资源,
* 如果你传入的 url 中没有携带后缀名,你需要额外指定 `options` 中的 `ext` 参数来表明你需要何种方式加载该资源。请参考下面的第三个示例。
*
* @param url - The url of asset
* @param options - Some optional parameters
* @param options.audioLoadMode - Indicate which mode audio you want to load
* @param options.ext - If the url does not have a extension name, you can specify one manually.
* @param onComplete - Callback invoked when finish loading
* @param onComplete.err - The error occurred in loading process.
* @param onComplete.asset - The loaded texture
* @param url @en The url of asset. @zh 资源的 URL 链接。
* @param options @en Some optional parameters. @zh 一些可选参数。
* @param options.ext
* @en If the url does not have an extension name, you can specify one manually. This will affect the way the assets are loaded.
* @zh 如果 URL 链接中没有包含扩展名,你可以手动指定一个扩展名。这将会影响资源的加载方式。
* @param onComplete @en Callback invoked when finish loading. @zh 当完成加载时触发的回调函数。
* @param onComplete.err @en The error occurred in loading process. Or null if loaded successfully. @zh 加载过程中出现的错误,如果加载成功则为 null。
* @param onComplete.asset
* @en The loaded asset. If there is an error in the loading process, this asset will be null.
* @zh 加载好的资源,如果加载过程出现了错误,资源将会 null。
*
* @example
* assetManager.loadRemote('http://www.cloud.com/test1.jpg', (err, texture) => console.log(err));
@@ -529,10 +569,10 @@ export class AssetManager {
* assetManager.loadRemote('http://www.cloud.com/test3', { ext: '.png' }, (err, texture) => console.log(err));
*
*/
public loadRemote<T extends Asset> (url: string, options: IRemoteOptions | null, onComplete?: CompleteCallbackWithData<T> | null): void;
public loadRemote<T extends Asset> (url: string, onComplete?: CompleteCallbackWithData<T> | null): void;
public loadRemote<T extends Asset> (url: string, options?: IRemoteOptions | CompleteCallbackWithData<T> | null, onComplete?: CompleteCallbackWithData<T> | null) {
const { options: opts, onComplete: onComp } = parseParameters<CompleteCallbackWithData<T>>(options, undefined, onComplete);
public loadRemote<T extends Asset> (url: string, options: { [k: string]: any, ext?: string } | null, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public loadRemote<T extends Asset> (url: string, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public loadRemote<T extends Asset> (url: string, options?: { [k: string]: any, ext?: string } | ((err: Error | null, data: T) => void) | null, onComplete?: ((err: Error | null, data: T) => void) | null) {
const { options: opts, onComplete: onComp } = parseParameters<((err: Error | null, data: T) => void)>(options, undefined, onComplete);
if (!opts.reloadAsset && this.assets.has(url)) {
asyncify(onComp)(null, this.assets.get(url));
@@ -555,26 +595,42 @@ export class AssetManager {
/**
* @en
* load bundle
* loads bundle with bundle name or URL. When you have configured a bundle in your project, you can load the bundle by the name configured in your project.
* Or when you put the bundle on the server, you can also load it by the full url address.
*
* Note: When you load a remote bundle by name, the bundle will be cached locally after download and will continue to use that cache in future, even if
* the version of the bundle file on your server has changed. When you need to load the latest bundle, you can pass an additional `version` parameter in the
* optional parameters and the asset system will compare this version number with the local cache, if the comparison fails, the asset system will pull
* the latest version of the bundle data from the server again.
*
* @zh
* 加载资源包
* 通过包名称或 url 加载资源包。当你在项目中配置了 Bundle 后,你可以通过项目中配置的名称来加载该 Bundle。
* 或者当你将 bundle 放在服务器上时,你也可以通过完整的 url 地址进行加载。
*
* @param nameOrUrl - The name or root path of bundle
* @param options - Some optional paramter, same like downloader.downloadFile
* @param options.version - The version of this bundle, you can check config.json in this bundle
* @param onComplete - Callback when bundle loaded or failed
* @param onComplete.err - The occurred error, null indicates success
* @param onComplete.bundle - The loaded bundle
* 注意:当你用名称加载远程 bundle 时,该 bundle 在下载后将会缓存在本地并在后续持续使用该缓存,即使你服务器上的 bundle 文件版本已经发生变化。当你需要加载
* 最新的 bundle 时,你可以在可选参数中额外传入一个 `version` 参数,资源系统将比对此版本号与本地缓存是否一致,如果比对失败,则资源系统将重新从服务器上拉取
* 最新版本的 bundle 数据。
*
* @param nameOrUrl @en The name or root path of bundle. @zh 待加载的 bundle 在项目中的名称或在服务器上的 url 路径。
* @param options @en Some optional parameters. @zh 一些可选参数。
* @param options.version
* @en The version of the bundle, which you can get in the editor's build system, or directly by looking at the md5 hash value in the `config.json` path in the bundle directory after the build.
* @zh bundle 的版本号,你可以在编辑器的构建系统中获取,或者直接查看构建后的 bundle 目录中 config.json 路径中的 md5 hash 值。
* @param onComplete @en Callback invoked when bundle loaded or failed. @zh bundle 加载完成的回调。
* @param onComplete.err @en The occurred error during the loading, Or null if loaded successfully. @zh 加载过程中发生的错误,如果加载成功则为 null。
* @param onComplete.bundle
* @en The loaded bundle. If there is an error in the loading process, this bundle will be null.
* @zh 加载完成的 bundle。如果加载过程中出现了错误,则为 null。
*
* @example
* loadBundle('myBundle', (err, bundle) => console.log(bundle));
* loadBundle('http://localhost:8080/test', null, (err, bundle) => console.log(err));
*
*/
public loadBundle (nameOrUrl: string, options: IBundleOptions | null, onComplete?: CompleteCallbackWithData<Bundle> | null): void;
public loadBundle (nameOrUrl: string, onComplete?: CompleteCallbackWithData<Bundle> | null): void;
public loadBundle (nameOrUrl: string, options?: IBundleOptions | CompleteCallbackWithData<Bundle> | null, onComplete?: CompleteCallbackWithData<Bundle> | null) {
const { options: opts, onComplete: onComp } = parseParameters<CompleteCallbackWithData<Bundle>>(options, undefined, onComplete);
public loadBundle (nameOrUrl: string, options: { [k: string]: any, version?: string } | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void;
public loadBundle (nameOrUrl: string, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void;
public loadBundle (nameOrUrl: string, options?: { [k: string]: any, version?: string } | ((err: Error | null, data: Bundle) => void) | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null) {
const { options: opts, onComplete: onComp } = parseParameters<((err: Error | null, data: Bundle) => void)>(options, undefined, onComplete);
const bundleName = path.basename(nameOrUrl);
@@ -611,7 +667,7 @@ export class AssetManager {
* 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。
* 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。
*
* @param asset - The asset to be released
* @param asset @en The asset to be released. @zh 被释放的资源。
*
* @example
* // release a texture which is no longer need
@@ -627,7 +683,7 @@ export class AssetManager {
* Release all unused assets. Refer to [[releaseAsset]] for detailed information.
*
* @zh
* 释放所有没有用到的资源。详细信息请参考 [[releaseAsset]]
* 释放所有没有用到的资源。详细信息请参考 [[releaseAsset]]。
*
* @engineInternal
*
@@ -643,7 +699,7 @@ export class AssetManager {
* Release all assets. Refer to [[releaseAsset]] for detailed information.
*
* @zh
* 释放所有资源。详细信息请参考 [[releaseAsset]]
* 释放所有资源。详细信息请参考 [[releaseAsset]]。
*
*/
public releaseAll () {
@@ -657,25 +713,25 @@ export class AssetManager {
* @param json
* @param options
* @param onComplete
* @private
* @internal
*/
public loadWithJson<T extends Asset> (
json: Record<string, any>,
options: IJsonAssetOptions | null,
onProgress: ProgressCallback | null,
onComplete: CompleteCallbackWithData<T> | null): void;
public loadWithJson<T extends Asset> (json: Record<string, any>, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T> | null): void;
public loadWithJson<T extends Asset> (json: Record<string, any>, options: IJsonAssetOptions | null, onComplete?: CompleteCallbackWithData<T> | null): void;
public loadWithJson<T extends Asset> (json: Record<string, any>, onComplete?: CompleteCallbackWithData<T> | null): void;
options: { [key: string]: any, assetId?: string } | null,
onProgress: ((finished: number, total: number, item: RequestItem) => void) | null,
onComplete: ((err: Error | null, data: T) => void) | null): void;
public loadWithJson<T extends Asset> (json: Record<string, any>, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T) => void) | null): void;
public loadWithJson<T extends Asset> (json: Record<string, any>, options: { [key: string]: any, assetId?: string }, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public loadWithJson<T extends Asset> (json: Record<string, any>, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public loadWithJson<T extends Asset> (
json: Record<string, any>,
options?: IJsonAssetOptions | CompleteCallbackWithData<T> | null,
onProgress?: ProgressCallback | CompleteCallbackWithData<T> | null,
onComplete?: CompleteCallbackWithData<T> | null,
options?: { [key: string]: any, assetId?: string } | ((err: Error | null, data: T) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T) => void) | null,
onComplete?: ((err: Error | null, data: T) => void) | null,
) {
if (BUILD) { throw new Error('Only valid in Editor'); }
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<CompleteCallbackWithData<T>>(options, onProgress, onComplete);
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err: Error | null, data: T) => void)>(options, onProgress, onComplete);
const item = RequestItem.create();
item.isNative = false;
@@ -706,6 +762,10 @@ AssetManager.Cache = Cache;
AssetManager.RequestItem = RequestItem;
AssetManager.Bundle = Bundle;
AssetManager.BuiltinBundleName = BuiltinBundleName;
AssetManager.CacheManager = CacheManager;
AssetManager.Downloader = Downloader;
AssetManager.Parser = Parser;
AssetManager.DependUtil = DependUtil;
export declare namespace AssetManager {
export { Pipeline };
@@ -714,7 +774,19 @@ export declare namespace AssetManager {
export { RequestItem };
export { Bundle };
export { BuiltinBundleName };
export { CacheManager };
export type { ICache };
export type { IAssetInfo, IPackInfo, IAddressableInfo, ISceneInfo, IRequest };
export { DependUtil };
export { Downloader };
export { Parser };
}
export default cclegacy.assetManager = new AssetManager();
/**
* @en `assetManager` is a global singleton instance of [[AssetManager]].
* The engine uses `assetManager` to manage all asset and asset bundle, including loading, releasing, etc.
* @zh `assetManager` 为 [[AssetManager]] 的全局单例,引擎使用 `assetManager` 来完成所有资源和资源包的管理工作,包括加载,释放等。
*/
const assetManager = cclegacy.assetManager = AssetManager.instance;
export default assetManager;
cclegacy.AssetManager = AssetManager;
+235 -190
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-len */
/*
Copyright (c) 2019-2023 Xiamen Yaji Software Co., Ltd.
@@ -28,23 +29,23 @@ import { error, errorID, cclegacy } from '../../core';
import Config, { IAddressableInfo, IAssetInfo, IConfigOption, ISceneInfo } from './config';
import releaseManager from './release-manager';
import RequestItem from './request-item';
import { assets, AssetType, bundles, CompleteCallbackWithData, CompleteCallbackNoData, IAssetOptions, ProgressCallback, RequestType } from './shared';
import { assets, bundles, RequestType } from './shared';
import { parseLoadResArgs, parseParameters } from './utilities';
/**
* @en
* A bundle contains an amount of assets(includes scene), you can load, preload, release asset which is in this bundle
* A bundle contains an amount of assets(includes scene), you can load, preload, release asset which is in this bundle.
*
* @zh
* 一个包含一定数量资源(包括场景)的包,你可以加载,预加载,释放此包内的资源
* 一个包含一定数量资源(包括场景)的包,你可以加载,预加载,释放此包内的资源。
*
*/
export default class Bundle {
private _config: Config = new Config();
/**
* for internal use
* @private
* For internal use.
* @engineInternal
*/
public get config (): Config {
return this._config;
@@ -52,10 +53,10 @@ export default class Bundle {
/**
* @en
* The name of this bundle
* The name of this bundle.
*
* @zh
* 此 bundle 的名称
* 此 bundle 的名称。
*
*/
public get name (): string {
@@ -64,10 +65,10 @@ export default class Bundle {
/**
* @en
* The dependency of this bundle
* The dependent bundles of this bundle.
*
* @zh
* 此 bundle 的依赖
* 此 bundle 的依赖包。
*
*/
public get deps (): string[] {
@@ -76,10 +77,10 @@ export default class Bundle {
/**
* @en
* The root path of this bundle, such like 'http://example.com/bundle1'
* The root path of this bundle, such like 'http://example.com/bundle1'.
*
* @zh
* 此 bundle 的根路径, 例如 'http://example.com/bundle1'
* 此 bundle 的根路径, 例如 'http://example.com/bundle1'。
*
*/
public get base (): string {
@@ -88,56 +89,57 @@ export default class Bundle {
/**
* @en
* Get asset's info using path, only valid when asset is in bundle folder.
* Gets asset's info using path, only valid when asset is in bundle folder.
*
* @zh
* 使用 path 获取资源的配置信息
* 使用 path 获取资源的配置信息。
*
* @param path - The relative path of asset, such as 'images/a'
* @param type - The constructor of asset, such as `Texture2D`
* @returns The asset info
* @param path @en The relative path of asset, such as 'images/a'. @zh 资源的相对路径,例如 `images/a`。
* @param type @en The constructor of asset, such as `Texture2D`. @zh 资源的类型,例如 [[Texture2D]]。
* @returns @en The asset info. @zh 资源的信息。
*
* @example
* var info = bundle.getInfoWithPath('image/a', Texture2D);
* const info = bundle.getInfoWithPath('image/a', Texture2D);
*
*/
public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null {
public getInfoWithPath (path: string, type?: Constructor<Asset> | null): IAddressableInfo | null {
return this._config.getInfoWithPath(path, type);
}
/**
* @en
* Get all asset's info within specific folder
* Gets all asset's info within specific folder.
*
* @zh
* 获取在某个指定文件夹下的所有资源信息
* 获取在某个指定文件夹下的所有资源信息。
*
* @param path - The relative path of folder, such as 'images'
* @param type - The constructor should be used to filter paths
* @param out - The output array
* @returns Infos
* @param path @en The relative path of folder, such as 'images'. @zh 文件夹的相对路径,例如 `images`。
* @param type
* @en The asset type, can be used to find the information of the specified type of asset in the directory.
* @zh 资源的类型,指定后可以用来查找目录下指定类型的资源信息。
* @param out @en The output array. @zh 输出数组。
* @returns @en Queried asset information. @zh 查询到的资源信息。
*
* @example
* var infos = [];
* const infos = [];
* bundle.getDirWithPath('images', Texture2D, infos);
*/
public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] {
public getDirWithPath (path: string, type?: Constructor<Asset> | null, out?: IAddressableInfo[]): IAddressableInfo[] {
return this._config.getDirWithPath(path, type, out);
}
/**
* @en
* Get asset's info with uuid
* Get asset's information with uuid.
*
* @zh
* 通过 uuid 获取资源信息
* 通过 uuid 获取资源信息。
*
* @method getAssetInfo
* @param uuid - The asset's uuid
* @returns info
* @param uuid @en The asset's uuid. @zh 资源的 uuid。
* @returns @en The information of asset. @zh 资源的信息。
*
* @example
* var info = bundle.getAssetInfo('fcmR3XADNLgJ1ByKhqcC5Z');
* const info = bundle.getAssetInfo('fcmR3XADNLgJ1ByKhqcC5Z');
*
*/
public getAssetInfo (uuid: string): IAssetInfo | null {
@@ -146,17 +148,16 @@ export default class Bundle {
/**
* @en
* Get scene'info with name
* Gets scene's information with name.
*
* @zh
* 通过场景名获取场景信息
* 通过场景名获取场景信息。
*
* @method getSceneInfo
* @param name - The name of scene
* @return info
* @param name @en The name of scene. @zh 场景名称。
* @returns @en The information of scene. @zh 场景信息。
*
* @example
* var info = bundle.getSceneInfo('first.fire');
* const info = bundle.getSceneInfo('first.fire');
*
*/
public getSceneInfo (name: string): ISceneInfo | null {
@@ -165,12 +166,13 @@ export default class Bundle {
/**
* @en
* Initialize this bundle with options
* Initializes this bundle with options.
*
* @zh
* 初始化此 bundle
* 初始化此 bundle。
*
* @param options
* @deprecate Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*
*/
public init (options: IConfigOption) {
@@ -180,20 +182,30 @@ export default class Bundle {
/**
* @en
* Load the asset within this bundle by the path which is relative to bundle's path
* Loads the asset within this bundle by the path which is relative to bundle's path.
*
* @zh
* 通过相对路径加载分包中的资源。路径是相对分包文件夹路径的相对路径
* 通过相对路径加载分包中的资源。路径是相对分包文件夹路径的相对路径。
*
* @param paths - Paths of the target assets.The path is relative to the bundle's folder, extensions must be omitted.
* @param type - Only asset of type will be loaded if this argument is supplied.
* @param onProgress - Callback invoked when progression change.
* @param onProgress.finish - The number of the items that are already completed.
* @param onProgress.total - The total number of the items.
* @param onProgress.item - The finished request item.
* @param onComplete - Callback invoked when all assets loaded.
* @param onComplete.error - The error info or null if loaded successfully.
* @param onComplete.assets - The loaded assets.
* @param paths
* @en Paths of the target assets.These paths are relative to the bundle's folder, extension name must be omitted.
* @zh 需要加载的资源的路径。此路径为工程中相对于 bundle 文件夹的相对路径,路径中请不要带扩展名。
* @param type
* @en Asset type, if this parameter is passed, the asset of the corresponding type will be found in the assets of the corresponding path to finish loading.
* @zh 资源类型,如果传入此参数,则会在对应路径的资源中找到对应类型的资源完成加载。
* @param onProgress
* @en Callback invoked when the loading progress change.
* @zh 加载进度发生变化时执行的回调。
* @param onProgress.finish
* @en The number of request items that have been loaded.
* @zh 已经完成加载的资源数量。
* @param onProgress.total
* @en The number of all request items to be loaded.
* @zh 所有待加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的加载项。
* @param onComplete @en Callback invoked when all assets loaded. @zh 所有资源加载完成后的回调。
* @param onComplete.error @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。
* @param onComplete.assets @en The loaded asset, or null if an error occurred during loading. @zh 已加载的资源,如果加载过程中有错误发生,则为 null。
*
* @example
* // load the texture (${project}/assets/resources/textures/background.jpg) from resources
@@ -211,24 +223,24 @@ export default class Bundle {
*/
public load<T extends Asset> (
paths: string,
type: AssetType<T> | null,
onProgress: ProgressCallback | null,
onComplete: CompleteCallbackWithData<T> | null): void;
type: Constructor<T> | null,
onProgress: ((finished: number, total: number, item: RequestItem) => void) | null,
onComplete: ((err: Error | null, data: T) => void) | null): void;
public load<T extends Asset> (
paths: string[], type: AssetType<T> | null,
onProgress: ProgressCallback | null,
onComplete: CompleteCallbackWithData<T[]> | null): void;
public load<T extends Asset> (paths: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T> | null): void;
public load<T extends Asset> (paths: string[], onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void;
public load<T extends Asset> (paths: string, onComplete?: CompleteCallbackWithData<T> | null): void;
public load<T extends Asset> (paths: string[], onComplete?: CompleteCallbackWithData<T[]> | null): void;
public load<T extends Asset> (paths: string, type: AssetType<T> | null, onComplete?: CompleteCallbackWithData<T> | null): void;
public load<T extends Asset> (paths: string[], type: AssetType<T> | null, onComplete?: CompleteCallbackWithData<T[]> | null): void;
paths: string[], type: Constructor<T> | null,
onProgress: ((finished: number, total: number, item: RequestItem) => void) | null,
onComplete: ((err: Error | null, data: T[]) => void) | null): void;
public load<T extends Asset> (paths: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T) => void) | null): void;
public load<T extends Asset> (paths: string[], onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T[]) => void) | null): void;
public load<T extends Asset> (paths: string, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public load<T extends Asset> (paths: string[], onComplete?: ((err: Error | null, data: T[]) => void) | null): void;
public load<T extends Asset> (paths: string, type: Constructor<T> | null, onComplete?: ((err: Error | null, data: T) => void) | null): void;
public load<T extends Asset> (paths: string[], type: Constructor<T> | null, onComplete?: ((err: Error | null, data: T[]) => void) | null): void;
public load<T extends Asset> (
paths: string|string[],
type?: AssetType<T> | ProgressCallback | CompleteCallbackWithData<T|T[]> | null,
onProgress?: ProgressCallback | CompleteCallbackWithData<T|T[]> | null,
onComplete?: CompleteCallbackWithData<T|T[]> | null,
type?: Constructor<T> | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T|T[]) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T|T[]) => void) | null,
onComplete?: ((err: Error | null, data: T|T[]) => void) | null,
) {
const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete);
const options = { __requestType__: RequestType.PATH, type: _type, bundle: this.name, __outputAsArray__: Array.isArray(paths) };
@@ -237,24 +249,34 @@ export default class Bundle {
/**
* @en
* Preload the asset within this bundle by the path which is relative to bundle's path.
* After calling this method, you still need to finish loading by calling `Bundle.load`.
* It will be totally fine to call `Bundle.load` at any time even if the preloading is not
* yet finished
* Preloads the asset within this bundle by the path which is relative to bundle's path.
* After calling this method, you still need to finish loading by calling [[Bundle.load]].
* It will be totally fine to call [[Bundle.load]] at any time even if the preloading is not
* yet finished.
*
* @zh
* 通过相对路径预加载分包中的资源。路径是相对分包文件夹路径的相对路径。调用完后,你仍然需要通过 `Bundle.load` 来完成加载。
* 就算预加载还没完成,你也可以直接调用 `Bundle.load`。
* 通过相对路径预加载分包中的资源。路径是相对分包文件夹路径的相对路径。调用完后,你仍然需要通过 [[Bundle.load]] 来完成加载。
* 就算预加载还没完成,你也可以直接调用 [[Bundle.load]]。
*
* @param paths - Paths of the target asset.The path is relative to bundle folder, extensions must be omitted.
* @param type - Only asset of type will be loaded if this argument is supplied.
* @param onProgress - Callback invoked when progression change.
* @param onProgress.finish - The number of the items that are already completed.
* @param onProgress.total - The total number of the items.
* @param onProgress.item - The finished request item.
* @param onComplete - Callback invoked when the resource loaded.
* @param onComplete.error - The error info or null if loaded successfully.
* @param onComplete.items - The preloaded items.
* @param paths
* @en Paths of the target assets.These paths are relative to the bundle's folder, extension name must be omitted.
* @zh 需要加载的资源的路径。此路径为工程中相对于 bundle 文件夹的相对路径,路径中请不要带扩展名。
* @param type
* @en Asset type, if this parameter is passed, the asset of the corresponding type will be found in the assets of the corresponding path to finish preloading.
* @zh 资源类型,如果传入此参数,则会在对应路径的资源中找到对应类型的资源完成预加载。
* @param onProgress
* @en Callback invoked when the preloading progress change.
* @zh 预加载进度发生变化时执行的回调。
* @param onProgress.finish
* @en The number of request items that have been preloaded.
* @zh 已经完成预加载的资源数量。
* @param onProgress.total
* @en The number of all request items to be preloaded.
* @zh 所有待预加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。
* @param onComplete @en Callback invoked when all assets preloaded. @zh 所有资源预加载完成后的回调。
* @param onComplete.error @en Error message during preloading, or null if preloaded successfully. @zh 预加载过程中的错误信息,如果预加载成功则为 null。
* @param onComplete.items @en The preloaded items. @zh 预加载项。
*
* @example
* // preload the texture (${project}/assets/resources/textures/background.jpg) from resources
@@ -274,15 +296,15 @@ export default class Bundle {
* bundle2.load('imgs/cocos', SpriteFrame, (err, spriteFrame) => {});
*
*/
public preload (paths: string|string[], type: AssetType|null, onProgress: ProgressCallback|null, onComplete: CompleteCallbackWithData<RequestItem[]>|null): void;
public preload (paths: string|string[], onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void;
public preload (paths: string|string[], onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void;
public preload (paths: string|string[], type: AssetType | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void;
public preload (paths: string|string[], type: Constructor<Asset>|null, onProgress: ((finished: number, total: number, item: RequestItem) => void)|null, onComplete: ((err: Error | null, data: RequestItem[]) => void)|null): void;
public preload (paths: string|string[], onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preload (paths: string|string[], onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preload (paths: string|string[], type: Constructor<Asset> | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preload (
paths: string|string[],
type?: AssetType | ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null,
onProgress?: ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null,
onComplete?: CompleteCallbackWithData<RequestItem[]> | null,
type?: Constructor<Asset> | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null,
onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null,
) {
const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete);
cclegacy.assetManager.preloadAny(paths, { __requestType__: RequestType.PATH, type: _type, bundle: this.name }, onProg, onComp);
@@ -290,23 +312,28 @@ export default class Bundle {
/**
* @en
* Load all assets under a folder inside the bundle folder.<br>
* Loads all assets under a folder inside the bundle folder.<br>
* <br>
* Note: All asset paths in Creator use forward slashes, paths using backslashes will not work.
*
* @zh
* 加载目标文件夹中的所有资源, 注意:路径中只能使用斜杠,反斜杠将停止工作
* 加载目标文件夹中的所有资源, 注意:路径中只能使用斜杠,反斜杠将停止工作。
*
* @param dir - path of the target folder.The path is relative to the bundle folder, extensions must be omitted.
* @param type - Only asset of type will be loaded if this argument is supplied.
* @param onProgress - Callback invoked when progression change.
* @param onProgress.finish - The number of the items that are already completed.
* @param onProgress.total - The total number of the items.
* @param onProgress.item - The latest request item
* @param onComplete - A callback which is called when all assets have been loaded, or an error occurs.
* @param onComplete.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 onComplete.assets - An array of all loaded assets.
* @param dir @en The path of the target folder. The path is relative to the bundle folder. @zh 目标文件夹路径,此路径为相对于 bundle 文件夹的路径。
* @param type @en The asset type. Only specify type asset will be loaded if this argument is supplied. @zh 资源类型,如果指定了此参数,则只会加载目标文件夹下此类型的资源。
* @param onProgress
* @en Callback invoked when the loading progress change.
* @zh 加载进度发生变化时执行的回调。
* @param onProgress.finish
* @en The number of request items that have been loaded.
* @zh 已经完成加载的资源数量。
* @param onProgress.total
* @en The number of all request items to be loaded.
* @zh 所有待加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的加载项。
* @param onComplete @en Callback invoked when all assets loaded. @zh 所有资源加载完成后的回调。
* @param onComplete.error @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。
* @param onComplete.assets @en An array of all loaded assets. @zh 完成加载的资源数组。
*
* @example
* // load all audios (resources/audios/)
@@ -325,15 +352,15 @@ export default class Bundle {
* bundle2.loadDir('skills', SpriteFrame, null, (err, spriteFrames) => console.log(err));
*
*/
public loadDir<T extends Asset> (dir: string, type: AssetType<T> | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void;
public loadDir<T extends Asset> (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void;
public loadDir<T extends Asset> (dir: string, onComplete?: CompleteCallbackWithData<T[]> | null): void;
public loadDir<T extends Asset> (dir: string, type: AssetType<T> | null, onComplete?: CompleteCallbackWithData<T[]> | null): void;
public loadDir<T extends Asset> (dir: string, type: Constructor<T> | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T[]) => void) | null): void;
public loadDir<T extends Asset> (dir: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: T[]) => void) | null): void;
public loadDir<T extends Asset> (dir: string, onComplete?: ((err: Error | null, data: T[]) => void) | null): void;
public loadDir<T extends Asset> (dir: string, type: Constructor<T> | null, onComplete?: ((err: Error | null, data: T[]) => void) | null): void;
public loadDir<T extends Asset> (
dir: string,
type?: AssetType<T> | ProgressCallback | CompleteCallbackWithData<T[]> | null,
onProgress?: ProgressCallback | CompleteCallbackWithData<T[]> | null,
onComplete?: CompleteCallbackWithData<T[]> | null,
type?: Constructor<T> | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T[]) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T[]) => void) | null,
onComplete?: ((err: Error | null, data: T[]) => void) | null,
) {
const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete);
cclegacy.assetManager.loadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name, __outputAsArray__: true }, onProg, onComp);
@@ -341,24 +368,29 @@ export default class Bundle {
/**
* @en
* Preload all assets under a folder inside the bundle folder.<br> After calling this method, you still need to
* finish loading by calling `Bundle.loadDir`.
* It will be totally fine to call `Bundle.loadDir` at any time even if the preloading is not yet finished
* Preloads all assets under a folder inside the bundle folder.<br> After calling this method, you still need to
* finish loading by calling [[Bundle.loadDir]].
* It will be totally fine to call [[Bundle.loadDir]] at any time even if the preloading is not yet finished.
*
* @zh
* 预加载目标文件夹中的所有资源。调用完后,你仍然需要通过 `Bundle.loadDir` 来完成加载。
* 就算预加载还没完成,你也可以直接调用 `Bundle.loadDir`。
* 预加载目标文件夹中的所有资源。调用完后,你仍然需要通过 [[Bundle.loadDir]] 来完成加载。
* 就算预加载还没完成,你也可以直接调用 [[Bundle.loadDir]]。
*
* @param dir - path of the target folder.The path is relative to the bundle folder, extensions must be omitted.
* @param type - Only asset of type will be preloaded if this argument is supplied.
* @param onProgress - Callback invoked when progression change.
* @param onProgress.finish - The number of the items that are already completed.
* @param onProgress.total - The total number of the items.
* @param onProgress.item - The latest request item
* @param onComplete - A callback which is called when all assets have been loaded, or an error occurs.
* @param onComplete.error - If one of the asset failed, the complete callback is immediately called with the error.
* If all assets are preloaded successfully, error will be null.
* @param onComplete.items - An array of all preloaded items.
* @param dir @en The path of the target folder. The path is relative to the bundle folder. @zh 目标文件夹路径,此路径为相对于 bundle 文件夹的路径。
* @param type @en The asset type. Only specify type asset will be preloaded if this argument is supplied. @zh 资源类型,如果指定了此参数,则只会预加载目标文件夹下此类型的资源。
* @param onProgress
* @en Callback invoked when the preloading progress change.
* @zh 预加载进度发生变化时执行的回调。
* @param onProgress.finish
* @en The number of request items that have been preloaded.
* @zh 已经完成预加载的资源数量。
* @param onProgress.total
* @en The number of all request items to be preloaded.
* @zh 所有待预加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。
* @param onComplete @en Callback invoked when all assets preloaded. @zh 所有资源预加载完成后的回调。
* @param onComplete.error @en Error message during preloading, or null if preloaded successfully. @zh 预加载过程中的错误信息,如果预加载成功则为 null。
* @param onComplete.items @en The preloaded items. @zh 预加载项。
*
* @example
* // preload all audios (resources/audios/)
@@ -377,15 +409,15 @@ export default class Bundle {
* // wait for while
* bundle2.loadDir('skills', SpriteFrame, (err, spriteFrames) => {});
*/
public preloadDir (dir: string, type: AssetType | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void;
public preloadDir (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void;
public preloadDir (dir: string, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void;
public preloadDir (dir: string, type: AssetType | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void;
public preloadDir (dir: string, type: Constructor<Asset> | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadDir (dir: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadDir (dir: string, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadDir (dir: string, type: Constructor<Asset> | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null): void;
public preloadDir (
dir: string,
type?: AssetType | ProgressCallback | CompleteCallbackWithData<RequestItem[]>| null,
onProgress?: ProgressCallback | CompleteCallbackWithData<RequestItem[]>| null,
onComplete?: CompleteCallbackWithData<RequestItem[]>| null,
type?: Constructor<Asset> | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void)| null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void)| null,
onComplete?: ((err: Error | null, data: RequestItem[]) => void)| null,
) {
const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete);
cclegacy.assetManager.preloadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name }, onProg, onComp);
@@ -398,31 +430,37 @@ export default class Bundle {
* @zh
* 通过场景名称加载分包中的场景资源。
*
* @param sceneName - The name of the scene to load.
* @param options - Some optional parameters
* @param onProgress - Callback invoked when progression change.
* @param onProgress.finish - The number of the items that are already completed.
* @param onProgress.total - The total number of the items.
* @param onProgress.item - The latest request item
* @param onComplete - callback, will be called after scene launched.
* @param onComplete.err - The occurred error, null indicetes success
* @param onComplete.sceneAsset - The scene asset
* @param sceneName @en The name of the scene to be loaded. @zh 待加载的场景名称。
* @param options @en Some optional parameters. @zh 可选参数。
* @param onProgress
* @en Callback invoked when the loading progress change.
* @zh 加载进度发生变化时执行的回调。
* @param onProgress.finish
* @en The number of request items that have been loaded.
* @zh 已经完成加载的资源数量。
* @param onProgress.total
* @en The number of all request items to be loaded.
* @zh 所有待加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的加载项。
* @param onComplete @en Callback invoked when the scene loaded. @zh 场景加载完成后的回调。
* @param onComplete.error @en Error message during loading, or null if loaded successfully. @zh 加载过程中的错误信息,如果加载成功则为 null。
* @param onComplete.sceneAsset @en The scene asset. @zh 加载完成的场景资源。
*
* @example
* bundle1.loadScene('first', (err, sceneAsset) => director.runScene(sceneAsset));
*
*/
public loadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<SceneAsset> | null): void;
public loadScene (sceneName: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<SceneAsset> | null): void;
public loadScene (sceneName: string, options: IAssetOptions | null, onComplete?: CompleteCallbackWithData<SceneAsset> | null): void;
public loadScene (sceneName: string, onComplete?: CompleteCallbackWithData<SceneAsset> | null): void;
public loadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: SceneAsset) => void) | null): void;
public loadScene (sceneName: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err: Error | null, data: SceneAsset) => void) | null): void;
public loadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onComplete?: ((err: Error | null, data: SceneAsset) => void) | null): void;
public loadScene (sceneName: string, onComplete?: ((err: Error | null, data: SceneAsset) => void) | null): void;
public loadScene (
sceneName: string,
options?: IAssetOptions | ProgressCallback | CompleteCallbackWithData<SceneAsset> | null,
onProgress?: ProgressCallback | CompleteCallbackWithData<SceneAsset> | null,
onComplete?: CompleteCallbackWithData<SceneAsset> | null,
options?: { [key: string]: any, preset?: 'string' } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: SceneAsset) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: SceneAsset) => void) | null,
onComplete?: ((err: Error | null, data: SceneAsset) => void) | null,
) {
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<CompleteCallbackWithData<SceneAsset>>(options, onProgress, onComplete);
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err: Error | null, data: SceneAsset) => void)>(options, onProgress, onComplete);
opts.preset = opts.preset || 'scene';
opts.bundle = this.name;
@@ -443,21 +481,27 @@ export default class Bundle {
/**
* @en
* Preload the scene asset within this bundle by its name. After calling this method, you still need to finish loading
* by calling `Bundle.loadScene` or `director.loadScene`.It will be totally fine to call `Bundle.loadDir` at any
* time even if the preloading is not yet finished
* by calling [[Bundle.loadScene]] or [[Director.loadScene]].It will be totally fine to call [[Bundle.loadScene]] at any
* time even if the preloading is not yet finished.
*
* @zh
* 通过场景名称预加载分包中的场景资源.调用完后,你仍然需要通过 `Bundle.loadScene` 或 `director.loadScene` 来完成加载。
* 就算预加载还没完成,你也可以直接调用 `Bundle.loadScene` 或 `director.loadScene`。
* 通过场景名称预加载分包中的场景资源.调用完后,你仍然需要通过 [[Bundle.loadScene]] 或 [[Director.loadScene]] 来完成加载。
* 就算预加载还没完成,你也可以直接调用 [[Bundle.loadScene]] 或 [[Director.loadScene]]。
*
* @param sceneName - The name of the scene to preload.
* @param options - Some optional parameters
* @param onProgress - callback, will be called when the load progression change.
* @param onProgress.finish - The number of the items that are already completed
* @param onProgress.total - The total number of the items
* @param onProgress.item The latest request item
* @param onComplete - callback, will be called after scene loaded.
* @param onComplete.error - null or the error object.
* @param sceneName @en The name of the scene to be preloaded. @zh 待预加载的场景名称。
* @param options @en Some optional parameters. @zh 可选参数。
* @param onProgress
* @en Callback invoked when the preloading progress change.
* @zh 预加载进度发生变化时执行的回调。
* @param onProgress.finish
* @en The number of request items that have been preloaded.
* @zh 已经完成预加载的资源数量。
* @param onProgress.total
* @en The number of all request items to be preloaded.
* @zh 所有待预加载的资源数量。
* @param onProgress.item @en The finished request item. @zh 当前完成的预加载项。
* @param onComplete @en Callback invoked when the scene preloaded. @zh 场景预加载完成后的回调。
* @param onComplete.error @en Error message during preloading, or null if preloaded successfully. @zh 预加载过程中的错误信息,如果预加载成功则为 null。
*
* @example
* bundle1.preloadScene('first');
@@ -465,17 +509,17 @@ export default class Bundle {
* bundle1.loadScene('first', (err, scene) => director.runScene(scene));
*
*/
public preloadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback, onComplete: CompleteCallbackNoData | null): void;
public preloadScene (sceneName: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackNoData | null): void;
public preloadScene (sceneName: string, options: IAssetOptions | null, onComplete?: CompleteCallbackNoData | null): void;
public preloadScene (sceneName: string, onComplete?: CompleteCallbackNoData | null): void;
public preloadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onProgress: ((finished: number, total: number, item: RequestItem) => void), onComplete: ((err?: Error | null) => void) | null): void;
public preloadScene (sceneName: string, onProgress: ((finished: number, total: number, item: RequestItem) => void) | null, onComplete: ((err?: Error | null) => void) | null): void;
public preloadScene (sceneName: string, options: { [key: string]: any, preset?: 'string' } | null, onComplete?: ((err?: Error | null) => void) | null): void;
public preloadScene (sceneName: string, onComplete?: ((err?: Error | null) => void) | null): void;
public preloadScene (
sceneName: string,
options?: IAssetOptions | ProgressCallback | CompleteCallbackNoData | null,
onProgress?: ProgressCallback | CompleteCallbackNoData | null,
onComplete?: CompleteCallbackNoData | null,
options?: { [key: string]: any, preset?: 'string' } | ((finished: number, total: number, item: RequestItem) => void) | ((err?: Error | null) => void) | null,
onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err?: Error | null) => void) | null,
onComplete?: ((err?: Error | null) => void) | null,
) {
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<CompleteCallbackNoData>(options, onProgress, onComplete);
const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err?: Error | null) => void)>(options, onProgress, onComplete);
opts.bundle = this.name;
cclegacy.assetManager.preloadAny({ scene: sceneName }, opts, onProg, (err) => {
@@ -488,27 +532,28 @@ export default class Bundle {
/**
* @en
* Get cached asset within this bundle by path and type. <br>
* Gets cached asset within this bundle by path and type. <br>
* After you load asset with [[load]] or [[loadDir]],
* you can acquire them by passing the path to this API.
*
* NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`,
* otherwise it may return some other resources with the same name!
* NOTE:When there are multiple asset with the same name, you can get the specific asset by specifying the type.
* Otherwise the first asset matching that name will be returned.
*
* @zh
* 通过路径与类型获取已缓存资源。在你使用 [[load]] 或者 [[loadDir]] 之后,
* 你能通过传路径通过这个 API 获取到这些资源。
*
* 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会获取到其他同名资源
* 注意:当有多个同名的资产时,你可以通过指定类型来获得具体的资产。
* 否则将返回与该名称相匹配的第一个资产。
*
* @param path - The path of asset
* @param type - Only asset of type will be returned if this argument is supplied.
* @returns - the asset has been cached
* @param path @en The path of asset. @zh 资源的路径。
* @param type @en The asset type. Only specify type asset will be returned if this argument is supplied. @zh 资源类型,指定后只会返回该类型的资源。
* @returns @en The asset has been cached. @zh 已缓存的资源。
*
* @example
* bundle1.get('music/hit', AudioClip);
*/
public get<T extends Asset> (path: string, type?: AssetType<T> | null): T | null {
public get<T extends Asset> (path: string, type?: Constructor<T> | null): T | null {
const info = this.getInfoWithPath(path, type);
if (info) {
return assets.get(info.uuid) as T || null;
@@ -519,27 +564,28 @@ export default class Bundle {
/**
* @en
* Release the asset loaded by [[load]] or [[loadDir]]
* and it's dependencies. Refer to [[AssetManager.releaseAsset]] for detailed informations.
* Releases the asset loaded by [[load]] or [[loadDir]].
* and it's dependencies. Refer to [[AssetManager.releaseAsset]] for detailed information.
*
* NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`,
* otherwise it may release some other resources with the same name!
* NOTE:When there are multiple asset with the same name, you can specify the asset to be released by specifying the type.
* Otherwise the first resource matching that name will be released.
*
* @zh
* 释放通过 [[load]] 或者 [[loadDir]] 加载的资源。
* 详细信息请参考 [[AssetManager.releaseAsset]]
* 详细信息请参考 [[AssetManager.releaseAsset]]。
*
* 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会释放到其他同名资源
* 注意:当存在多个资源同名时,可以通过指定类型来指定要释放的资源,否则将释放第一个匹配该名称的资源。
*
* @param path - The path of asset
* @param type - Only asset of type will be released if this argument is supplied.
* @param path @en The path of asset. @zh 资源的路径。
* @param type @en The type of asset. @zh 资源的类型。
*
* @example
* // release a texture which is no longer need
* bundle1.release('misc/character/cocos');
*
*/
public release (path: string, type?: AssetType | null) {
public release (path: string, type?: Constructor<Asset> | null) {
const asset = this.get(path, type);
if (asset) {
releaseManager.tryRelease(asset, true);
@@ -548,17 +594,16 @@ export default class Bundle {
/**
* @en
* Release all unused assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed informations.
* Release all unused assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed information.
*
* @zh
* 释放此包中的所有没有用到的资源。详细信息请参考 [[AssetManager.releaseAll]]
*
* @private
* 释放此包中的所有没有用到的资源。详细信息请参考 [[AssetManager.releaseAll]]。
*
* @example
* // release all unused asset within bundle1
* bundle1.releaseUnusedAssets();
*
* @engineInternal
*/
public releaseUnusedAssets () {
assets.forEach((asset) => {
@@ -574,7 +619,7 @@ export default class Bundle {
* Release all assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed information.
*
* @zh
* 释放此包中的所有资源。详细信息请参考 [[AssetManager.releaseAll]]
* 释放此包中的所有资源。详细信息请参考 [[AssetManager.releaseAll]]。
*
* @example
* // release all asset within bundle1
@@ -599,10 +644,10 @@ export default class Bundle {
/**
* @en
* resources is a bundle and controls all asset under assets/resources
* A [[Bundle]] instance to manage all assets in assets/resources.
*
* @zh
* resources 是一个 bundle,用于管理所有在 assets/resources 下的资源
* 一个 [[Bundle]] 实例,用于管理所有在 assets/resources 下的资源。
*/
export const resources: Bundle = new Bundle();
cclegacy.resources = resources;
+29 -28
View File
@@ -27,123 +27,124 @@ import Cache from './cache';
/**
* @en
* Cache manager is a module which controls all caches downloaded from server in non-web platform, it is a singleton
* All member can be accessed with `assetManager.cacheManager`.
* You can access it via [[AssetManager.cacheManager]].
*
* @zh
* 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存,这是一个单例,所有成员能通过 `assetManager.cacheManager` 访问。
* 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存,这是一个单例,你能通过 [[AssetManager.cacheManager]] 访问它。
*
*/
export default abstract class CacheManager {
/**
* @en
* The name of cacheDir
* The name of cache directory.
*
* @zh
* 缓存目录的名称
* 缓存目录的名称。
*/
public abstract cacheDir: string;
/**
* @en
* Whether or not cache asset into user's storage space, this property only works on mini-game platforms
* Whether to cache file into user's storage space, this property only works on mini-game platforms.
*
* @zh
* 是否缓存资源到用户存储空间,此属性只在小游戏平台有效
* 是否缓存文件到用户存储空间,此属性只在小游戏平台有效。
*
*/
public abstract cacheEnabled: boolean;
/**
* @en
* Whether or not auto clear cache when storage ran out, this property only works on mini-game platforms
* Whether to clear cache automatically when storage ran out, this property only works on mini-game platforms.
*
* @zh
* 是否在存储空间满了后自动清理缓存,此属性只在小游戏平台有效
* 是否在存储空间满了后自动清理缓存,此属性只在小游戏平台有效。
*
*/
public abstract autoClear: boolean;
/**
* @en
* The interval between caching resources, this property only works on mini-game platforms, unit: ms
* The interval between caching file, this property only works on mini-game platforms, unit: ms.
*
* @zh
* 缓存资源的间隔时间,此属性只在小游戏平台有效,单位:毫秒
* 缓存文件的间隔时间,此属性只在小游戏平台有效,单位:毫秒。
*
*/
public abstract cacheInterval: number;
/**
* @en
* The interval between deleting resources, when you use `cleanLRU`, the resources will be deleted as this interval, unit: ms
* The interval between deleting file, when you use `cleanLRU`, the file will be deleted as this interval, unit: ms.
*
* @zh
* 清理资源的间隔时间,当你使用 `cleanLRU` 时,资源将以此间隔被删除,单位:毫秒
* 清理资源的间隔时间,当你使用 `cleanLRU` 时,资源将以此间隔被删除,单位:毫秒。
*
*/
public abstract deleteInterval: number;
/**
* @en
* List of all cached files
* List of all cached files.
*
* @zh
* 所有缓存文件列表
* 所有缓存文件列表。
*
*/
public abstract cachedFiles: Cache<{ bundle: string, url: string, lastTime: number }>;
/**
* @en
* Get cached path with origin url
* Gets cached path with origin url.
*
* @zh
* 通过原始 url 获取缓存后的路径
* 通过原始 url 获取缓存后的路径。
*
* @param originUrl
* @returns The cached path
* @param originUrl @en The origin url of file. @zh 文件的原始 url。
* @returns @en The path where the file is cached. @zh 该文件所缓存的路径。
*/
public abstract getCache (originUrl: string): string;
/**
* @en
* Get temporary path with origin url, this method only works on mini-game platforms
* Gets temporary path with origin url, this method only works on mini-game platforms.
*
* @zh
* 通过原始 url 获取临时文件的路径,此方法只在小游戏平台有效
* 通过原始 url 获取临时文件的路径,此方法只在小游戏平台有效。
*
* @param originUrl
* @returns The temp path
* @param originUrl @en The origin url of file. @zh 文件的原始 url。
* @returns @en The temporary path where the file is stored. @zh 该文件所存储的临时路径。
*/
public abstract getTemp (originUrl: string): string;
/**
* @en
* Clear all caches, please use with caution, If necessary, we recommend using it before the game is launched
* Clear all caches, please use with caution, If necessary, we recommend using it before the game is launched.
*
* @zh
* 清空所有缓存,请谨慎使用,如果必要的话,我们建议在游戏启动之前使用
* 清空所有缓存,请谨慎使用,如果必要的话,我们建议在游戏启动之前使用。
*
*/
public abstract clearCache (): void;
/**
* @en
* Clear part of caches with LRU strategy
* Clear part of caches with LRU strategy.
*
* @zh
* 使用 LRU 策略清空部分缓存
* 使用 LRU 策略清空部分缓存。
*
*/
public abstract clearLRU (): void;
/**
* @en
* Remove cache with origin url
* Removes cache with origin url.
*
* @zh
* 通过原始 url 移除缓存
* 通过原始 url 移除缓存。
*
* @param originUrl @en The origin url to remove from cache. @zh 要从缓存中移除的原始 url。
*/
public abstract removeCache (originUrl: string): void;
}
+128 -37
View File
@@ -24,24 +24,115 @@
import { js } from '../../core';
/**
* @zh 缓存结构的接口定义,可以用于保存数据。
* @en Interface definition of a cache structure that can be used to save data.
*/
export interface ICache<T> {
/**
* @en
* Adds a Key-Value pair to cache.
*
* @zh
* 增加键值对到缓存中。
*
* @param key @en The key. @zh 要增加的键值对中的键。
* @param val @en The value. @zh 要增加的键值对中的值。
* @returns @en The value. @zh 新增的键值对中的值。
*/
add (key: string, val: T): T;
/**
* @en
* Gets the cached content by key.
*
* @zh
* 通过 key 获取对应的 value。
*
* @param key @en The key. @zh 要查询的键。
* @returns @en The corresponding content. @zh 对应键值对中的值。
*/
get (key: string): T | undefined | null;
/**
* @en
* Checks whether or not content exists by key.
*
* @zh
* 通过 Key 判断是否存在对应的内容。
*
* @param key @en The key. @zh 要查询的键。
* @returns @en True indicates that content of the key exists. @zh 返回 True 则表明该值存在。
*/
has (key: string): boolean;
/**
* @en
* Removes the cached content by key.
*
* @zh
* 通过 Key 移除对应的内容。
*
* @param key @en The key. @zh 要移除的键值对中的键。
* @returns @en The removed content. @zh 移出的键值对中的值。
*/
remove (key: string): T | undefined | null;
/**
* @en
* Clear all contents.
*
* @zh
* 清除所有内容。
*/
clear (): void;
/**
*
* @en
* Enumerates all contents and invokes function.
*
* @zh
* 枚举所有内容并执行方法。
*
* @param func @en Function to be invoked. @zh 待执行的方法。
* @param func.val @en The value. @zh 传入的键值对中的值。
* @param func.key @en The corresponding key. @zh 传入的键值对中的键。
*/
forEach (func: (val: T, key: string) => void): void;
/**
* @en
* Enumerates all content to find one element which can fulfill condition.
*
* @zh
* 枚举所有内容,找到一个可以满足条件的元素。
*
* @param predicate @en The condition function. @zh 条件方法。
* @returns @en The first content that meets this condition. @zh 第一个符合该条件的内容。
*/
find (predicate: (val: T, key: string) => boolean): T | null;
/**
* @en
* The count of cached content.
*
* @zh
* 缓存数量。
*/
readonly count: number;
/**
* @en
* Destroy this cache。
*
* @zh
* 销毁这个 cache.
*/
destroy (): void;
}
/**
* @en
* use to cache something
* A data structure used to cache certain content.
*
* @zh
* 用于缓存某些内容
* 用于缓存某些内容的数据结构。
*
*/
export default class Cache<T = any> implements ICache<T> {
@@ -50,12 +141,12 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Create a cache
* Creates a Cache.
*
* @zh
* 创建一个 cache
* 创建一个 Cache。
*
* @param map - An object used to initialize
* @param map @en An object used to initialize. @zh 用于初始化此缓存的对象。
*
*/
constructor (map?: Record<string, T>) {
@@ -70,14 +161,14 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Add Key-Value to cache
* Adds a Key-Value pair to cache.
*
* @zh
* 增加键值对到缓存中
* 增加键值对到缓存中。
*
* @param key - The key
* @param val - The value
* @returns The value
* @param key @en The key. @zh 要增加的键值对中的键。
* @param val @en The value. @zh 要增加的键值对中的值。
* @returns @en The value. @zh 新增的键值对中的值。
*
* @example
* var cache = new Cache();
@@ -93,13 +184,13 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Get the cached content by key
* Gets the cached content by key.
*
* @zh
* 通过 key 获取对应的 value
* 通过 key 获取对应的 value。
*
* @param key - The key
* @returns The corresponding content
* @param key @en The key. @zh 要查询的键。
* @returns @en The corresponding content. @zh 对应键值对中的值。
*
* @example
* let cache = new Cache();
@@ -112,13 +203,13 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Check whether or not content exists by key
* Checks whether or not content exists by key.
*
* @zh
* 通过 Key 判断是否存在对应的内容
* 通过 Key 判断是否存在对应的内容。
*
* @param key - The key
* @returns True indicates that content of the key exists
* @param key @en The key. @zh 要查询的键。
* @returns @en True indicates that content of the key exists. @zh 返回 True 则表明该值存在。
*
* @example
* var cache = new Cache();
@@ -131,13 +222,13 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Remove the cached content by key
* Removes the cached content by key.
*
* @zh
* 通过 Key 移除对应的内容
* 通过 Key 移除对应的内容。
*
* @param key - The key
* @returns The removed content
* @param key @en The key. @zh 要移除的键值对中的键。
* @returns @en The removed content. @zh 移出的键值对中的值。
*
* @example
* var cache = new Cache();
@@ -155,10 +246,10 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Clear all content
* Clear all content.
*
* @zh
* 清除所有内容
* 清除所有内容。
*
* @example
* var cache = new Cache();
@@ -174,14 +265,14 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Enumerate all content and invoke function
* Enumerates all content and invokes function.
*
* @zh
* 枚举所有内容并执行方法
* 枚举所有内容并执行方法。
*
* @param func - Function to be invoked
* @param func.val - The value
* @param func.key - The corresponding key
* @param func @en Function to be invoked. @zh 待执行的方法。
* @param func.val @en The value. @zh 传入的键值对中的值。
* @param func.key @en The corresponding key. @zh 传入的键值对中的键。
*
* @example
* var cache = new Cache();
@@ -196,13 +287,13 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Enumerate all content to find one element which can fulfill condition
* Enumerate all content to find one element which can fulfill condition.
*
* @zh
* 枚举所有内容,找到一个可以满足条件的元素
* 枚举所有内容,找到一个可以满足条件的元素。
*
* @param predicate - The condition
* @returns content
* @param predicate @en The condition function. @zh 条件方法。
* @returns @en The first content that meets this condition. @zh 第一个符合该条件的内容。
*
* @example
* var cache = new Cache();
@@ -220,10 +311,10 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* The count of cached content
* The count of cached content.
*
* @zh
* 缓存数量
* 缓存数量。
*
*/
get count (): number {
@@ -232,10 +323,10 @@ export default class Cache<T = any> implements ICache<T> {
/**
* @en
* Destroy this cache
* Destroy this cache.
*
* @zh
* 销毁这个 cache
* 销毁这个 cache。
*
*/
public destroy (): void {
+75 -5
View File
@@ -26,7 +26,6 @@ import { Asset } from '../assets';
import { js, cclegacy } from '../../core';
import Cache from './cache';
import { decodeUuid, normalize } from './helper';
import { AssetType } from './shared';
export interface IConfigOption {
importBase: string;
@@ -45,26 +44,97 @@ export interface IConfigOption {
extensionMap: Record<string, string[]>;
}
/**
* @en Th asset's meta information. Used to obtain information about the asset.
* @zh 资源的元信息。用于获取资源的相关信息。
*/
export interface IAssetInfo {
/**
* @en The uuid of asset.
* @zh 资源的 uuid.
*/
uuid: string;
/**
* @en Information about the file where the asset is located. A asset can be in multiple merged files.
* @zh 资源所在文件的相关信息。一个资源可在多个合并文件中。
*/
packs?: IPackInfo[];
/**
* @en The redirect bundle of this asset. When multiple bundles with different priorities reference to the same asset,
* the asset will be stored in the bundle with the higher priority first, while the other bundles will store a record
* and the `redirect` property of that record will point to the bundle that actually stores the resource.
* @zh 资源所重定向的 bundle。当多个 bundle 引用同一份资源,且优先级不一样时,资源会优先存储在优先级高的 bundle 中,
* 其他 bundle 则会存储一条记录,并且该记录的 redirect 属性将指向真实存储此资源的 bundle。
*/
redirect?: string;
/**
* @en The version of the asset.
* @zh 资源的版本号。
*/
ver?: string;
/**
* @en The version of the native dependency of the asset.
* @zh 资源的原生依赖的版本号。
*/
nativeVer?: string;
/**
* @en The extension of the asset, or 'json' if it is null.
* This property is used to mark assets with special extensions like 'CCON'.
* @zh 资源的原生依赖的版本号。
*/
extension?: string;
}
export interface IPackInfo extends IAssetInfo {
/**
* @en Information about the merged files.
* @zh 合并文件的信息。
*/
export interface IPackInfo {
/**
* @en The unique id of this merged file.
* @zh 此合并文件的唯一 id.
*/
uuid: string;
/**
* @en The uuid of all the assets contained in this file.
* @zh 此文件中包含的所有资源的 uuid。
*/
packedUuids: string[];
/**
* @en The extension of this merged file on the file system, default is 'json'.
* @zh 此合并文件在文件系统上的扩展名,默认为 'json'.
*/
ext: string;
}
/**
* @en Addressable asset information, you can look up the path of the asset in the project and the type of the asset.
* @zh 可寻址资源的信息,你可以查询到该资源在项目中的路径与资源的类型。
*/
export interface IAddressableInfo extends IAssetInfo {
/**
* @en The relative path of this asset in the project relative to the bundle folder.
* @zh 此资源在项目中相对于 bundle 文件夹的相对路径。
*/
path: string;
ctor: AssetType;
/**
* @en The type of the asset.
* @zh 此资源的类型。
*/
ctor: Constructor<Asset>;
}
/**
* @en Information about the scene asset.
* @zh 场景资源的相关信息。
*/
export interface ISceneInfo extends IAssetInfo {
/**
* @en The path of the scene asset in the project relative to the bundle folder.
* @zh 场景资源在项目中相对 bundle 文件夹的路径。
*/
url: string;
}
@@ -199,7 +269,7 @@ export default class Config {
}
}
public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null {
public getInfoWithPath (path: string, type?: Constructor<Asset> | null): IAddressableInfo | null {
if (!path) {
return null;
}
@@ -220,7 +290,7 @@ export default class Config {
return null;
}
public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] {
public getDirWithPath (path: string, type?: Constructor<Asset> | null, out?: IAddressableInfo[]): IAddressableInfo[] {
path = normalize(path);
if (path[path.length - 1] === '/') {
path = path.slice(0, -1);
+46 -18
View File
@@ -42,10 +42,10 @@ export interface IDependencies {
/**
* @en
* Control asset's dependency list, it is a singleton. All member can be accessed with `assetManager.dependUtil`
* Manages asset's dependency list, it is a singleton. You can access it via [[AssetManager.dependUtil]].
*
* @zh
* 控制资源的依赖列表,这是一个单例, 所有成员能通过 `assetManager.dependUtil` 访问
* 管理资源的依赖列表,这是一个单例, 你能通过 [[AssetManager.dependUtil]] 访问它。
*
*/
export class DependUtil {
@@ -53,23 +53,43 @@ export class DependUtil {
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
*/
public _depends: Cache<IDependencies> = new Cache<IDependencies>();
private static _instance: DependUtil;
/**
* @en Global singleton for [[DependUtil]]. You can access it via [[AssetManager.dependUtil]].
* @zh [[DependUtil]] 的全局单例. 你可以通过 [[AssetManager.dependUtil]] 访问.
*/
static get instance () {
if (!this._instance) {
this._instance = new DependUtil();
}
return this._instance;
}
private constructor () {}
/**
* @engineInternal
*/
public init (): void {
this._depends.clear();
}
/**
* @en
* Get asset's native dependency. For example, Texture's native dependency is image.
* Gets asset's native dependency. For example, ImageAsset's native dependency is image.
* Note: You will need to have loaded this resource to query this information.
*
* @zh
* 获取资源的原生依赖,例如 Texture 的原生依赖是图片
* 获取资源的原生依赖,例如 ImageAsset 的原生依赖是图片。
* 注意:你需要加载过该资源,才能查询此信息。
*
* @param uuid - asset's uuid
* @returns native dependency
* @param uuid @en asset's uuid. @zh 资源的 uuid。
* @returns @en The native dependency information of this asset. @zh 资源的原生依赖的信息。
*
* @example
* var dep = dependUtil.getNativeDep('fcmR3XADNLgJ1ByKhqcC5Z');
* @deprecated Since v3.7, this is an engine internal interface.
* If you want to know the native dependency of the asset, use [[Asset.nativeUrl]] instead.
*/
public getNativeDep (uuid: string): Record<string, any> | null {
const depend = this._depends.get(uuid);
@@ -81,13 +101,15 @@ export class DependUtil {
/**
* @en
* Get asset's direct referencing non-native dependency list. For example, Material's non-native dependencies are Texture.
* Gets asset's direct referencing dependency list. For example, Material's dependencies are Texture, effect asset etc.
* Note: You will need to have loaded this resource to query this information.
*
* @zh
* 获取资源直接引用的非原生依赖列表,例如,材质的非原生依赖是 Texture
* 获取资源直接引用的依赖列表,例如,材质的直接依赖资源是 Texture, Effect 等。
* 注意:你需要加载过该资源,才能查询此信息。
*
* @param uuid - asset's uuid
* @returns direct referencing non-native dependency list
* @param uuid @en asset's uuid. @zh 资源的 uuid。
* @returns @en The direct referencing dependency asset list. @zh 直接引用的依赖资源列表。
*
* @example
* var deps = dependUtil.getDeps('fcmR3XADNLgJ1ByKhqcC5Z');
@@ -102,15 +124,17 @@ export class DependUtil {
/**
* @en
* Get non-native dependency list of the loaded asset, include indirect reference.
* The returned array stores the dependencies with their uuid, after retrieve dependencies,
* Gets dependency list of the loaded asset, include indirect reference.
* Note: You will need to have loaded this resource to query this information.
*
* @zh
* 获取某个已经加载好的资源的所有非原生依赖资源列表,包括间接引用的资源,并保存在数组中返回。
* 返回的数组将仅保存依赖资源的 uuid。
* 获取某个已经加载好的资源的所有依赖资源列表,包括间接引用的资源,并保存在数组中返回。
* 注意:你需要加载过该资源,才能查询此信息。
*
* @param uuid - The asset's uuid
* @returns non-native dependency list
* @param uuid @en asset's uuid. @zh 资源的 uuid。
* @returns
* @en The all dependency list including direct reference and indirect reference.
* @zh 所有依赖列表,包括直接引用的与间接引用的。
*
* @example
* var deps = dependUtil.getDepsRecursively('fcmR3XADNLgJ1ByKhqcC5Z');
@@ -123,13 +147,16 @@ export class DependUtil {
return depends;
}
/**
* @engineInternal
*/
public remove (uuid: string) {
this._depends.remove(uuid);
}
/**
* @en
* Extract dependency list from serialized data or asset and then store in cache.
* Extracts dependency list from serialized data or asset and then store in cache.
*
* @zh
* 从序列化数据或资源中提取出依赖列表,并且存储在缓存中。
@@ -143,6 +170,7 @@ export class DependUtil {
* var dependencies = parse('fcmR3XADNLgJ1ByKhqcC5Z', file);
* });
*
* @engineInternal
*/
public parse (uuid: string, json: any): IDependencies {
let out: IDependencies | null = null;
@@ -221,4 +249,4 @@ export class DependUtil {
}
}
export default new DependUtil();
export default DependUtil.instance;
+6 -5
View File
@@ -33,9 +33,10 @@ import downloader from './downloader';
import { getUuidFromURL, transform } from './helper';
import parser from './parser';
import releaseManager from './release-manager';
import { assets, BuiltinBundleName, bundles, ProgressCallback, CompleteCallback } from './shared';
import { assets, BuiltinBundleName, bundles } from './shared';
import { parseLoadResArgs, setDefaultProgressCallback } from './utilities';
import factory from './factory';
import RequestItem from './request-item';
const ImageFmts = ['.png', '.jpg', '.bmp', '.jpeg', '.gif', '.ico', '.tiff', '.webp', '.image', '.pvr', '.pkm', '.astc'];
const AudioFmts = ['.mp3', '.ogg', '.wav', '.m4a'];
@@ -92,7 +93,7 @@ export class CCLoader {
*
* @deprecated since v3.0, loader.onProgress is deprecated, please transfer onProgress to API as a parameter
*/
public set onProgress (val: ProgressCallback) {
public set onProgress (val: ((finished: number, total: number, item: RequestItem) => void)) {
setDefaultProgressCallback(val);
}
@@ -581,7 +582,7 @@ export class CCLoader {
* @param extMap Handlers for corresponding type in a map
* @deprecated since v3.0 loader.addDownloadHandlers is deprecated, please use assetManager.downloader.register instead
*/
public addDownloadHandlers (extMap: Record<string, (item: { url: string }, cb: CompleteCallback) => void>) {
public addDownloadHandlers (extMap: Record<string, (item: { url: string }, cb: ((err: Error | null, data?: any | null) => void)) => void>) {
const handler = Object.create(null);
for (const type in extMap) {
const func = extMap[type];
@@ -605,7 +606,7 @@ export class CCLoader {
* @param extMap Handlers for corresponding type in a map
* @deprecated since v3.0 loader.addLoadHandlers is deprecated, please use assetManager.parser.register instead
*/
public addLoadHandlers (extMap: Record<string, ({ content: any }, cb: CompleteCallback) => void>) {
public addLoadHandlers (extMap: Record<string, ({ content: any }, cb: ((err: Error | null, data?: any | null) => void)) => void>) {
const handler = Object.create(null);
for (const type in extMap) {
const func = extMap[type];
@@ -879,7 +880,7 @@ export const AssetLibrary = {
* @param {Asset} options.existingAsset - 加载现有资源,此参数仅在编辑器中可用。
* @deprecated since v3.0 AssetLibrary.loadAsset is deprecated, please use assetManager.loadAny instead
*/
loadAsset (uuid: string, callback: CompleteCallback, options?) {
loadAsset (uuid: string, callback: ((err: Error | null, data?: any | null) => void), options?) {
assetManager.loadAny(uuid, callback);
},
};
@@ -23,18 +23,19 @@
THE SOFTWARE.
*/
import { XIAOMI } from 'internal:constants';
import { getError } from '../../core';
import { ccwindow } from '../../core/global-exports';
import { CompleteCallback, IDownloadParseOptions } from './shared';
export default function downloadDomImage (
url: string,
options: IDownloadParseOptions,
onComplete: CompleteCallback<HTMLImageElement>,
options: Record<string, any>,
onComplete: ((err: Error | null, data?: HTMLImageElement | null) => void),
): HTMLImageElement {
const img = new ccwindow.Image();
if (ccwindow.location.protocol !== 'file:') {
// NOTE: on xiaomi platform, we need to force setting img.crossOrigin as 'anonymous'
if (ccwindow.location.protocol !== 'file:' || XIAOMI) {
img.crossOrigin = 'anonymous';
}
+2 -4
View File
@@ -22,15 +22,13 @@
THE SOFTWARE.
*/
import { CompleteCallback, IXHROptions } from './shared';
type FileProgressCallback = (loaded: number, total: number) => void;
export default function downloadFile (
url: string,
options: IXHROptions,
options: Record<string, any>,
onProgress: FileProgressCallback | null | undefined,
onComplete: CompleteCallback,
onComplete: ((err: Error | null, data?: any | null) => void),
): XMLHttpRequest {
const xhr = new XMLHttpRequest();
const errInfo = `download failed: ${url}, status: `;
+2 -3
View File
@@ -24,7 +24,6 @@
import { getError } from '../../core';
import { ccwindow } from '../../core/global-exports';
import { CompleteCallback, IBundleOptions } from './shared';
const ccdocument = ccwindow.document;
@@ -32,8 +31,8 @@ const downloaded = {};
export default function downloadScript (
url: string,
options: IBundleOptions,
onComplete: CompleteCallback,
options: Record<string, any>,
onComplete: ((err: Error | null, data?: any | null) => void),
): HTMLScriptElement | null {
// no need to load script again
if (downloaded[url]) {
+116 -76
View File
@@ -28,46 +28,46 @@ import Cache from './cache';
import downloadDomImage from './download-dom-image';
import downloadFile from './download-file';
import downloadScript from './download-script';
import { CompleteCallback, CompleteCallbackNoData, IBundleOptions, IDownloadParseOptions, files } from './shared';
import { files } from './shared';
import { retry, RetryFunction, urlAppendTimestamp } from './utilities';
import { IConfigOption } from './config';
import { CCON, parseCCONJson, decodeCCONBinary } from '../../serialization/ccon';
export type DownloadHandler = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => void;
export type DownloadHandler = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void;
interface IDownloadRequest {
id: string;
priority: number;
url: string;
options: IDownloadParseOptions;
done: CompleteCallback;
options: Record<string, any>;
done: ((err: Error | null, data?: any | null) => void);
handler: DownloadHandler;
}
const REGEX = /^(?:\w+:\/\/|\.+\/).+/;
const downloadImage = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => {
const downloadImage = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => {
// if createImageBitmap is valid, we can transform blob to ImageBitmap. Otherwise, just use HTMLImageElement to load
const func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && cclegacy.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage;
func(url, options, onComplete);
};
const downloadBlob = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => {
const downloadBlob = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => {
options.xhrResponseType = 'blob';
downloadFile(url, options, options.onFileProgress, onComplete);
};
const downloadJson = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback<Record<string, any>>) => {
const downloadJson = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: Record<string, any> | null) => void)) => {
options.xhrResponseType = 'json';
downloadFile(url, options, options.onFileProgress, onComplete);
};
const downloadArrayBuffer = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => {
const downloadArrayBuffer = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => {
options.xhrResponseType = 'arraybuffer';
downloadFile(url, options, options.onFileProgress, onComplete);
};
const downloadCCON = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback<CCON>) => {
const downloadCCON = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: CCON | null) => void)) => {
downloadJson(url, options, (err, json) => {
if (err) {
onComplete(err);
@@ -92,7 +92,7 @@ const downloadCCON = (url: string, options: IDownloadParseOptions, onComplete: C
});
};
const downloadCCONB = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback<CCON>) => {
const downloadCCONB = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: CCON | null) => void)) => {
downloadArrayBuffer(url, options, (err, arrayBuffer: ArrayBuffer) => {
if (err) {
onComplete(err);
@@ -107,12 +107,12 @@ const downloadCCONB = (url: string, options: IDownloadParseOptions, onComplete:
});
};
const downloadText = (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) => {
const downloadText = (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => {
options.xhrResponseType = 'text';
downloadFile(url, options, options.onFileProgress, onComplete);
};
const downloadBundle = (nameOrUrl: string, options: IBundleOptions, onComplete: CompleteCallback) => {
const downloadBundle = (nameOrUrl: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => {
const bundleName = path.basename(nameOrUrl);
let url = nameOrUrl;
if (!REGEX.test(url)) {
@@ -147,49 +147,50 @@ const downloadBundle = (nameOrUrl: string, options: IBundleOptions, onComplete:
/**
* @en
* Control all download process, it is a singleton.
* All member can be accessed with `assetManager.downloader`, it can download several types of files:
* 1. Text
* 2. Image
* 3. Audio
* 4. Assets
* 5. Scripts
* Manages all download process, it is a singleton.
* You can access it via [[AssetManager.downloader]], It can download various types of files.
*
* @zh
* 管理所有下载过程,downloader 是个单例,所有成员能通过 `assetManager.downloader` 访问,它能下载以下几种类型的文件:
* 1. 文本
* 2. 图片
* 3. 音频
* 4. 资源
* 5. 脚本
* 管理所有下载过程,downloader 是个单例,你能通过 [[AssetManager.downloader]] 访问它,它能下载各种类型的文件。
*
*/
export class Downloader {
/**
* @en Global singleton for [[Downloader]]. You can access it via [[AssetManager.downloader]].
* @zh [[Downloader]] 的全局单例. 你可以通过 [[AssetManager.downloader]] 访问.
*/
public static get instance () {
if (!Downloader._instance) {
Downloader._instance = new Downloader();
}
return Downloader._instance;
}
/**
* @en
* The maximum number of concurrent when downloading
* The maximum number of concurrent when downloading.
*
* @zh
* 下载时的最大并发数
* 下载时的最大并发数。
*/
public maxConcurrency = 6;
/**
* @en
* The maximum number of request can be launched per frame when downloading
* The maximum number of request can be launched per frame when downloading.
*
* @zh
* 下载时每帧可以启动的最大请求数
* 下载时每帧可以启动的最大请求数。
*
*/
public maxRequestsPerFrame = 6;
/**
* @en
* The address of remote server
* The address of remote server.
*
* @zh
* 远程服务器地址
* 远程服务器地址。
*
*/
public get remoteServerAddress () {
@@ -198,40 +199,67 @@ export class Downloader {
/**
* @en
* The max number of retries when fail
* The max number of retries when fail.
*
* @zh
* 失败重试次数
* 失败重试次数。
*
* @property maxRetryCount
* @type {Number}
*/
public maxRetryCount = BUILD ? 3 : 0;
/**
* Whether to automatically add a timestamp after the url.
* This function is mainly used to prevent the browser from using cache in editor mode.
* You don't need to change it at runtime.
* @internal
*/
public appendTimeStamp = !!EDITOR;
/**
* @engineInternal
*/
public limited = !EDITOR;
/**
* @en
* Wait for while before another retry, unit: ms
* Wait for while before another retry, unit: ms.
*
* @zh
* 重试的间隔时间
* 重试的间隔时间,单位为毫秒。
*
*/
public retryInterval = 2000;
/**
* Version information of all bundles.
* @engineInternal
*/
public bundleVers: Record<string, string> | null = null;
public remoteBundles: string[] = [];
/**
* Remote bundle list.
* @engineInternal
*/
public remoteBundles: ReadonlyArray<string> = [];
/**
* @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using HTMLImageElement.
*/
public downloadDomImage = downloadDomImage;
/**
* @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using HTMLAudioElement.
*/
public downloadDomAudio: DownloadHandler | null = null;
/**
* @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using XMLHttpRequest.
*/
public downloadFile = downloadFile;
/**
* @deprecated Since v3.7, this is an engine internal interface. You can easily implement the functionality of this API using XMLHttpRequest.
*/
public downloadScript = downloadScript;
// default handler map
@@ -282,7 +310,7 @@ export class Downloader {
default: downloadText,
};
private _downloading = new Cache<CompleteCallback[]>();
private _downloading = new Cache<((err: Error | null, data?: any | null) => void)[]>();
private _queue: IDownloadRequest[] = [];
private _queueDirty = false;
// the number of loading thread
@@ -295,7 +323,11 @@ export class Downloader {
private _checkNextPeriod = false;
private _remoteServerAddress = '';
private _maxInterval = 1 / 30;
private static _instance: Downloader;
/**
* @engineInternal
*/
public init (remoteServerAddress = '', bundleVers: Record<string, string> = {}, remoteBundles: string[] = []) {
this._downloading.clear();
this._queue.length = 0;
@@ -306,16 +338,21 @@ export class Downloader {
/**
* @en
* Register custom handler if you want to change default behavior or extend downloader to download other format file
* Register custom handler if you want to change default behavior or extend downloader to download other format file.
*
* @zh
* 当你想修改默认行为或者拓展 downloader 来下载其他格式文件时可以注册自定义的 handler
* 当你想修改默认行为或者拓展 downloader 来下载其他格式文件时可以注册自定义的 handler。
*
* @param type - Extension likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler}
* @param handler - handler
* @param handler.url - url
* @param handler.options - some optional parameters will be transferred to handler.
* @param handler.onComplete - callback when finishing downloading
* @param type
* @en Extension name likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler}.
* @zh 扩展名,或者形如 {'.jpg': jpgHandler, '.png': pngHandler} 的映射表。
* @param handler @en Customized handling for this extension. @zh 针对此扩展名的自定义的处理方法。
* @param handler.url @en The url to be downloaded. @zh 待下载的 url.
* @param handler.options @en Some optional parameters will be transferred to handler. @zh 传递到处理方法的可选参数。
* @param handler.onComplete
* @en Callback when finishing downloading. You need to call this method manually and pass in the execution result after the custom handler
* is executed.
* @zh 完成下载后的回调。你需要在自定义处理方法执行完后手动调用此方法,并将执行结果传入。
*
* @example
* downloader.register('.tga', (url, options, onComplete) => onComplete(null, null));
@@ -323,9 +360,12 @@ export class Downloader {
* '.ext': (url, options, onComplete) => onComplete(null, null)});
*
*/
public register (type: string, handler: DownloadHandler): void;
public register (map: Record<string, DownloadHandler>): void;
public register (type: string | Record<string, DownloadHandler>, handler?: DownloadHandler) {
public register (type: string, handler: (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void): void;
public register (map: Record<string, (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void>): void;
public register (
type: string | Record<string, (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void>,
handler?: (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void,
) {
if (typeof type === 'object') {
js.mixin(this._downloaders, type);
} else {
@@ -335,29 +375,29 @@ export class Downloader {
/**
* @en
* Use corresponding handler to download file under limitation
* Use corresponding handler to download file under limitation.
*
* @zh
* 在限制下使用对应的 handler 来下载文件
* 在限制下使用对应的 handler 来下载文件。
*
* @param id - The unique id of this download
* @param url - The url should be downloaded
* @param type - The type indicates that which handler should be used to download, such as '.jpg'
* @param options - some optional parameters will be transferred to the corresponding handler.
* @param options.onFileProgress - progressive callback will be transferred to handler.
* @param options.maxRetryCount - How many times should retry when download failed
* @param options.maxConcurrency - The maximum number of concurrent when downloading
* @param options.maxRequestsPerFrame - The maximum number of request can be launched per frame when downloading
* @param options.priority - The priority of this url, default is 0, the greater number is higher priority.
* @param onComplete - callback when finishing downloading
* @param onComplete.err - The occurred error, null indicates success
* @param onComplete.content - The downloaded file
* @param id @en The unique id of this download. @zh 本次下载的唯一 id.
* @param url @en The url should be downloaded. @zh 待下载的 url。
* @param type @en The type indicates that which handler should be used to download, such as '.jpg'. @zh 要使用的处理方法的类型,例如 '.jpg'。
* @param options @en Some optional parameters will be transferred to the corresponding handler. @zh 传递到处理方法的一些可选参数。
* @param options.onFileProgress @en Progressive callback will be transferred to handler. @zh 传递到处理方法的进度回调。
* @param options.maxRetryCount @en How many times should retry when download failed. @zh 下载失败后的重试数量。
* @param options.maxConcurrency @en The maximum number of concurrent when downloading. @zh 下载的最大并行数。
* @param options.maxRequestsPerFrame @en The maximum number of request can be launched per frame when downloading. @zh 每帧能发起的最大请求数量,在下载时。
* @param options.priority @en The priority of this url, default is 0, the greater number is higher priority. @zh 下载的优先级,值越大优先级越高。
* @param onComplete @en Callback when finishing downloading. @zh 完成下载后的回调。
* @param onComplete.err @en The occurred error, null indicates success. @zh 下载过程中出现的错误,如果为 null 则表明下载成功。
* @param onComplete.content @en The downloaded file. @zh 下载下来的文件内容。
*
* @example
* download('http://example.com/test.tga', '.tga', { onFileProgress: (loaded, total) => console.log(loaded/total) },
* onComplete: (err) => console.log(err));
*/
public download (id: string, url: string, type: string, options: IDownloadParseOptions, onComplete: CompleteCallback): void {
public download (id: string, url: string, type: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)): void {
// if it is downloaded, don't download again
const file = files.get(id);
if (file) {
@@ -397,7 +437,7 @@ export class Downloader {
// refresh
this._updateTime();
const done: CompleteCallback = (err, data) => {
const done: ((err: Error | null, data?: any | null) => void) = (err, data) => {
// when finish downloading, update _totalNum
this._totalNum--;
this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
@@ -420,7 +460,7 @@ export class Downloader {
// when retry finished, invoke callbacks
const finale = (err, result) => {
if (!err) { files.add(id, result); }
const callbacks = this._downloading.remove(id) as CompleteCallback[];
const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any | null) => void)[];
for (let i = 0, l = callbacks.length; i < l; i++) {
callbacks[i](err, result);
}
@@ -431,17 +471,19 @@ export class Downloader {
/**
* @en Load sub package with name.
* @zh 通过子包名加载子包代码。
* @param name - Sub package name
* @param completeCallback - Callback invoked when sub package loaded
* @param {Error} completeCallback.error - error information
* @zh 通过子包名加载子包。
* @param name @en Sub package name. @zh 子包名称。
* @param completeCallback @en Callback invoked when sub package loaded. @zh 子包加载完成后的回调。
* @param completeCallback.error @en Error information. Will be null if loaded successfully. @zh 错误信息。如果加载成功则为 null。
*
* @deprecated loader.downloader.loadSubpackage is deprecated, please use AssetManager.loadBundle instead
* @deprecated loader.downloader.loadSubpackage is deprecated, please use AssetManager.loadBundle instead.
*/
public loadSubpackage (name: string, completeCallback?: CompleteCallbackNoData) {
public loadSubpackage (name: string, completeCallback?: ((err?: Error | null) => void)) {
cclegacy.assetManager.loadBundle(name, null, completeCallback);
}
private constructor () {}
private _updateTime () {
const now = performance.now();
// use deltaTime as interval
@@ -481,7 +523,5 @@ export class Downloader {
}
}
}
const downloader = new Downloader();
export default downloader;
const downloader = Downloader.instance;
export default Downloader.instance;
@@ -24,13 +24,13 @@
import { EDITOR, NATIVE, PREVIEW, TEST } from 'internal:constants';
import { assert, Settings, settings } from '../../core';
import { fetchPipeline, pipeline } from './shared';
import Task, { TaskCompleteCallback } from './task';
import Task from './task';
declare const Editor: any;
if ((EDITOR || PREVIEW) && !TEST) {
const cache: {[uuid: string]: string | null} = {};
const resolveMap: { [uuid: string]: Function[] } = {};
const replaceExtension = (task: Task, done: TaskCompleteCallback) => {
const replaceExtension = (task: Task, done) => {
task.output = task.input;
(async () => {
for (let i = 0; i < task.input.length; i++) {
+10 -11
View File
@@ -32,15 +32,14 @@ import Bundle, { resources } from './bundle';
import Cache from './cache';
import { IConfigOption } from './config';
import {
assets, BuiltinBundleName, bundles, CompleteCallback, IRemoteOptions,
IDownloadParseOptions,
assets, BuiltinBundleName, bundles,
} from './shared';
import { cache } from './utilities';
import { js } from '../../core';
export type CreateHandler = (id: string, data: any, options: IDownloadParseOptions, onComplete: CompleteCallback<Asset|Bundle>) => void;
export type CreateHandler = (id: string, data: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: Asset | Bundle | null) => void)) => void;
function createImageAsset (id: string, data: HTMLImageElement, options: IDownloadParseOptions, onComplete: CompleteCallback<ImageAsset>) {
function createImageAsset (id: string, data: HTMLImageElement, options: Record<string, any>, onComplete: ((err: Error | null, data?: ImageAsset | null) => void)) {
let out: ImageAsset | null = null;
let err: Error | null = null;
try {
@@ -53,33 +52,33 @@ function createImageAsset (id: string, data: HTMLImageElement, options: IDownloa
onComplete(err, out);
}
function createJsonAsset (id: string, data: Record<string, any>, options: IDownloadParseOptions, onComplete: CompleteCallback<JsonAsset>) {
function createJsonAsset (id: string, data: Record<string, any>, options: Record<string, any>, onComplete: ((err: Error | null, data?: JsonAsset | null) => void)) {
const out = new JsonAsset();
out.json = data;
onComplete(null, out);
}
function createTextAsset (id: string, data: string, options: IDownloadParseOptions, onComplete: CompleteCallback<TextAsset>) {
function createTextAsset (id: string, data: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: TextAsset | null) => void)) {
const out = new TextAsset();
out.text = data;
onComplete(null, out);
}
function createBufferAsset (id: string, data: ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback<BufferAsset>) {
function createBufferAsset (id: string, data: ArrayBufferView, options: Record<string, any>, onComplete: ((err: Error | null, data?: BufferAsset | null) => void)) {
const out = new BufferAsset();
out._nativeUrl = id;
out._nativeAsset = data;
onComplete(null, out);
}
function createAsset (id: string, data: any, options: IDownloadParseOptions, onComplete: CompleteCallback<Asset>) {
function createAsset (id: string, data: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: Asset | null) => void)) {
const out = new Asset();
out._nativeUrl = id;
out._nativeAsset = data;
onComplete(null, out);
}
function createBundle (id: string, data: IConfigOption, options: IDownloadParseOptions, onComplete: CompleteCallback<Bundle>) {
function createBundle (id: string, data: IConfigOption, options: Record<string, any>, onComplete: ((err: Error | null, data?: Bundle | null) => void)) {
let bundle = bundles.get(data.name);
if (!bundle) {
bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle();
@@ -97,7 +96,7 @@ function createBundle (id: string, data: IConfigOption, options: IDownloadParseO
}
export class Factory {
private _creating = new Cache<CompleteCallback[]>();
private _creating = new Cache<((err: Error | null, data?: any | null) => void)[]>();
private _producers: Record<string, CreateHandler> = {
// Images
@@ -147,7 +146,7 @@ export class Factory {
}
}
public create (id: string, data: any, type: string, options: IRemoteOptions, onComplete: CompleteCallback<Asset | Bundle>): void {
public create (id: string, data: any, type: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: Asset | Bundle | null) => void)): void {
const handler = this._producers[type] || this._producers.default;
const asset = assets.get(id);
if (!options.reloadAsset && asset) {
+5 -5
View File
@@ -26,11 +26,11 @@ import { Asset } from '../assets';
import { error, cclegacy } from '../../core';
import packManager from './pack-manager';
import RequestItem from './request-item';
import { assets, CompleteCallbackNoData, fetchPipeline } from './shared';
import { assets, fetchPipeline } from './shared';
import Task from './task';
import { clear, forEach, getDepends } from './utilities';
export default function fetch (task: Task, done: CompleteCallbackNoData) {
export default function fetch (task: Task, done: ((err?: Error | null) => void)) {
let firstTask = false;
if (!task.progress) {
task.progress = { finish: 0, total: task.input.length, canInvoke: true };
@@ -58,7 +58,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) {
packManager.load(item, task.options, (err, data) => {
if (err) {
if (!task.isFinish) {
if (!task.isFinished) {
if (!cclegacy.assetManager.force || firstTask) {
error(err.message, err.stack);
progress.canInvoke = false;
@@ -70,7 +70,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) {
}
}
}
} else if (!task.isFinish) {
} else if (!task.isFinished) {
item.file = data;
task.output.push(item);
if (!item.isNative) {
@@ -85,7 +85,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) {
cb();
});
}, () => {
if (task.isFinish) {
if (task.isFinished) {
clear(task, true);
task.dispatch('error');
return;
+21 -22
View File
@@ -23,7 +23,7 @@
*/
import { cclegacy, error } from '../../core';
import RequestItem from './request-item';
import { bundles, Request, IOptions, transformPipeline } from './shared';
import { bundles, transformPipeline } from './shared';
import Task from './task';
const _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/;
@@ -32,13 +32,13 @@ export { default as decodeUuid } from '../../core/utils/decode-uuid';
/**
* @en
* Extract uuid from url
* Extracts uuid from url.
*
* @zh
* 从 url 中提取 uuid
* 从 url 中提取 uuid。
*
* @param url - url
* @returns the uuid parsed from url
* @param url @en The url to be converted. @zh 待转换的 url。
* @returns @en The uuid extracted from url. @zh url 转换为的 uuid。
*
* @example
* var url = 'res/import/fc/fc991dd7-0033-4b80-9d41-c8a86a702e59.json';
@@ -54,16 +54,16 @@ export function getUuidFromURL (url: string): string {
/**
* @en
* Transform uuid to url
* Transforms uuid to url.
*
* @zh
* 转换 uuid 为 url
* 转换 uuid 为 url。
*
* @param uuid - The uuid of asset
* @param options - Some optional parameters
* @param options.isNative - Indicates whether the path you want is a native resource path
* @param options.nativeExt - Extension of the native resource path, it is required when isNative is true
* @returns url
* @param uuid @en The uuid of asset. @zh 资源的 uuid。
* @param options @en Some optional parameters. @zh 一些可选参数。
* @param options.isNative @en Indicates whether the path you want is a native resource path. @zh 需要转换的路径是否是原生资源路径。
* @param options.nativeExt @en Extension of the native resource path, it is required when isNative is true. @zh 原生资源路径的扩展名,如果 `isNative` 为 true,则需要。
* @returns @en The url converted from uuid. @zh 从 uuid 转换而来的 url.
*
* @example
* // json path, 'assets/main/import/fc/fc991dd7-0033-4b80-9d41-c8a86a702e59.json';
@@ -90,14 +90,13 @@ export function getUrlWithUuid (uuid: string, options?: { [k: string]: any, isNa
/**
* @en
* Check if the type of asset is scene
* Checks if the type of asset is scene.
*
* @zh
* 检查资源类型是否是场景
* 检查资源类型是否是场景。
*
* @method isScene
* @param {*} asset - asset
* @returns {boolean} - whether or not type is SceneAsset
* @param asset @en The asset to be checked. @zh 待检查的资源。
* @returns @en Whether or not the asset is a SceneAsset. @zh 此资源是否是场景资源。
*
*/
export function isScene (asset) {
@@ -106,13 +105,13 @@ export function isScene (asset) {
/**
* @en
* Normalize url, strip './' and '/'
* Normalizes url, strip './' and '/'.
*
* @zh
* 标准化 url ,去除 './' 和 '/'
* 标准化 url ,去除 './' 和 '/'。
*
* @param url - url
* @returns - The normalized url
* @param url @en The url to be normalized. @zh 待标准化的 url。
* @returns @en The normalized url. @zh 标准化后的 url。
*/
export function normalize (url: string): string {
if (url) {
@@ -127,7 +126,7 @@ export function normalize (url: string): string {
return url;
}
export function transform (input: Request, options?: IOptions | null): string | string[] {
export function transform (input: string | string[] | Record<string, any> | Array<Record<string, any>>, options?: Record<string, any> | null): string | string[] {
const subTask = Task.create({ input, options });
const urls: string[] = [];
try {
+6 -6
View File
@@ -28,7 +28,7 @@ import packManager from './pack-manager';
import parser from './parser';
import { Pipeline } from './pipeline';
import RequestItem from './request-item';
import { CompleteCallbackNoData, assets, files, parsed, pipeline } from './shared';
import { assets, files, parsed, pipeline } from './shared';
import Task from './task';
import { cache, checkCircleReference, clear, forEach, gatherAsset, getDepends, setProperties } from './utilities';
import { nativeDependMap, onLoadedInvokedMap } from './depend-maps';
@@ -43,10 +43,10 @@ interface ILoadingRequest {
content: Asset;
finish: boolean;
err?: Error | null;
callbacks: Array<{ done: CompleteCallbackNoData; item: RequestItem }>;
callbacks: Array<{ done: ((err?: Error | null) => void); item: RequestItem }>;
}
export default function load (task: Task, done: CompleteCallbackNoData) {
export default function load (task: Task, done: ((err?: Error | null) => void)) {
let firstTask = false;
if (!task.progress) {
task.progress = { finish: 0, total: task.input.length, canInvoke: true };
@@ -66,7 +66,7 @@ export default function load (task: Task, done: CompleteCallbackNoData) {
options,
progress,
onComplete: (err, result) => {
if (err && !task.isFinish) {
if (err && !task.isFinished) {
if (!cclegacy.assetManager.force || firstTask) {
if (BUILD) {
error(err.message, err.stack);
@@ -87,7 +87,7 @@ export default function load (task: Task, done: CompleteCallbackNoData) {
}, () => {
options!.__exclude__ = null;
if (task.isFinish) {
if (task.isFinished) {
clear(task, true);
task.dispatch('error');
return;
@@ -173,7 +173,7 @@ const loadOneAssetPipeline = new Pipeline('loadOneAsset', [
},
]);
function loadDepends (task: Task, asset: Asset, done: CompleteCallbackNoData) {
function loadDepends (task: Task, asset: Asset, done: ((err?: Error | null) => void)) {
const { input: item, progress } = task;
const { uuid, id, options, config } = item as RequestItem;
const { cacheAsset } = options;
+6 -6
View File
@@ -30,12 +30,12 @@ import Cache from './cache';
import downloader from './downloader';
import { transform } from './helper';
import RequestItem from './request-item';
import { CompleteCallback, files, IDownloadParseOptions } from './shared';
import { files } from './shared';
export type Unpacker = (packUuid: string[], data: any, options: IDownloadParseOptions, onComplete: CompleteCallback) => void;
export type Unpacker = (packUuid: string[], data: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void;
interface IUnpackRequest {
onComplete: CompleteCallback;
onComplete: ((err: Error | null, data?: any | null) => void);
id: string;
}
@@ -73,7 +73,7 @@ export class PackManager {
* });
*
*/
public unpackJson (pack: string[], json: any, options: IDownloadParseOptions, onComplete: CompleteCallback<Record<string, any>>): void {
public unpackJson (pack: string[], json: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: Record<string, any> | null) => void)): void {
let out = js.createMap(true);
let err: Error | null = null;
@@ -170,7 +170,7 @@ export class PackManager {
* });
*
*/
public unpack (pack: string[], data: any, type: string, options: IDownloadParseOptions, onComplete: CompleteCallback): void {
public unpack (pack: string[], data: any, type: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)): void {
if (!data) {
onComplete(new Error('package data is wrong!'));
return;
@@ -200,7 +200,7 @@ export class PackManager {
* packManager.load(requestItem, null, (err, data) => console.log(err));
*
*/
public load (item: RequestItem, options: IDownloadParseOptions | null, onComplete: CompleteCallback): void {
public load (item: RequestItem, options: Record<string, any> | null, onComplete: ((err: Error | null, data?: any | null) => void)): void {
// if not in any package, download as uausl
if (item.isNative || !item.info || !item.info.packs) {
downloader.download(item.id, item.url, item.ext, item.options, onComplete);
+68 -32
View File
@@ -28,22 +28,22 @@ import Cache from './cache';
import deserialize from './deserialize';
import { isScene } from './helper';
import plistParser from './plist-parser';
import { CompleteCallback, IDownloadParseOptions, files, parsed } from './shared';
import { files, parsed } from './shared';
import { CCON } from '../../serialization/ccon';
import { Asset } from '../assets';
export type ParseHandler = (file: any, options: IDownloadParseOptions, onComplete: CompleteCallback) => void;
export type ParseHandler = (file: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void;
/**
* @en
* Parse the downloaded file, it's a singleton, all member can be accessed with `assetManager.parser`
* Parse the downloaded file, it's a singleton, you can access it via [[AssetManager.parser]].
*
* @zh
* 解析已下载的文件,parser 是一个单例, 所有成员能通过 `assetManaager.parser` 访问
* 解析已下载的文件,parser 是一个单例, 你能通过 [[assetManager.parser]] 访问它。
*
*/
export class Parser {
private _parsing = new Cache<CompleteCallback[]>();
private _parsing = new Cache<((err: Error | null, data?: any | null) => void)[]>();
private _parsers: Record<string, ParseHandler> = {
'.png': this.parseImage,
@@ -67,7 +67,20 @@ export class Parser {
'.cconb': this.parseImport,
};
public parseImage (file: HTMLImageElement | Blob, options: IDownloadParseOptions, onComplete: CompleteCallback<HTMLImageElement|ImageBitmap>) {
private static _instance: Parser;
public static get instance () {
if (!this._instance) {
this._instance = new Parser();
}
return this._instance;
}
private constructor () {}
/**
* @engineInternal
*/
public parseImage (file: HTMLImageElement | Blob, options: Record<string, any>, onComplete: ((err: Error | null, data?: HTMLImageElement | ImageBitmap | null) => void)) {
if (file instanceof HTMLImageElement) {
onComplete(null, file);
return;
@@ -79,7 +92,10 @@ export class Parser {
});
}
public parsePVRTex (file: ArrayBuffer | ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback<IMemoryImageSource>) {
/**
* @engineInternal
*/
public parsePVRTex (file: ArrayBuffer | ArrayBufferView, options: Record<string, any>, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) {
let err: Error | null = null;
let out: IMemoryImageSource | null = null;
try {
@@ -91,7 +107,10 @@ export class Parser {
onComplete(err, out);
}
public parsePKMTex (file: ArrayBuffer | ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback<IMemoryImageSource>) {
/**
* @engineInternal
*/
public parsePKMTex (file: ArrayBuffer | ArrayBufferView, options: Record<string, any>, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) {
let err: Error | null = null;
let out: IMemoryImageSource | null = null;
try {
@@ -103,7 +122,10 @@ export class Parser {
onComplete(err, out);
}
public parseASTCTex (file: ArrayBuffer | ArrayBufferView, options: IDownloadParseOptions, onComplete: CompleteCallback<IMemoryImageSource>) {
/**
* @engineInternal
*/
public parseASTCTex (file: ArrayBuffer | ArrayBufferView, options: Record<string, any>, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) {
let err: Error | null = null;
let out: IMemoryImageSource | null = null;
try {
@@ -115,14 +137,20 @@ export class Parser {
onComplete(err, out);
}
public parsePlist (file: string, options: IDownloadParseOptions, onComplete: CompleteCallback) {
/**
* @engineInternal
*/
public parsePlist (file: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) {
let err: Error | null = null;
const result = plistParser.parse(file);
if (!result) { err = new Error('parse failed'); }
onComplete(err, result);
}
public parseImport (file: Record<string, any> | CCON, options: IDownloadParseOptions, onComplete: CompleteCallback<Asset>) {
/**
* @engineInternal
*/
public parseImport (file: Record<string, any> | CCON, options: Record<string, any>, onComplete: ((err: Error | null, data?: Asset | null) => void)) {
if (!file) {
onComplete(new Error(`The json file of asset ${options.__uuid__ as string} is empty or missing`));
return;
@@ -137,22 +165,27 @@ export class Parser {
onComplete(err, result);
}
/**
* @engineInternal
*/
public init () {
this._parsing.clear();
}
/**
* @en
* Register custom handler if you want to change default behavior or extend parser to parse other format file
* Register custom handler if you want to change default behavior or extend parser to parse other format file.
*
* @zh
* 当你想修改默认行为或者拓展 parser 来解析其他格式文件时可以注册自定义的handler
* 当你想修改默认行为或者拓展 parser 来解析其他格式文件时可以注册自定义的 handler。
*
* @param type - Extension likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler}
* @param handler - The corresponding handler
* @param handler.file - File
* @param handler.options - Some optional paramter
* @param handler.onComplete - callback when finishing parsing
* @param type
* @en Extension name likes '.jpg' or map likes {'.jpg': jpgHandler, '.png': pngHandler}.
* @zh 形如 '.jpg' 的扩展名或形如 {'.jpg': jpgHandler, '.png': pngHandler} 的映射表。
* @param handler @en The corresponding handler. @zh 对应扩展名的处理方法。
* @param handler.file @en The file to be parsed. @zh 待解析的文件。
* @param handler.options @en Some optional parameters. @zh 一些可选的参数。
* @param handler.onComplete @en The callback invoked when parsing finished. @zh 完成解析的回调。
*
* @example
* parser.register('.tga', (file, options, onComplete) => onComplete(null, null));
@@ -160,9 +193,12 @@ export class Parser {
* '.ext': (file, options, onComplete) => onComplete(null, null)});
*
*/
public register (type: string, handler: ParseHandler): void;
public register (map: Record<string, ParseHandler>): void;
public register (type: string | Record<string, ParseHandler>, handler?: ParseHandler) {
public register (type: string, handler: (file: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void): void;
public register (map: Record<string, (file: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void>): void;
public register (
type: string | Record<string, (file: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void>,
handler?: (file: any, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) => void,
) {
if (typeof type === 'object') {
js.mixin(this._parsers, type);
} else {
@@ -172,18 +208,18 @@ export class Parser {
/**
* @en
* Use corresponding handler to parse file
* Use corresponding handler to parse file.
*
* @zh
* 使用对应的handler来解析文件
* 使用对应的 handler 来解析文件。
*
* @param id - The id of file
* @param file - File
* @param type - The corresponding type of file, likes '.jpg'.
* @param options - Some optional parameters will be transferred to the corresponding handler.
* @param onComplete - callback when finishing downloading
* @param onComplete.err - The occurred error, null indicates success
* @param onComplete.content - The parsed file
* @param id @en The id of file. @zh 文件的唯一 id。
* @param file @en The data of file. @zh 文件的数据。
* @param type @en The corresponding type of file, likes '.jpg'. @zh 需要使用的解析方法类型。
* @param options @en Some optional parameters will be transferred to the corresponding handler. @zh 传递到解析方法的额外参数。
* @param onComplete @en The callback invoked when finishing parsing. @zh 完成解析的回调。
* @param onComplete.err @en The occurred error, null indicates success. @zh 解析过程中发生的错误,null 表明解析成功。
* @param onComplete.content @en The parsed data. @zh 解析后的数据。
*
* @example
* downloader.download('test.jpg', 'test.jpg', '.jpg', {}, (err, file) => {
@@ -191,7 +227,7 @@ export class Parser {
* });
*
*/
public parse (id: string, file: any, type: string, options: IDownloadParseOptions, onComplete: CompleteCallback): void {
public parse (id: string, file: any, type: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)): void {
const parsedAsset = parsed.get(id);
if (parsedAsset) {
onComplete(null, parsedAsset);
@@ -224,4 +260,4 @@ export class Parser {
}
}
export default new Parser();
export default Parser.instance;
+56 -53
View File
@@ -23,19 +23,14 @@
*/
import { warnID } from '../../core';
import { CompleteCallbackNoData } from './shared';
import Task from './task';
export type IAsyncPipe = (task: Task, done: CompleteCallbackNoData) => void;
export type ISyncPipe = (task: Task) => Error | void;
export type IPipe = IAsyncPipe | ISyncPipe;
/**
* @en
* Pipeline can execute the task for some effect.
* The loading pipeline can complete the loading task by executing a series of phases. [[AssetManager]] uses it to load all assets.
*
* @zh
* 管线能执行任务达到某个效果
* 加载管线能通过执行一系列阶段来完成加载任务。[[AssetManager]] 使用其来加载所有资源。
*
*/
export class Pipeline {
@@ -43,44 +38,46 @@ export class Pipeline {
/**
* @en
* The id of pipeline
* The unique id of this pipeline.
*
* @zh
* 管线的 id
* 管线的唯一 id。
*
*/
public id: number = Pipeline._pipelineId++;
/**
* @en
* The name of pipeline
* The name of this pipeline.
*
* @zh
* 管线的名字
* 此管线的名称。
*
*/
public name = '';
/**
* @en
* All pipes of pipeline
* All pipes of this pipeline.
*
* @zh
* 所有的管道
* 此管线的所有管道。
*
*/
public pipes: IPipe[] = [];
public pipes: Array<((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void)> = [];
/**
* @en
* Create a new pipeline
* Creates a new pipeline.
*
* @zh
* 创建一个管线
* 创建一个管线。
*
* @param name - The name of pipeline
* @param funcs - The array of pipe, every pipe must be function which take two parameters,
* the first is a `Task` flowed in pipeline, the second is complete callback
* @param name - @en The name of pipeline. @zh 管线的名称。
* @param funcs
* @en The array of pipes to create pipeline, every pipe must be function which take two parameters,
* the first is a `Task` flowed in pipeline, the second is complete callback.
* @zh 用于创建管线的管道数组,每个管道必须是一个接受两个参数的方法,第一个参数为任务 [[Task]], 第二个参数为完成回调。
*
* @example
* const pipeline = new Pipeline('download', [
@@ -100,7 +97,7 @@ export class Pipeline {
* ]);
*
*/
constructor (name: string, funcs: IPipe[]) {
constructor (name: string, funcs: Array<((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void)>) {
this.name = name;
for (let i = 0, l = funcs.length; i < l; i++) {
this.pipes.push(funcs[i]);
@@ -109,16 +106,18 @@ export class Pipeline {
/**
* @en
* At specific point insert a new pipe to pipeline
* Inserts a new pipe to pipeline at specific point .
*
* @zh
* 在某个特定的点为管线插入一个新的 pipe
* 在某个特定的点为管线插入一个新的 pipe。
*
* @param func - The new pipe
* @param func.task - The task handled with pipeline will be transferred to this function
* @param func.done - Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary.
* @param index - The specific point you want to insert at.
* @return pipeline
* @param func @en The new pipe to be inserted. @zh 待插入的管道。
* @param func.task @en The task handled with pipeline will be transferred to this function. @zh 正在被此管线处理的任务。
* @param func.done
* @en Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary.
* @zh 当这个管道完成时,你需要手动调用回调。如果管道是同步的,回调就没有必要。
* @param index @en The specific point you want to insert at. @zh 要插入进的位置。
* @return @en Returns the Pipeline itself, which can be used to make chain calls. @zh 返回 Pipeline 本身,可以用于做链式调用。
*
* @example
* var pipeline = new Pipeline('test', []);
@@ -128,7 +127,7 @@ export class Pipeline {
* }, 0);
*
*/
public insert (func: IPipe, index: number): Pipeline {
public insert (func: ((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void), index: number): Pipeline {
if (index > this.pipes.length) {
warnID(4921);
return this;
@@ -140,15 +139,19 @@ export class Pipeline {
/**
* @en
* Append a new pipe to the pipeline
* Appends a new pipe to the pipeline.
*
* @zh
* 添加一个管道到管线中
* 添加一个管道到管线中。
*
* @param func - The new pipe
* @param func.task - The task handled with pipeline will be transferred to this function
* @param func.done - Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary.
* @return pipeline
* @param func @en The new pipe to be appended. @zh 要追加的新管道。
* @param func.task
* @en The task handled with pipeline will be transferred to this function.
* @zh 正在被此管线处理的任务。
* @param func.done
* @en Callback you need to invoke manually when this pipe is finished. if the pipeline is synchronous, callback is unnecessary.
* @zh 当这个管道完成时,你需要手动调用回调。如果管道是同步的,回调就没有必要。
* @return @en Returns the Pipeline itself, which can be used to make chain calls. @zh 返回 Pipeline 本身,可以用于做链式调用。
*
* @example
* var pipeline = new Pipeline('test', []);
@@ -158,20 +161,20 @@ export class Pipeline {
* });
*
*/
public append (func: IPipe): Pipeline {
public append (func: ((task: Task, done: ((err?: Error | null) => void)) => void) | ((task: Task) => Error | void)): Pipeline {
this.pipes.push(func);
return this;
}
/**
* @en
* Remove pipe which at specific point
* Removes pipe which at specific point.
*
* @zh
* 移除特定位置的管道
* 移除特定位置的管道。
*
* @param index - The specific point
* @return pipeline
* @param index @en The specific point. @zh 指定位置的索引。
* @return @en Returns the Pipeline itself, which can be used to make chain calls. @zh 返回 Pipeline 本身,可以用于做链式调用。
*
* @example
* var pipeline = new Pipeline('test', (task, done) => {
@@ -188,13 +191,13 @@ export class Pipeline {
/**
* @en
* Execute task synchronously
* Executes task synchronously.
*
* @zh
* 同步执行任务
* 同步执行任务。
*
* @param task - The task will be executed
* @returns result
* @param task @en The task will be executed. @zh 要执行的任务。
* @returns @en The execution result. @zh 执行结果。
*
* @example
* var pipeline = new Pipeline('sync', [(task) => {
@@ -209,12 +212,12 @@ export class Pipeline {
public sync (task: Task): any {
const pipes = this.pipes;
if (pipes.length === 0) { return null; }
task.isFinish = false;
task.isFinished = false;
for (let i = 0, l = pipes.length; i < l;) {
const pipe = pipes[i] as ISyncPipe;
const pipe = pipes[i] as ((task: Task) => Error | void);
const result = pipe(task);
if (result) {
task.isFinish = true;
task.isFinished = true;
return result;
}
i++;
@@ -223,18 +226,18 @@ export class Pipeline {
task.output = null;
}
}
task.isFinish = true;
task.isFinished = true;
return task.output as unknown;
}
/**
* @en
* Execute task asynchronously
* Executes task asynchronously.
*
* @zh
* 异步执行任务
* 异步执行任务。
*
* @param task - The task will be executed
* @param task @en The task will be executed. @zh 待执行的任务。
*
* @example
* var pipeline = new Pipeline('sync', [(task, done) => {
@@ -249,7 +252,7 @@ export class Pipeline {
public async (task: Task): void {
const pipes = this.pipes;
if (pipes.length === 0) { return; }
task.isFinish = false;
task.isFinished = false;
this._flow(0, task);
}
@@ -257,7 +260,7 @@ export class Pipeline {
const pipe = this.pipes[index];
pipe(task, (result) => {
if (result) {
task.isFinish = true;
task.isFinished = true;
task.dispatch('complete', result);
} else {
index++;
@@ -267,7 +270,7 @@ export class Pipeline {
task.output = null;
this._flow(index, task);
} else {
task.isFinish = true;
task.isFinished = true;
task.dispatch('complete', result, task.output);
}
}
+2 -2
View File
@@ -22,10 +22,10 @@
THE SOFTWARE.
*/
import { CompleteCallbackNoData, RequestType, transformPipeline } from './shared';
import { RequestType, transformPipeline } from './shared';
import Task from './task';
export default function preprocess (task: Task, done: CompleteCallbackNoData) {
export default function preprocess (task: Task, done: ((err?: Error | null) => void)) {
const options = task.options;
const subOptions = Object.create(null);
const leftOptions = Object.create(null);
+34 -25
View File
@@ -26,19 +26,19 @@ import Config, { IAssetInfo } from './config';
/**
* @en
* A collection of information about a request
* A collection of information about a request.
*
* @zh
* 请求的相关信息集合
* 请求的相关信息集合。
*
*/
export default class RequestItem {
/**
* @en
* The id of request, combined from uuid and isNative
* The id of request, combined from uuid and isNative.
*
* @zh
* 请求的 id, 由 uuid 和 isNative 组合而成
* 请求的 id, 由 uuid 和 isNative 组合而成。
*/
get id (): string {
if (!this._id) {
@@ -47,16 +47,19 @@ export default class RequestItem {
return this._id;
}
/**
* @engineInternal
*/
public static MAX_DEAD_NUM = 500;
/**
* @en
* Create a new request item from pool
* Create a new request item from pool.
*
* @zh
* 从对象池中创建 requestItem
* 从对象池中创建 requestItem。
*
* @returns requestItem
* @returns @en return a newly created RequestItem. @zh 返回一个刚创建的 `RequestItem`。
*
*/
public static create (): RequestItem {
@@ -74,84 +77,90 @@ export default class RequestItem {
/**
* @en
* The uuid of request
* The uuid of request.
*
* @zh
* 请求资源的uuid
* 所请求资源的 uuid。
*
*/
public uuid = '';
/**
* @engineInternal only used for L10N asset replacement.
*/
public overrideUuid = '';
/**
* @en
* The final url of request
* The final url of request.
*
* @zh
* 请求的最终url
* 请求的最终 url。
*
*/
public url = '';
/**
* @en
* The extension name of asset
* The extension name of asset.
*
* @zh
* 资源的扩展名
* 资源的扩展名。
*
*/
public ext = '.json';
/**
* @en
* The content of asset
* The content of asset.
*
* @zh
* 资源的内容
* 资源的内容。
*
*/
public content: any = null;
/**
* @en
* The file of asset
* The file of asset.
*
* @zh
* 资源的文件
* 资源的文件。
*
*/
public file: any = null;
/**
* @en
* The information of asset
* The information of asset.
*
* @zh
* 资源的相关信息
* 资源的相关信息。
*
*/
public info: IAssetInfo | null = null;
/**
* @engineInternal
*/
public config: Config | null = null;
/**
* @en
* Whether or not it is native asset
* Whether or not it is native asset.
*
* @zh
* 资源是否是原生资源
* 资源是否是原生资源。
*
*/
public isNative = false;
/**
* @en
* Custom options
* Custom options.
*
* @zh
* 自定义参数
* 自定义参数。
*
*/
public options: Record<string, any> = Object.create(null);
@@ -160,10 +169,10 @@ export default class RequestItem {
/**
* @en
* Recycle this for reuse
* Recycle this to be reused.
*
* @zh
* 回收 requestItem 用于复用
* 回收 requestItem 用于复用。
*
*/
public recycle (): void {
+8 -62
View File
@@ -27,70 +27,8 @@ import { Asset } from '../assets/asset';
import Bundle from './bundle';
import Cache from './cache';
import { Pipeline } from './pipeline';
import RequestItem from './request-item';
import WeakCache from './weak-cache';
export type CompleteCallback<T = any> = (err: Error | null, data?: T | null) => void;
export type CompleteCallbackNoData = (err?: Error | null) => void;
export type CompleteCallbackWithData<T = any> = (err: Error | null, data: T) => void;
export type ProgressCallback = (finished: number, total: number, item: RequestItem) => void;
export type Request = string | string[] | IRequest | Array<IRequest>;
export interface IRequest extends IOptions {
uuid?: string;
url?: string;
path?: string;
dir?: string;
scene?: string;
}
export interface IOptions extends IBundleOptions, IRemoteOptions {
type?: typeof Asset;
bundle?: string;
}
export interface IRemoteOptions extends IAssetOptions {
ext?: string;
}
export interface IXHROptions extends Record<string, any> {
xhrResponseType?: XMLHttpRequestResponseType;
xhrWithCredentials?: boolean;
xhrTimeout?: number;
xhrHeader?: Record<string, string>;
xhrMimeType?: string;
}
export interface IAssetOptions extends INativeAssetOptions {
reloadAsset?: boolean;
cacheAsset?: boolean;
}
export interface IJsonAssetOptions extends IAssetOptions {
assetId?: string;
}
export interface IDownloadParseOptions extends IXHROptions {
priority?: number;
audioLoadMode?: number;
onFileProgress?: (loaded: number, total: number) => void;
maxConcurrency?: number;
maxRequestsPerFrame?: number;
maxRetryCount?: number;
cacheEnabled?: boolean;
}
export interface IBundleOptions extends INativeAssetOptions {
version?: string;
scriptAsyncLoading?: boolean;
}
export interface INativeAssetOptions extends IDownloadParseOptions {
preset?: string;
}
export type AssetType<T = Asset> = Constructor<T>;
export const assets = EDITOR ? new WeakCache<Asset>() : new Cache<Asset>();
export const files = new Cache();
export const parsed = new Cache();
@@ -114,6 +52,14 @@ export enum RequestType {
SCENE = 'scene',
}
export interface IRequest extends Record<string, any> {
uuid?: string;
url?: string;
path?: string;
dir?: string;
scene?: string;
}
export const presets: Record<string, Record<string, any>> = {
default: {
+112 -79
View File
@@ -22,13 +22,10 @@
THE SOFTWARE.
*/
export type TaskCompleteCallback = (err: Error | null | undefined, data: any) => void;
export type TaskProgressCallback = (...args: any[]) => void;
export type TaskErrorCallback = (...args: any[]) => void;
export interface ITaskOption {
onComplete?: TaskCompleteCallback | null;
onProgress?: TaskProgressCallback | null;
onError?: TaskErrorCallback | null;
onComplete?: ((err: Error | null | undefined, data: any) => void) | null;
onProgress?: ((...args: any[]) => void) | null;
onError?: ((...args: any[]) => void) | null;
input: any;
progress?: any;
options?: Record<string, any> | null;
@@ -36,32 +33,40 @@ export interface ITaskOption {
/**
* @en
* Task is used to run in the pipeline for some effect
* Tasks are the smallest unit of data running in the pipeline, You can create a task and pass in the input information,
* and then get the output of that task after it has been executed in the pipeline to use.
*
* @zh
* 任务用于在管线中运行以达成某种效果
* 任务是在管线中运行的最小数据单位,你可以创建一个任务并传入输入信息,在经过管线执行后获取该任务的输出来使用。
*
*/
export default class Task {
/**
* @engineInternal
*/
public static MAX_DEAD_NUM = 500;
/**
* @en
* Create a new task from pool
* Create a new task from pool.
*
* @zh
* 从对象池中创建 task
* 从对象池中创建 task。
*
* @static
* @method create
* @param options - Some optional paramters
* @param options.onComplete - Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary.
* @param options.onProgress - Continuously callback when the task is runing, if the pipeline is synchronous, onProgress is unnecessary.
* @param options.onError - Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary.
* @param options.input - Something will be handled with pipeline
* @param options.progress - Progress information, you may need to assign it manually when multiple pipeline share one progress
* @param options.options - Custom parameters
* @returns task
* @param options @en Some optional parameters. @zh 一些可选参数。
* @param options.onComplete
* @en Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary.
* @zh 任务完成后的回调,如果流水线是同步的,onComplete 是不必要的。
* @param options.onProgress
* @en Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary.
* @zh 在任务运行时持续回调,如果管道是同步的,onProgress 是不必要的。
* @param options.onError
* @en Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary.
* @zh 出错时的回调,如果流水线是同步的,onError 是不必要的。
* @param options.input @en Something will be handled with pipeline. @zh 需要被此管道处理的任务数据。
* @param options.progress @en Progress information. @zh 进度信息。
* @param options.options @en Custom parameters. @zh 自定义参数。
* @returns @en return a newly created task. @zh 返回一个新创建的任务。
*
*/
public static create (options: ITaskOption): Task {
@@ -81,117 +86,138 @@ export default class Task {
/**
* @en
* The id of task
* The id of task.
*
* @zh
* 任务id
* 任务 id。
*
*/
public id: number = Task._taskId++;
/**
* @en
* The callback when task is completed
* The callback when task is completed.
*
* @zh
* 完成回调
* 完成回调。
*
*/
public onComplete: TaskCompleteCallback | null = null;
public onComplete: ((err: Error | null | undefined, data: any) => void) | null = null;
/**
* @en
* The callback of progression
* The callback of progression.
*
* @zh
* 进度回调
* 进度回调。
*
*/
public onProgress: TaskProgressCallback | null = null;
public onProgress: ((...args: any[]) => void) | null = null;
/**
* @en
* The callback when something goes wrong
* The callback when something goes wrong.
*
* @zh
* 错误回调
* 错误回调。
*
*/
public onError: TaskErrorCallback | null = null;
public onError: ((...args: any[]) => void) | null = null;
/**
* @en
* The source of task
* The source data of task.
*
* @zh
* 任务的源
* 任务的源数据。
*
*/
public source: any = null;
/**
* @en
* The output of task
* The output of task.
*
* @zh
* 任务的输出
* 任务的输出。
*/
public output: any = null;
/**
* @en
* The input of task
* The input of task.
*
* @zh
* 任务的输入
* 任务的输入。
*
*/
public input: any = null;
/**
* @en
* The progression of task
* The progression of task.
*
* @zh
* 任务的进度
* 任务的进度。
*
*/
public progress: any = null;
/**
* @en
* Custom options
* Custom options.
*
* @zh
* 自定义参数
* 自定义参数。
*
*/
public options: Record<string, any> | null = null;
/**
* @en
* Whether or not this task is completed
*
* @zh
* 此任务是否已经完成
*
* @deprecated Typo. Since v3.7, please use [[Task.isFinished]] instead.
*/
public isFinish = true;
public get isFinish () {
return this.isFinished;
}
/**
* @deprecated Typo. Since v3.7, please use [[Task.isFinished]] instead.
*/
public set isFinish (val: boolean) {
this.isFinished = val;
}
/**
* @en
* Create a new Task
* Whether or not this task is completed.
*
* @zh
* 创建一个任务
* 此任务是否已经完成。
*
* @param options - Some optional paramters
* @param options.onComplete - Callback when the task is completed, if the pipeline is synchronous, onComplete is unnecessary.
* @param options.onProgress - Continuously callback when the task is runing, if the pipeline is synchronous, onProgress is unnecessary.
* @param options.onError - Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary.
* @param options.input - Something will be handled with pipeline
* @param options.progress - Progress information, you may need to assign it manually when multiple pipeline share one progress
* @param options.options - Custom parameters
*/
public isFinished = true;
/**
* @en
* Create a new Task.
*
* @zh
* 创建一个任务。
*
* @param options @en Some optional parameters. @zh 一些可选参数。
* @param options.onComplete
* @en Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary.
* @zh 任务完成后的回调,如果流水线是同步的,onComplete 是不必要的。
* @param options.onProgress
* @en Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary.
* @zh 在任务运行时持续回调,如果管道是同步的,onProgress 是不必要的。
* @param options.onError
* @en Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary.
* @zh 出错时的回调,如果流水线是同步的,onError 是不必要的。
* @param options.input @en Something will be handled with pipeline. @zh 需要被此管道处理的任务数据。
* @param options.progress @en Progress information. @zh 进度信息。
* @param options.options @en Custom parameters. @zh 自定义参数。
* @returns @en return a newly created task. @zh 返回一个新创建的任务。
*/
public constructor (options?: ITaskOption) {
this.set(options);
@@ -199,21 +225,28 @@ export default class Task {
/**
* @en
* Set parameters of this task
* Set parameters of this task.
*
* @zh
* 设置任务的参数
* 设置任务的参数。
*
* @param options - Some optional parameters
* @param options.onComplete - Callback when the task is completed, if the pipeline is synchronous, onComplete is unnecessary.
* @param options.onProgress - Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary.
* @param options.onError - Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary.
* @param options.input - Something will be handled with pipeline
* @param options.progress - Progress information, you may need to assign it manually when multiple pipeline share one progress
* @param options.options - Custom parameters
* @param options @en Some optional parameters. @zh 一些可选参数。
* @param options.onComplete
* @en Callback when the task complete, if the pipeline is synchronous, onComplete is unnecessary.
* @zh 任务完成后的回调,如果流水线是同步的,onComplete 是不必要的。
* @param options.onProgress
* @en Continuously callback when the task is running, if the pipeline is synchronous, onProgress is unnecessary.
* @zh 在任务运行时持续回调,如果管道是同步的,onProgress 是不必要的。
* @param options.onError
* @en Callback when something goes wrong, if the pipeline is synchronous, onError is unnecessary.
* @zh 出错时的回调,如果流水线是同步的,onError 是不必要的。
* @param options.input @en Something will be handled with pipeline. @zh 需要被此管道处理的任务数据。
* @param options.progress @en Progress information. @zh 进度信息。
* @param options.options @en Custom parameters. @zh 自定义参数。
* @returns @en return a newly created task. @zh 返回一个新创建的任务。
*
* @example
* var task = new Task();
* const task = new Task();
* task.set({input: ['test'], onComplete: (err, result) => console.log(err), onProgress: (finish, total) => console.log(finish / total)});
*
*/
@@ -230,21 +263,21 @@ export default class Task {
/**
* @en
* Dispatch event
* Dispatch event with any parameter.
*
* @zh
* 发布事件
* 分发事件,可以传递任意参数。
*
* @param event - The event name
* @param param1 - Parameter 1
* @param param2 - Parameter 2
* @param param3 - Parameter 3
* @param param4 - Parameter 4
* @param event @en The event name. @zh 事件名称。
* @param param1 @en The parameter 1. @zh 参数 1。
* @param param2 @en The parameter 2. @zh 参数 2。
* @param param3 @en The parameter 3. @zh 参数 3。
* @param param4 @en The parameter 4. @zh 参数 4。
*
* @example
* var task = Task.create();
* Task.onComplete = (msg) => console.log(msg);
* Task.dispatch('complete', 'hello world');
* const task = Task.create();
* task.onComplete = (msg) => console.log(msg);
* task.dispatch('complete', 'hello world');
*
*/
public dispatch (event: string, param1?: any, param2?: any, param3?: any, param4?: any): void {
@@ -276,10 +309,10 @@ export default class Task {
/**
* @en
* Recycle this for reuse
* Recycle this task to be reused.
*
* @zh
* 回收 task 用于复用
* 回收 task 用于复用。
*
*/
public recycle (): void {
+17 -17
View File
@@ -30,16 +30,16 @@ import { dependMap, nativeDependMap } from './depend-maps';
import dependUtil from './depend-util';
import { isScene } from './helper';
import RequestItem from './request-item';
import { assets, AssetType, CompleteCallbackNoData, CompleteCallback, IOptions, ProgressCallback, references } from './shared';
import { assets, references } from './shared';
import Task from './task';
let defaultProgressCallback: ProgressCallback | null = null;
let defaultProgressCallback: ((finished: number, total: number, item: RequestItem) => void) | null = null;
declare class WeakRef {
constructor (obj: any);
}
export function setDefaultProgressCallback (onProgress: ProgressCallback) {
export function setDefaultProgressCallback (onProgress: (finished: number, total: number, item: RequestItem) => void) {
defaultProgressCallback = onProgress;
}
@@ -67,9 +67,9 @@ export function urlAppendTimestamp (url: string, append: boolean): string {
return url;
}
export type RetryFunction = (times: number, done: CompleteCallback) => void;
export type RetryFunction = (times: number, done: ((err: Error | null, data?: any | null) => void)) => void;
export function retry (process: RetryFunction, times: number, wait: number, onComplete: CompleteCallback, index = 0) {
export function retry (process: RetryFunction, times: number, wait: number, onComplete: ((err: Error | null, data?: any | null) => void), index = 0) {
process(index, (err, result) => {
index++;
if (!err || index > times) {
@@ -182,7 +182,7 @@ export function gatherAsset (task: Task) {
}
}
type ForEachFunction<T> = (item: T, done: CompleteCallbackNoData) => void;
type ForEachFunction<T> = (item: T, done: ((err?: Error | null) => void)) => void;
export function forEach<T = any> (array: T[], process: ForEachFunction<T>, onComplete: (errs: Error[]) => void) {
let count = 0;
@@ -208,20 +208,20 @@ export function forEach<T = any> (array: T[], process: ForEachFunction<T>, onCom
}
interface IParameters<T> {
options: IOptions;
onProgress: ProgressCallback | null;
options: Record<string, any>;
onProgress: ((finished: number, total: number, item: RequestItem) => void) | null;
onComplete: T | null;
}
interface ILoadResArgs<T> {
type: AssetType | null;
onProgress: ProgressCallback | null;
type: Constructor<Asset> | null;
onProgress: ((finished: number, total: number, item: RequestItem) => void) | null;
onComplete: T | null;
}
export function parseParameters<T extends (...args) => void> (
options: IOptions | ProgressCallback | T | null | undefined,
onProgress: ProgressCallback | T | null | undefined,
options: Record<string, any> | ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined,
onProgress: ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined,
onComplete: T | null | undefined): IParameters<T> {
let optionsOut: any = options;
let onProgressOut: any = onProgress;
@@ -239,7 +239,7 @@ export function parseParameters<T extends (...args) => void> (
onProgressOut = null;
}
if (onProgress !== undefined && isCallback) {
onProgressOut = options as ProgressCallback;
onProgressOut = options as ((finished: number, total: number, item: RequestItem) => void);
optionsOut = null;
}
}
@@ -248,14 +248,14 @@ export function parseParameters<T extends (...args) => void> (
}
export function parseLoadResArgs<T extends (...args) => void> (
type: AssetType | ProgressCallback | T | null | undefined,
onProgress: ProgressCallback | T | null | undefined,
type: Constructor<Asset> | ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined,
onProgress: ((finished: number, total: number, item: RequestItem) => void) | T | null | undefined,
onComplete: T | null | undefined): ILoadResArgs<T> {
let typeOut: any = type;
let onProgressOut: any = onProgress;
let onCompleteOut: any = onComplete;
if (onComplete === undefined) {
const isValidType = js.isChildClassOf(type as AssetType, Asset);
const isValidType = js.isChildClassOf(type as Constructor<Asset>, Asset);
if (onProgress) {
onCompleteOut = onProgress as T;
if (isValidType) {
@@ -267,7 +267,7 @@ export function parseLoadResArgs<T extends (...args) => void> (
typeOut = null;
}
if (onProgress !== undefined && !isValidType) {
onProgressOut = type as ProgressCallback;
onProgressOut = type as ((finished: number, total: number, item: RequestItem) => void);
typeOut = null;
}
}
+89 -16
View File
@@ -76,12 +76,24 @@ export class Asset extends Eventify(CCObject) {
public loaded = true;
/**
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
* @en
* The UUID of this asset.
*
* @zh
* 资源的 UUID。
*
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future, please use [[Asset.uuid]] instead.
*/
public declare _uuid: string;
/**
* @internal
* @en
* Indicates whether this asset is a default asset.
*
* @zh
* 表明此资源是否是默认资源。
*
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public declare isDefault: boolean;
@@ -96,8 +108,14 @@ export class Asset extends Eventify(CCObject) {
*/
@serializable
public _native = '';
/**
* @internal
* @en
* Path to native dependency.
* @zh
* 原生依赖的路径。
*
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
*/
public _nativeUrl = '';
@@ -106,9 +124,9 @@ export class Asset extends Eventify(CCObject) {
/**
* @en
* Returns the url of this asset's native object, if none it will returns an empty string.
* Returns the url of this asset's native object, will return an empty string if this asset does not have any native dependency.
* @zh
* 返回该资源对应的目标平台资源的 URL,如果没有将返回一个空字符串。
* 返回该资源对应的目标平台资源的 URL,如果此资源没有原生依赖将返回一个空字符串。
* @readOnly
*/
get nativeUrl () {
@@ -131,6 +149,17 @@ export class Asset extends Eventify(CCObject) {
return this._nativeUrl;
}
/**
* @en
* The UUID of this asset.
*
* @zh
* 资源的 UUID。
*/
get uuid () {
return this._uuid;
}
/**
* @en
* The underlying native asset of this asset if one is available.<br>
@@ -188,7 +217,7 @@ export class Asset extends Eventify(CCObject) {
* 否则,返回空字符串。<br>
* 子类可能会覆盖此方法。
* @method toString
* @return {String}
* @returns @en String representation of this asset. @zh 此资源的字符串表示。
*/
public toString () {
return this.nativeUrl;
@@ -199,7 +228,7 @@ export class Asset extends Eventify(CCObject) {
* 返回一个序列化后的对象
*
* @method serialize
* @return {String}
* @returns {String}
* @private
*/
public serialize () { }
@@ -234,7 +263,15 @@ export class Asset extends Eventify(CCObject) {
public createNode? (callback: CreateNodeCallback): void;
/**
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
* @en
* Get native dependency information.
*
* @zh
* 获取原生依赖信息。
*
* @returns @en The native dependency information. @zh 原生依赖信息。
*
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public get _nativeDep () {
if (this._native) {
@@ -245,10 +282,10 @@ export class Asset extends Eventify(CCObject) {
/**
* @en
* The number of reference
* Current reference count to this asset.
*
* @zh
* 引用的数量
* 当前该资源被引用的数量。
*/
public get refCount (): number {
return this._ref;
@@ -256,12 +293,13 @@ export class Asset extends Eventify(CCObject) {
/**
* @en
* Add references of asset
* Increase the reference count. This will prevent assets from being automatically recycled.
* When you no longer need to hold the asset, you need to using [[decRef]] to decrease the refCount.
*
* @zh
* 增加资源的引用
* 增加资源的引用。这将阻止资源被自动释放。当你不再需要持有该资源时,你需要调用 [[decRef]] 来减少引用计数。
*
* @return itself
* @returns @en The asset itself. @zh 此资源本身。
*
*/
public addRef (): Asset {
@@ -271,12 +309,12 @@ export class Asset extends Eventify(CCObject) {
/**
* @en
* Reduce references of asset and it will be auto released when refCount equals 0.
* Decrease the reference count and it will be auto released when refCount equals 0.
*
* @zh
* 减少资源的引用并尝试进行自动释放。
* 减少资源的引用,如果引用数量为 0,则将自动释放该资源。
*
* @return itself
* @return @en The asset itself. @zh 此资源本身。
*
*/
public decRef (autoRelease = true): Asset {
@@ -289,17 +327,52 @@ export class Asset extends Eventify(CCObject) {
return this;
}
/**
* @en
* A callback after the asset is loaded that you can use to initialize the asset's internal data.
*
* @zh
* 资源加载后的回调,你可以用于初始化资源的内部数据。
*
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public onLoaded () {}
/**
* @en
* Initializes default asset.
*
* @zh
* 初始化为默认资源。
*
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public initDefault (uuid?: string) {
if (uuid) { this._uuid = uuid; }
this.isDefault = true;
}
/**
* @en
* Used to verify this asset is an available asset.
*
* @zh
* 用于验证此资源是否为可用资源。
*
* @returns @zh 是否是可用资源。@en Whether this asset is available or not.
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public validate (): boolean {
return true;
}
/**
* @en
* Destroy this asset and its internal data.
*
* @zh
* 销毁此资源以及其内部数据。
*/
public destroy () {
debug(getError(12101, this._uuid));
return super.destroy();
+7
View File
@@ -26,6 +26,13 @@ import { ccclass, override } from 'cc.decorator';
import { assertIsNonNullable, cclegacy } from '../../core';
import { Asset } from './asset';
/**
* @en
* `BufferAsset` is a kind of assets whose internal data is a section of memory buffer
* that you can access through the [[BufferAsset.buffer]] function.
* @zh
* `BufferAsset` 是一类资产,其内部数据是一段内存缓冲,你可以通过 [[BufferAsset.buffer]] 函数获取其内部数据。
*/
@ccclass('cc.BufferAsset')
export class BufferAsset extends Asset {
private _buffer: ArrayBuffer | null = null;
+33 -5
View File
@@ -211,8 +211,10 @@ const legacyBuiltinEffectNames = [
@ccclass('cc.EffectAsset')
export class EffectAsset extends Asset {
/**
* @en Register the effect asset to the static map
* @en Register the effect asset to the static map.
* @zh 将指定 effect 注册到全局管理器。
*
* @param asset @en The effect asset to be registered. @zh 待注册的 effect asset。
*/
public static register (asset: EffectAsset) {
EffectAsset._effects[asset.name] = asset;
@@ -222,6 +224,8 @@ export class EffectAsset extends Asset {
/**
* @en Unregister the effect asset from the static map
* @zh 将指定 effect 从全局管理器移除。
*
* @param asset - @en The effect asset to be removed. @zh 待移除的 effect asset。
*/
public static remove (asset: EffectAsset | string) {
if (typeof asset !== 'string') {
@@ -240,8 +244,11 @@ export class EffectAsset extends Asset {
}
/**
* @en Get the effect asset by the given name.
* @en Gets the effect asset by the given name.
* @zh 获取指定名字的 effect 资源。
*
* @param name - @en The name of effect you want to get. @zh 想要获取的 effect 的名字。
* @returns @en The effect. @zh 你查询的 effect.
*/
public static get (name: string) {
if (EffectAsset._effects[name]) { return EffectAsset._effects[name]; }
@@ -257,14 +264,28 @@ export class EffectAsset extends Asset {
}
/**
* @en Get all registered effect assets.
* @en Gets all registered effect assets.
* @zh 获取所有已注册的 effect 资源。
* @returns @en All registered effects. @zh 所有已注册的 effect 资源。
*/
public static getAll () { return EffectAsset._effects; }
/**
* @engineInternal
*/
protected static _effects: Record<string, EffectAsset> = {};
/**
* @engineInternal
*/
public static isLayoutValid (): boolean { return EffectAsset._layoutValid; }
/**
* @engineInternal
*/
public static setLayoutValid (): void { EffectAsset._layoutValid = true; }
/**
* @engineInternal
*/
protected static _layoutValid = true;
/**
@@ -291,13 +312,17 @@ export class EffectAsset extends Asset {
@editable
public combinations: EffectAsset.IPreCompileInfo[] = [];
/**
* @en Whether to hide in editor mode.
* @zh 是否在编辑器内隐藏。
*/
@serializable
@editorOnly
public hideInEditor = false;
/**
* @en The loaded callback which should be invoked by the [[CCLoader]], will automatically register the effect.
* @zh 通过 [[CCLoader]] 加载完成时的回调,将自动注册 effect 资源。
* @en The loaded callback which should be invoked by the [[AssetManager]], will automatically register the effect.
* @zh 通过 [[AssetManager]] 加载完成时的回调,将自动注册 effect 资源。
*/
public onLoaded () {
if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) {
@@ -310,6 +335,9 @@ export class EffectAsset extends Asset {
if (!EDITOR || cclegacy.GAME_VIEW) { cclegacy.game.once(cclegacy.Game.EVENT_RENDERER_INITED, this._precompile, this); }
}
/**
* @engineInternal
*/
protected _precompile () {
if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) {
(cclegacy.rendering.programLib as ProgramLibrary).precompileEffect(deviceManager.gfxDevice, this);
+36 -36
View File
@@ -24,7 +24,7 @@
// @ts-check
import { ccclass, override } from 'cc.decorator';
import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU } from 'internal:constants';
import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU, TAOBAO } from 'internal:constants';
import { Device, Format, FormatFeatureBit, deviceManager } from '../../gfx';
import { Asset } from './asset';
import { PixelFormat } from './asset-enum';
@@ -163,7 +163,7 @@ function fetchImageSource (imageSource: ImageSource) {
// 返回该图像源是否是平台提供的图像对象。
function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElement | HTMLCanvasElement | ImageBitmap) {
if (ALIPAY || XIAOMI || BAIDU) {
if (ALIPAY || TAOBAO || XIAOMI || BAIDU) {
// We're unable to grab the constructors of Alipay native image or canvas object.
return !('_data' in imageSource);
}
@@ -175,8 +175,8 @@ function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElem
}
/**
* @en Image Asset.
* @zh 图像资源。
* @en Image Asset. The image resource stores the raw data of the image and you can use this resource to create any Texture resource.
* @zh 图像资源。图像资源存储了图像的原始数据,你可以使用此资源来创建任意 [[TextureBase]] 资源。
*/
@ccclass('cc.ImageAsset')
export class ImageAsset extends Asset {
@@ -202,8 +202,8 @@ export class ImageAsset extends Asset {
* * * *
* ****************************** *
* *************************************
* @param files @zh 压缩纹理数组 @en Compressed Texture Arrays
* @returns out @zh 合并后的压缩纹理数据 @en Merged compressed texture data
* @param files @zh 压缩纹理数组。 @en Compressed Texture Arrays.
* @returns out @zh 合并后的压缩纹理数据。 @en Merged compressed texture data.
*/
public static mergeCompressedTextureMips (files: ArrayBuffer[] | ArrayBufferView[]) {
let out = new Uint8Array(0);
@@ -253,8 +253,8 @@ export class ImageAsset extends Asset {
}
/**
* @param file 解析压缩纹理
* @param type 压缩纹理类型
* @param file 解析压缩纹理。
* @param type 压缩纹理类型。
* @engineInternal
*/
public static parseCompressedTextures (file: ArrayBuffer | ArrayBufferView, type: number) {
@@ -296,13 +296,13 @@ export class ImageAsset extends Asset {
}
/**
* @zh 解析压缩纹理
* @param file @zh ccon 文件
* @param levelIndex @zh 当前 mipmap 层级
* @param beginOffset @zh 压缩纹理开始时的偏移
* @param endOffset @zh 压缩纹理结束时的偏移
* @param type @zh 压缩纹理类型
* @param out @zh 压缩纹理输出
* @zh 解析压缩纹理。
* @param file @zh 压缩纹理原始数据。
* @param levelIndex @zh 当前 mipmap 层级。
* @param beginOffset @zh 压缩纹理开始时的偏移。
* @param endOffset @zh 压缩纹理结束时的偏移。
* @param type @zh 压缩纹理类型。
* @param out @zh 压缩纹理输出。
* @engineInternal
*/
public static parseCompressedTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number,
@@ -323,12 +323,12 @@ export class ImageAsset extends Asset {
}
/**
* @zh 解析 PVR 格式的压缩纹理
* @param file @zh ccon 文件
* @param levelIndex @zh 当前 mipmap 层级
* @param beginOffset @zh 压缩纹理开始时的偏移
* @param endOffset @zh 压缩纹理结束时的偏移
* @param out @zh 压缩纹理输出
* @zh 解析 PVR 格式的压缩纹理。
* @param file @zh 压缩纹理原始数据。
* @param levelIndex @zh 当前 mipmap 层级。
* @param beginOffset @zh 压缩纹理开始时的偏移。
* @param endOffset @zh 压缩纹理结束时的偏移。
* @param out @zh 压缩纹理输出。
* @engineInternal
*/
public static parsePVRTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number,
@@ -375,12 +375,12 @@ export class ImageAsset extends Asset {
}
/**
* @zh 解析 PKM 格式的压缩纹理
* @param file @zh ccon 文件
* @param levelIndex @zh 当前 mipmap 层级
* @param beginOffset @zh 压缩纹理开始时的偏移
* @param endOffset @zh 压缩纹理结束时的偏移
* @param out @zh 压缩纹理输出
* @zh 解析 PKM 格式的压缩纹理。
* @param file @zh 压缩纹理原始数据。
* @param levelIndex @zh 当前 mipmap 层级。
* @param beginOffset @zh 压缩纹理开始时的偏移。
* @param endOffset @zh 压缩纹理结束时的偏移。
* @param out @zh 压缩纹理输出。
* @engineInternal
*/
public static parsePKMTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number,
@@ -409,12 +409,12 @@ export class ImageAsset extends Asset {
}
/**
* @zh 解析 ASTC 格式的压缩纹理
* @param file @zh ccon 文件
* @param levelIndex @zh 当前 mipmap 层级
* @param beginOffset @zh 压缩纹理开始时的偏移
* @param endOffset @zh 压缩纹理结束时的偏移
* @param out @zh 压缩纹理输出
* @zh 解析 ASTC 格式的压缩纹理。
* @param file @zh 压缩纹理原始数据。
* @param levelIndex @zh 当前 mipmap 层级。
* @param beginOffset @zh 压缩纹理开始时的偏移。
* @param endOffset @zh 压缩纹理结束时的偏移。
* @param out @zh 压缩纹理输出。
* @engineInternal
*/
public static parseASTCTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number,
@@ -571,7 +571,7 @@ export class ImageAsset extends Asset {
/**
* @en Reset the source of the image asset.
* @zh 重置此图像资源使用的原始图像源。
* @param data The new source
* @param data @en The new source. @zh 新的图片数据源。
*/
public reset (data: ImageSource) {
if (isImageBitmap(data)) {
@@ -602,7 +602,7 @@ export class ImageAsset extends Asset {
// SERIALIZATION
/**
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
* @engineInternal
*/
// eslint-disable-next-line consistent-return
public _serialize () {
@@ -631,7 +631,7 @@ export class ImageAsset extends Asset {
}
/**
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
* @engineInternal
*/
public _deserialize (data: any) {
let fmtStr = '';
+1 -1
View File
@@ -39,7 +39,7 @@ export default class JsonAsset extends Asset {
*/
@serializable
@editable
public json: object | null = null;
public json: Record<string, any> | null = null;
}
cclegacy.JsonAsset = JsonAsset;
+71 -18
View File
@@ -98,23 +98,44 @@ export class Material extends Asset {
return hash;
}
/**
* @engineInternal
*/
@type(EffectAsset)
protected _effectAsset: EffectAsset | null = null;
/**
* @internal
*/
@serializable
protected _techIdx = 0;
/**
* @internal
*/
@serializable
protected _defines: MacroRecord[] = [];
/**
* @internal
*/
@serializable
protected _states: PassOverrides[] = [];
/**
* @internal
*/
@serializable
protected _props: Record<string, MaterialPropertyFull | MaterialPropertyFull[]>[] = [];
/**
* @internal
*/
protected _passes: Pass[] = [];
/**
* @internal
*/
protected _hash = 0;
constructor () {
@@ -162,16 +183,16 @@ export class Material extends Asset {
}
/**
* @en The parent material
* @zh 父材质
* @en The parent material.
* @zh 父材质。
*/
get parent (): Material | null {
return null;
}
/**
* @en The owner render component
* @zh 该材质所归属的渲染组件
* @en The owner render component.
* @zh 该材质所归属的渲染组件。
*/
get owner (): Renderer | null {
return null;
@@ -180,7 +201,7 @@ export class Material extends Asset {
/**
* @en Initialize this material with the given information.
* @zh 根据所给信息初始化这个材质,初始化正常结束后材质即可立即用于渲染。
* @param info Material description info.
* @param info @en Material description info. @zh 材质描述信息
*/
public initialize (info: IMaterialInfo) {
if (this._passes.length) {
@@ -195,6 +216,12 @@ export class Material extends Asset {
this._update();
}
/**
* @en Reset the material with the given information.
* @zh 使用指定的信息重置该材质。
*
* @param info @en Material description info. @zh 材质描述信息。
*/
public reset (info: IMaterialInfo) { // to be consistent with other assets
this.initialize(info);
}
@@ -219,8 +246,8 @@ export class Material extends Asset {
/**
* @en Recompile the shader with the specified macro overrides. Allowed only on material instances.
* @zh 使用指定预处理宏重新编译当前 pass(数组)中的 shader。只允许对材质实例执行。
* @param overrides The shader macro override values.
* @param passIdx The pass to apply to. Will apply to all passes if not specified.
* @param overrides @en The shader macro override values. @zh 宏的覆盖值,用于编译不同 Shader 变体。
* @param passIdx @en The pass to apply to. Will apply to all passes if not specified. @zh 要重编的 pass 索引,如果没有指定,则重编所有 pass。
*/
public recompileShaders (overrides: MacroRecord, passIdx?: number) {
console.warn(`Shaders in material asset '${this.name}' cannot be modified at runtime, please instantiate the material first.`);
@@ -237,8 +264,8 @@ export class Material extends Asset {
}
/**
* @en Callback function after material is loaded in [[CCLoader]]. Initialize the resources automatically.
* @zh 通过 [[CCLoader]] 加载完成时的回调,将自动初始化材质资源。
* @en Callback function after material is loaded in [[AssetManager]]. Initialize the resources automatically.
* @zh 通过 [[AssetManager]] 加载完成时的回调,将自动初始化材质资源。
*/
public onLoaded () {
this._update();
@@ -247,7 +274,7 @@ export class Material extends Asset {
/**
* @en Reset all the uniforms to the default value specified in [[EffectAsset]].
* @zh 重置材质的所有 uniform 参数数据为 [[EffectAsset]] 中的默认初始值。
* @param clearPasses Will the rendering data be cleared too?
* @param clearPasses @en Whether to clear the rendering data too. @zh 是否同时清空渲染数据。
*/
public resetUniforms (clearPasses = true) {
this._props.length = this._passes.length;
@@ -266,9 +293,11 @@ export class Material extends Asset {
* @zh
* 设置材质 uniform 参数的统一入口。<br>
* 注意如果需要每帧更新 uniform,建议使用 [[renderer.Pass.setUniform]] 以获得更好的性能。
* @param name The target uniform name.
* @param val The target value.
* @param passIdx The pass to apply to. Will apply to all passes if not specified.
* @param name @en The target uniform name. @zh 目标 Uniform 名称。
* @param val @en The target value. @zh 需要设置的目标值。
* @param passIdx
* @en The pass to apply to. Will apply to all passes if not specified.
* @zh 设置此属性的 pass 索引,如果没有指定,则会设置此属性到所有 pass 上。
*/
public setProperty (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) {
let success = false;
@@ -297,15 +326,18 @@ export class Material extends Asset {
/**
* @en
* Get the specified uniform value for this material.<br>
* Gets the specified uniform value for this material.<br>
* Note that only uniforms set through [[Material.setProperty]] can be acquired here.<br>
* For the complete rendering data, use [[renderer.Pass.getUniform]] instead.
* @zh
* 获取当前材质的指定 uniform 参数的值。<br>
* 注意只有通过 [[Material.setProperty]] 函数设置的参数才能从此函数取出,<br>
* 如需取出完整的渲染数据,请使用 [[renderer.Pass.getUniform]]。
* @param name The property or uniform name.
* @param passIdx The target pass index. If not specified, return the first found value in all passes.
* @param name @en The property or uniform name. @zh 属性或 Uniform 的名称。
* @param passIdx
* @en The target pass index. If not specified, return the first found value in all passes.
* @zh 目标 pass 索引,如果没指定,则返回所有 pass 中第一个找到的值。
* @return @en The acquired material properties. @zh 获取的材质属性。
*/
public getProperty (name: string, passIdx?: number): Readonly<MaterialPropertyFull | MaterialPropertyFull[]> {
if (passIdx === undefined) { // try get property in all possible passes
@@ -326,8 +358,8 @@ export class Material extends Asset {
/**
* @en Copy the target material, with optional overrides.
* @zh 复制目标材质到当前实例,允许提供重载信息。
* @param mat The material to be copied.
* @param overrides The overriding states on top of the original material.
* @param mat @en The material to be copied. @zh 需要拷贝的原始材质。
* @param overrides @en The overriding states on top of the original material. @zh 需要在原始材质上覆盖的状态。
*/
public copy (mat: Material, overrides?: IMaterialInfo) {
this._techIdx = mat._techIdx;
@@ -348,6 +380,9 @@ export class Material extends Asset {
this._update();
}
/**
* @engineInternal
*/
protected _fillInfo (info: IMaterialInfo) {
if (info.technique !== undefined) { this._techIdx = info.technique; }
if (info.effectAsset) {
@@ -359,6 +394,9 @@ export class Material extends Asset {
if (info.states) { this._prepareInfo(info.states, this._states); }
}
/**
* @engineInternal
*/
protected _prepareInfo (patch: Record<string, unknown> | Record<string, unknown>[], cur: Record<string, unknown>[]) {
let patchArray = patch;
if (!Array.isArray(patchArray)) { // fill all the passes if not specified
@@ -370,6 +408,9 @@ export class Material extends Asset {
}
}
/**
* @engineInternal
*/
protected _createPasses () {
const tech = this._effectAsset!.techniques[this._techIdx || 0];
if (!tech) { return []; }
@@ -394,6 +435,9 @@ export class Material extends Asset {
return passes;
}
/**
* @engineInternal
*/
protected _update (keepProps = true) {
if (this._effectAsset) {
this._passes = this._createPasses();
@@ -418,6 +462,9 @@ export class Material extends Asset {
this._hash = Material.getHash(this);
}
/**
* @engineInternal
*/
protected _uploadProperty (pass: Pass, name: string, val: MaterialPropertyFull | MaterialPropertyFull[]) {
const handle = pass.getHandle(name);
if (!handle) { return false; }
@@ -448,6 +495,9 @@ export class Material extends Asset {
return true;
}
/**
* @engineInternal
*/
protected _bindTexture (pass: Pass, handle: number, val: MaterialPropertyFull, index?: number) {
const binding = Pass.getBindingFromHandle(handle);
if (val instanceof Texture) {
@@ -463,6 +513,9 @@ export class Material extends Asset {
}
}
/**
* @engineInternal
*/
protected _doDestroy () {
if (this._passes && this._passes.length) {
for (const pass of this._passes) {
+24 -20
View File
@@ -69,7 +69,7 @@ export class RenderTexture extends TextureBase {
/**
* @en Initialize the render texture. Using IRenderTextureCreateInfo.
* @zh 初始化渲染贴图。设置渲染贴图的名称、尺寸、渲染通道信息。
* @param info @en The create info of render texture @zh 渲染贴图的创建信息
* @param info @en The create info of render texture. @zh 渲染贴图的创建信息。
*/
public initialize (info: IRenderTextureCreateInfo) {
this._name = info.name || '';
@@ -81,7 +81,7 @@ export class RenderTexture extends TextureBase {
/**
* @en Reset the render texture. User may change the name, size or render pass info of the render texture.
* @zh 重新初始化渲染贴图。用户可以更改渲染贴图的名称、尺寸、渲染通道信息。
* @param info @en The create info of render texture @zh 渲染贴图的创建信息
* @param info @en The create info of render texture. @zh 渲染贴图的创建信息。
*/
public reset (info: IRenderTextureCreateInfo) { // to be consistent with other assets
this.initialize(info);
@@ -102,10 +102,10 @@ export class RenderTexture extends TextureBase {
}
/**
* @en Resize the render texture
* @zh 修改渲染贴图的尺寸
* @param width The pixel width, the range is from 1 to 2048
* @param height The pixel height, the range is from 1 to 2048
* @en Resize the render texture.
* @zh 修改渲染贴图的尺寸。
* @param width @en The pixel width to resize to, the range is from 1 to 2048. @zh 需要调整到的像素宽度,范围为 1-2048。
* @param height @en The pixel height to resize to, the range is from 1 to 2048. @zh 需要调整到的像素高度,范围为 1-2048。
*/
public resize (width: number, height: number) {
this._width = Math.floor(clamp(width, 1, 2048));
@@ -139,16 +139,17 @@ export class RenderTexture extends TextureBase {
// To be compatible with material property interface
/**
* @en Gets the related [[gfx.Texture]] resource, it's also the color attachment for the render window
* @zh 获取渲染贴图的 GFX 资源,同时也是渲染窗口所指向的颜色缓冲贴图资源
* @en Gets the related [[gfx.Texture]] resource, it's also the color attachment for the render window.
* @zh 获取渲染贴图的 GFX 资源,同时也是渲染窗口所指向的颜色缓冲贴图资源。
* @return @en The low level gfx texture. @zh 底层的 gfx 贴图。
*/
public getGFXTexture (): Texture | null {
return this._window && this._window.framebuffer.colorTextures[0];
}
/**
* @en Callback function after render texture is loaded in [[CCLoader]]. Initialize the render texture.
* @zh 通过 [[CCLoader]] 加载完成时的回调,初始化渲染贴图。
* @en Callback function after render texture is loaded in [[AssetManager]]. Initialize the render texture.
* @zh 通过 [[AssetManager]] 加载完成时的回调,初始化渲染贴图。
*/
public onLoaded () {
this._initWindow();
@@ -157,7 +158,8 @@ export class RenderTexture extends TextureBase {
/**
* @en Implementation of the render texture initialization.
* @zh 初始化渲染贴图的具体实现。
* @param info @en The create info of render texture @zh 渲染贴图的创建信息
* @param info @en The create info of render texture. @zh 渲染贴图的创建信息。
* @engineInternal
*/
protected _initWindow (info?: IRenderTextureCreateInfo) {
const root = cclegacy.director.root as Root;
@@ -182,8 +184,9 @@ export class RenderTexture extends TextureBase {
/**
* @en Initialize the render texture with uuid. The default size is 1x1.
* @zh 初始化渲染贴图。使用uuid进行初始化,贴图的尺寸为 1x1。
* @param uuid @en asset uuid @zh 资源 uuid
* @zh 初始化渲染贴图。使用 uuid 进行初始化,贴图的尺寸为 1x1。
* @param uuid @en asset uuid. @zh 资源 uuid。
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public initDefault (uuid?: string) {
super.initDefault(uuid);
@@ -194,20 +197,21 @@ export class RenderTexture extends TextureBase {
/**
* @en Validate the correctness of the render texture.
* @zh 验证渲染贴图的正确性。
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
*/
public validate () {
return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048;
}
/**
* @en Read pixel buffer from render texture @zh 从 render texture 读取像素数据
* @param x @en The location on x axis @zh 起始位置X轴坐标
* @param y @en The location on y axis @zh 起始位置Y轴坐标
* @param width @en The pixel width @zh 像素宽度
* @param height @en The pixel height @zh 像素高度
* @param buffer @en The buffer to hold pixel data @zh 像素缓存
* @en Read pixel buffer from render texture. @zh 从 render texture 读取像素数据。
* @param x @en The location on x axis. @zh 起始位置X轴坐标。
* @param y @en The location on y axis. @zh 起始位置Y轴坐标。
* @param width @en The pixel width. @zh 像素宽度。
* @param height @en The pixel height. @zh 像素高度。
* @param buffer @en The buffer to hold pixel data. @zh 像素缓存。
*/
public readPixels (x = 0, y = 0, width?: number, height?: number, buffer?: Uint8Array) : Uint8Array | null {
public readPixels (x = 0, y = 0, width?: number, height?: number, buffer?: Uint8Array): Uint8Array | null {
width = width || this.width;
height = height || this.height;
const gfxTexture = this.getGFXTexture();
+32 -32
View File
@@ -37,38 +37,38 @@ import { Mesh } from '../../3d/assets/mesh';
export type IBArray = Uint8Array | Uint16Array | Uint32Array;
/**
* @en The interface of geometric information
* @en The interface of geometric information.
* @zh 几何信息。
*/
export interface IGeometricInfo {
/**
* @en Vertex positions
* @en Vertex positions.
* @zh 顶点位置。
*/
positions: Float32Array;
/**
* @en Indices data
* @en Indices data.
* @zh 索引数据。
*/
indices?: IBArray;
/**
* @en Whether the geometry is treated as double sided
* @en Whether the geometry is treated as double sided.
* @zh 是否将图元按双面对待。
*/
doubleSided?: boolean;
/**
* @en The bounding box
* @en The bounding box.
* @zh 此几何体的轴对齐包围盒。
*/
boundingBox: { max: Vec3 | Readonly<Vec3>; min: Vec3 | Readonly<Vec3> };
}
/**
* @en Flat vertex buffer
* @zh 扁平化顶点缓冲区
* @en Flat vertex buffer.
* @zh 扁平化顶点缓冲区。
*/
export interface IFlatBuffer {
stride: number;
@@ -83,17 +83,17 @@ export interface IFlatBuffer {
export class RenderingSubMesh {
/**
* @en
* mesh object where this sub mesh locates
* mesh object where this sub mesh locates.
* @zh
* 子网格所处的网格模型对象
* 子网格所处的网格模型对象。
*/
public mesh?: Mesh;
/**
* @en
* sub mesh's index in mesh
* sub mesh's index in mesh.
* @zh
* 子网格在网格模型中的索引
* 子网格在网格模型中的索引。
*/
public subMeshIdx?: number;
@@ -125,14 +125,14 @@ export class RenderingSubMesh {
/**
* @en
* sub mesh's constructor
* sub mesh's constructor.
* @zh
* 子网格构造函数
* @param vertexBuffers @en vertex buffers @zh 顶点缓冲区数组
* @param attributes @en vertex attributes @zh 顶点属性数组
* @param primitiveMode @en primitive mode @zh 图元类型
* @param indexBuffer @en index buffer @zh 索引缓冲区
* @param indirectBuffer @en indirect buffer @zh 间接缓冲区
* 子网格构造函数。
* @param vertexBuffers @en vertex buffers. @zh 顶点缓冲区数组。
* @param attributes @en vertex attributes. @zh 顶点属性数组。
* @param primitiveMode @en primitive mode. @zh 图元类型。
* @param indexBuffer @en index buffer. @zh 索引缓冲区。
* @param indirectBuffer @en indirect buffer. @zh 间接缓冲区。
*/
constructor (
vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode,
@@ -149,31 +149,31 @@ export class RenderingSubMesh {
}
/**
* @en All vertex attributes used by the sub mesh
* @en All vertex attributes used by the sub mesh.
* @zh 所有顶点属性。
*/
get attributes () { return this._attributes; }
/**
* @en All vertex buffers used by the sub mesh
* @en All vertex buffers used by the sub mesh.
* @zh 使用的所有顶点缓冲区。
*/
get vertexBuffers () { return this._vertexBuffers; }
/**
* @en Index buffer used by the sub mesh
* @en Index buffer used by the sub mesh.
* @zh 使用的索引缓冲区,若未使用则无需指定。
*/
get indexBuffer () { return this._indexBuffer; }
/**
* @en Indirect buffer used by the sub mesh
* @en Indirect buffer used by the sub mesh.
* @zh 间接绘制缓冲区。
*/
get indirectBuffer () { return this._indirectBuffer; }
/**
* @en Primitive mode used by the sub mesh
* @en Primitive mode used by the sub mesh.
* @zh 图元类型。
*/
get primitiveMode () { return this._primitiveMode; }
@@ -234,8 +234,8 @@ export class RenderingSubMesh {
public invalidateGeometricInfo () { this._geometricInfo = undefined; }
/**
* @en the draw range
* @zh 渲染范围
* @en the draw range.
* @zh 渲染范围。
*/
set drawInfo (info: DrawInfo | null | undefined) {
this._drawInfo = info;
@@ -246,13 +246,13 @@ export class RenderingSubMesh {
}
/**
* @en Flatted vertex buffers
* @en Flatted vertex buffers.
* @zh 扁平化的顶点缓冲区。
*/
get flatBuffers () { return this._flatBuffers; }
/**
* @en generate flatted vertex buffers
* @en generate flatted vertex buffers.
* @zh 生成扁平化的顶点缓冲区。
*/
public genFlatBuffers () {
@@ -292,7 +292,7 @@ export class RenderingSubMesh {
}
/**
* @en The vertex buffer for joint after mapping
* @en The vertex buffer for joint after mapping.
* @zh 骨骼索引按映射表处理后的顶点缓冲。
*/
get jointMappedBuffers () {
@@ -344,14 +344,14 @@ export class RenderingSubMesh {
}
/**
* @en The input assembler info
* @zh 输入汇集器信息
* @en The input assembler info.
* @zh 输入汇集器信息。
*/
get iaInfo () { return this._iaInfo; }
/**
* @en destroy sub mesh
* @zh 销毁子网格
* @en Destroys sub mesh.
* @zh 销毁子网格。
*/
public destroy () {
for (let i = 0; i < this.vertexBuffers.length; i++) {
+55 -11
View File
@@ -59,27 +59,40 @@ function canGenerateMipmap (device: Device, w: number, h: number) {
*/
@ccclass('cc.SimpleTexture')
export class SimpleTexture extends TextureBase {
/**
* @engineInternal
*/
protected _gfxTexture: Texture | null = null;
/**
* @engineInternal
*/
protected _gfxTextureView: Texture | null = null;
private _mipmapLevel = 1;
// Cache these data to reduce JSB invoking.
private _textureWidth = 0;
private _textureHeight = 0;
/**
* @engineInternal
*/
protected _baseLevel = 0;
/**
* @engineInternal
*/
protected _maxLevel = 1000;
/**
* @en The mipmap level of the texture
* @zh 贴图中的 Mipmap 层级数量
* @en The mipmap level of the texture.
* @zh 贴图中的 Mipmap 层级数量。
*/
get mipmapLevel () {
return this._mipmapLevel;
}
/**
* @en The GFX Texture resource
* @en The GFX Texture resource.
* @zh 获取此贴图底层的 GFX 贴图对象。
* @return @en The low level gfx texture. @zh 底层的 GFX 贴图。
*/
public getGFXTexture () {
return this._gfxTextureView;
@@ -103,8 +116,8 @@ export class SimpleTexture extends TextureBase {
* @en Update the given level mipmap image.
* @zh 更新指定层级范围内的 Mipmap。当 Mipmap 数据发生了改变时应调用此方法提交更改。
* 若指定的层级范围超出了实际已有的层级范围,只有覆盖的那些层级范围会被更新。
* @param firstLevel First level to be updated
* @param count Mipmap level count to be updated
* @param firstLevel @en First level to be updated. @zh 更新指定层的 mipmap。
* @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。
*/
public updateMipmaps (firstLevel = 0, count?: number) {
@@ -123,9 +136,9 @@ export class SimpleTexture extends TextureBase {
* - 若图像的尺寸与 Mipmap 的尺寸相同,上传后整个 Mipmap 的数据将与图像数据一致;
* - 若图像的尺寸小于指定层级 Mipmap 的尺寸(不管是长或宽),则从贴图左上角开始,图像尺寸范围内的 Mipmap 会被更新;
* - 若图像的尺寸超出了指定层级 Mipmap 的尺寸(不管是长或宽),都将引起错误。
* @param source The source image or image data
* @param level Mipmap level to upload the image to
* @param arrayIndex The array index
* @param source @en The source image or image data. @zh 源图像或图像数据。
* @param level @en Mipmap level to upload the image to. @zh 要上传的 mipmap 层级。
* @param arrayIndex @en The array index. @zh 要上传的数组索引。
*/
public uploadData (source: HTMLCanvasElement | HTMLImageElement | ArrayBufferView | ImageBitmap, level = 0, arrayIndex = 0) {
if (!this._gfxTexture || this._mipmapLevel <= level) {
@@ -159,6 +172,9 @@ export class SimpleTexture extends TextureBase {
}
}
/**
* @engineInternal
*/
protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) {
const data = image.data;
if (!data) {
@@ -177,10 +193,16 @@ export class SimpleTexture extends TextureBase {
}
}
/**
* @engineInternal
*/
protected _checkTextureLoaded () {
this._textureReady();
}
/**
* @engineInternal
*/
protected _textureReady () {
this.loaded = true;
this.emit('load');
@@ -193,11 +215,16 @@ export class SimpleTexture extends TextureBase {
* @zh
* 设置此贴图的 mipmap 层级
* @param value The mipmap level.
* @engineInternal
*
*/
protected _setMipmapLevel (value: number) {
this._mipmapLevel = value < 1 ? 1 : value;
}
/**
* @engineInternal
*/
protected _setMipRange (baseLevel: number, maxLevel: number) {
this._baseLevel = baseLevel < 1 ? 0 : baseLevel;
this._maxLevel = maxLevel < 1 ? 0 : maxLevel;
@@ -206,8 +233,8 @@ export class SimpleTexture extends TextureBase {
/**
* @en Set mipmap level range for this texture.
* @zh 设置当前贴图的 mipmap 范围。
* @param baseLevel The base mipmap level.
* @param maxLevel The maximum mipmap level.
* @param baseLevel @en The base mipmap level. @zh 最低 mipmap 等级。
* @param maxLevel @en The maximum mipmap level. @zh 最高 mipmap 等级。
*/
public setMipRange (baseLevel: number, maxLevel: number) {
assertID(baseLevel <= maxLevel, 3124);
@@ -229,6 +256,7 @@ export class SimpleTexture extends TextureBase {
* @en This method is override by derived classes to provide GFX texture info.
* @zh 这个方法被派生类重写以提供 GFX 纹理信息。
* @param presumed The presumed GFX texture info.
* @engineInternal
*/
protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo): TextureInfo | null {
return null;
@@ -238,11 +266,15 @@ export class SimpleTexture extends TextureBase {
* @en This method is overrided by derived classes to provide GFX TextureViewInfo.
* @zh 这个方法被派生类重写以提供 GFX 纹理视图信息。
* @param presumed The presumed GFX TextureViewInfo.
* @engineInternal
*/
protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo): TextureViewInfo | null {
return null;
}
/**
* @engineInternal
*/
protected _tryReset () {
this._tryDestroyTextureView();
this._tryDestroyTexture();
@@ -259,12 +291,15 @@ export class SimpleTexture extends TextureBase {
/**
* @en Whether mipmaps are baked convolutional maps.
* @zh mipmaps是否为烘焙出来的卷积图。
* @zh mipmaps 是否为烘焙出来的卷积图。
*/
public isUsingOfflineMipmaps (): boolean {
return false;
}
/**
* @engineInternal
*/
protected _createTexture (device: Device) {
if (this._width === 0 || this._height === 0) { return; }
let flags = TextureFlagBit.NONE;
@@ -291,6 +326,9 @@ export class SimpleTexture extends TextureBase {
this._gfxTexture = texture;
}
/**
* @engineInternal
*/
protected _createTextureView (device: Device): Texture | null {
if (!this._gfxTexture) {
return null;
@@ -309,6 +347,9 @@ export class SimpleTexture extends TextureBase {
return device.createTexture(textureViewCreateInfo);
}
/**
* @engineInternal
*/
protected _tryDestroyTexture () {
if (this._gfxTexture) {
this._gfxTexture.destroy();
@@ -316,6 +357,9 @@ export class SimpleTexture extends TextureBase {
}
}
/**
* @engineInternal
*/
protected _tryDestroyTextureView () {
if (this._gfxTextureView) {
this._gfxTextureView.destroy();
+1 -1
View File
@@ -28,7 +28,7 @@ import { Asset } from './asset';
import { cclegacy } from '../../core';
/**
* @en Class for text file.
* @en The asset for text file.
* @zh 文本资源。
*/
@ccclass('cc.TextAsset')
+21 -12
View File
@@ -34,45 +34,45 @@ import { js, cclegacy } from '../../core';
const compressedImageAsset: ImageAsset[] = [];
/**
* @en The create information for [[Texture2D]]
* @en The create information for [[Texture2D]].
* @zh 用来创建贴图的信息。
*/
export interface ITexture2DCreateInfo {
/**
* @en The pixel width
* @en The pixel width.
* @zh 像素宽度。
*/
width: number;
/**
* @en The pixel height
* @en The pixel height.
* @zh 像素高度。
*/
height: number;
/**
* @en The pixel format
* @en The pixel format.
* @zh 像素格式。
* @default PixelFormat.RGBA8888
*/
format?: PixelFormat;
/**
* @en The mipmap level count
* @en The mipmap level count.
* @zh mipmap 层级。
* @default 1
*/
mipmapLevel?: number;
/**
* @en The selected base mipmap level
* @en The selected base mipmap level.
* @zh 选择使用的最小 mipmap 层级。
* @default 1
*/
baseLevel?: number;
/**
* @en The selected maximum mipmap level
* @en The selected maximum mipmap level.
* @zh 选择使用的最大 mipmap 层级。
* @default 1000
*/
@@ -177,6 +177,9 @@ export class Texture2D extends SimpleTexture {
@type([ImageAsset])
public _mipmaps: ImageAsset[] = [];
/**
* @engineInternal
*/
public initialize () {
this.mipmaps = this._mipmaps;
}
@@ -190,7 +193,7 @@ export class Texture2D extends SimpleTexture {
* After reset, the gfx resource will become invalid, you must use [[uploadData]] explicitly to upload the new mipmaps to GPU resources.
* @zh 将当前贴图重置为指定尺寸、像素格式以及指定 mipmap 层级。重置后,贴图的像素数据将变为未定义。
* mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。
* @param info The create information
* @param info @en The create information. @zh 创建贴图的相关信息。
*/
public reset (info: ITexture2DCreateInfo) {
this._width = info.width;
@@ -251,7 +254,7 @@ export class Texture2D extends SimpleTexture {
/**
* @en If the level 0 mipmap image is a HTML element, then return it, otherwise return null.
* @zh 若此贴图 0 级 Mipmap 的图像资源的实际源存在并为 HTML 元素则返回它,否则返回 `null`。
* @returns HTML element or `null`
* @returns @en HTMLElement or `null`. @zh HTML 元素或者 null。
* @deprecated Please use [[ImageAsset.data]] instead
*/
public getHtmlElementObj () {
@@ -268,9 +271,9 @@ export class Texture2D extends SimpleTexture {
}
/**
* @en Gets the description of the 2d texture
* @en Gets the description of the 2d texture.
* @zh 返回此贴图的描述。
* @returns The description
* @returns @en The description. @zh 贴图的描述信息。
*/
public description () {
const url = this._mipmaps[0] ? this._mipmaps[0].url : '';
@@ -280,7 +283,7 @@ export class Texture2D extends SimpleTexture {
/**
* @en Release used GPU resources.
* @zh 释放占用的 GPU 资源。
* @deprecated please use [[destroy]] instead
* @deprecated please use [[destroy]] instead.
*/
public releaseTexture () {
this.destroy();
@@ -327,6 +330,9 @@ export class Texture2D extends SimpleTexture {
}
}
/**
* @engineInternal
*/
protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo) {
const texInfo = new TextureInfo(TextureType.TEX2D);
texInfo.width = this._width;
@@ -335,6 +341,9 @@ export class Texture2D extends SimpleTexture {
return texInfo;
}
/**
* @engineInternal
*/
protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo) {
const texViewInfo = new TextureViewInfo();
texViewInfo.type = TextureType.TEX2D;
+53 -23
View File
@@ -50,7 +50,7 @@ export class TextureBase extends Asset {
}
/**
* @en Pixel width of the texture
* @en Pixel width of the texture.
* @zh 此贴图的像素宽度。
*/
public get width (): number {
@@ -58,7 +58,7 @@ export class TextureBase extends Asset {
}
/**
* @en Pixel height of the texture
* @en Pixel height of the texture.
* @zh 此贴图的像素高度。
*/
public get height (): number {
@@ -67,47 +67,77 @@ export class TextureBase extends Asset {
/**
* @en The pixel format enum.
* @zh 像素格式枚举类型
* @zh 像素格式枚举类型。
*/
public static PixelFormat = PixelFormat;
/**
* @en The wrap mode enum.
* @zh 环绕模式枚举类型
* @zh 环绕模式枚举类型。
*/
public static WrapMode = WrapMode;
/**
* @en The texture filter mode enum
* @zh 纹理过滤模式枚举类型
* @en The texture filter mode enum.
* @zh 纹理过滤模式枚举类型。
*/
public static Filter = Filter;
/**
* @engineInternal
*/
@serializable
protected _format = PixelFormat.RGBA8888;
/**
* @engineInternal
*/
@serializable
protected _minFilter = Filter.LINEAR;
/**
* @engineInternal
*/
@serializable
protected _magFilter = Filter.LINEAR;
/**
* @engineInternal
*/
@serializable
protected _mipFilter = Filter.NONE;
/**
* @engineInternal
*/
@serializable
protected _wrapS = WrapMode.REPEAT;
/**
* @engineInternal
*/
@serializable
protected _wrapT = WrapMode.REPEAT;
/**
* @engineInternal
*/
@serializable
protected _wrapR = WrapMode.REPEAT;
/**
* @engineInternal
*/
@serializable
protected _anisotropy = 0;
/**
* @engineInternal
*/
protected _width = 1;
/**
* @engineInternal
*/
protected _height = 1;
private _id: string;
@@ -127,27 +157,27 @@ export class TextureBase extends Asset {
}
/**
* @en Gets the id of the texture
* @en Gets the id of the texture.
* @zh 获取标识符。
* @returns The id
* @returns @en The id of this texture. @zh 此贴图的 id。
*/
public getId () {
return this._id;
}
/**
* @en Gets the pixel format
* @en Gets the pixel format.
* @zh 获取像素格式。
* @returns The pixel format
* @returns @en The pixel format. @zh 像素格式。
*/
public getPixelFormat () {
return this._format;
}
/**
* @en Gets the anisotropy
* @en Gets the anisotropy.
* @zh 获取各向异性。
* @returns The anisotropy
* @returns @en The anisotropy. @zh 各项异性值。
*/
public getAnisotropy () {
return this._anisotropy;
@@ -158,9 +188,9 @@ export class TextureBase extends Asset {
* Be noted, if the size of the texture is not power of two, only [[WrapMode.CLAMP_TO_EDGE]] is allowed.
* @zh 设置此贴图的缠绕模式。
* 注意,若贴图尺寸不是 2 的整数幂,缠绕模式仅允许 [[WrapMode.CLAMP_TO_EDGE]]。
* @param wrapS S(U) coordinate wrap mode
* @param wrapT T(V) coordinate wrap mode
* @param wrapR R(W) coordinate wrap mode
* @param wrapS @en S(U) coordinate wrap mode. @zh S(U) 坐标系缠绕模式.
* @param wrapT @en T(V) coordinate wrap mode. @zh T(V) 坐标系缠绕模式.
* @param wrapR @en R(W) coordinate wrap mode. @zh R(W) 坐标系缠绕模式.
*/
public setWrapMode (wrapS: WrapMode, wrapT: WrapMode, wrapR?: WrapMode) {
if (wrapR === undefined) wrapR = wrapS; // wrap modes should be as consistent as possible for performance
@@ -178,10 +208,10 @@ export class TextureBase extends Asset {
}
/**
* @en Sets the texture's filter mode
* @en Sets the texture's filter mode.
* @zh 设置此贴图的过滤算法。
* @param minFilter Filter mode for scale down
* @param magFilter Filter mode for scale up
* @param minFilter @en Filter mode for scale down. @zh 贴图缩小时使用的过滤模式。
* @param magFilter @en Filter mode for scale up. @zh 贴图放大时使用的过滤模式。
*/
public setFilters (minFilter: Filter, magFilter: Filter) {
this._minFilter = minFilter;
@@ -195,9 +225,9 @@ export class TextureBase extends Asset {
}
/**
* @en Sets the texture's mip filter
* @zh 设置此贴图的缩小过滤算法。
* @param mipFilter Filter mode for scale down
* @en Sets the texture's mip filter mode.
* @zh 设置此贴图的多层 mip 过滤算法。
* @param mipFilter @en Filter mode for multiple mip level. @zh 多层 mip 过滤模式。
*/
public setMipFilter (mipFilter: Filter) {
this._mipFilter = mipFilter;
@@ -209,9 +239,9 @@ export class TextureBase extends Asset {
}
/**
* @en Sets the texture's anisotropy
* @en Sets the texture's anisotropy.
* @zh 设置此贴图的各向异性。
* @param anisotropy
* @param anisotropy @en The anisotropy to be set. @zh 待设置的各向异性数值。
*/
public setAnisotropy (anisotropy: number) {
this._anisotropy = anisotropy;
+15 -7
View File
@@ -22,7 +22,7 @@
THE SOFTWARE.
*/
import { EDITOR, TEST, WECHAT } from 'internal:constants';
import { EDITOR, TEST, VIVO, WECHAT } from 'internal:constants';
import { ccclass, serializable } from 'cc.decorator';
import { TextureType, TextureInfo, TextureViewInfo, BufferTextureCopy } from '../../gfx';
import { ImageAsset } from './image-asset';
@@ -168,10 +168,11 @@ export class TextureCube extends SimpleTexture {
}
/**
* @en Fill mipmaps with convolutional maps.
* @zh 使用卷积图填充mipmaps。
* @param value All mipmaps of each face of the cube map are stored in the form of atlas
* @en Fill mipmaps for cube map with atlas.
* @zh 使用 atlas 方式排布的图填充到立方体贴图的 mipmaps。
* @param value @en All mipmaps of each face of the cube map are stored in the form of atlas
* and the value contains the atlas of the 6 faces and the layout information of each mipmap layer.
* @zh 立方体贴图六个面的图,其中每张图中的全部 mip 数据都使用 atlas 方式排布
*/
set mipmapAtlas (value: ITextureCubeMipmapAtlas | null) {
this._mipmapAtlas = value;
@@ -189,7 +190,7 @@ export class TextureCube extends SimpleTexture {
}
//In ios wechat mini-game platform drawImage and getImageData can not get correct data,so upload to gfxTexture than use readPixels to get data
//The performance of upload to gfxTexture and readPixels is not good, so only use this way in the ios wechat mini-game platform
if (WECHAT && sys.os === OS.IOS) {
if ((WECHAT && sys.os === OS.IOS) || VIVO) {
this._uploadAtlas();
return;
}
@@ -315,7 +316,7 @@ export class TextureCube extends SimpleTexture {
* After reset, the gfx resource will become invalid, you must use [[uploadData]] explicitly to upload the new mipmaps to GPU resources.
* @zh 将当前贴图重置为指定尺寸、像素格式以及指定 mipmap 层级。重置后,贴图的像素数据将变为未定义。
* mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。
* @param info The create information
* @param info @en The create information. @zh 创建贴图的相关信息。
*/
public reset (info: ITextureCubeCreateInfo) {
this._width = info.width;
@@ -329,6 +330,13 @@ export class TextureCube extends SimpleTexture {
this._tryReset();
}
/**
* @en Updates the given level mipmap image.
* @zh 更新指定层级范围内的 Mipmap。当 Mipmap 数据发生了改变时应调用此方法提交更改。
* 若指定的层级范围超出了实际已有的层级范围,只有覆盖的那些层级范围会被更新。
* @param firstLevel @en First level to be updated. @zh 更新指定层的 mipmap。
* @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。
*/
public updateMipmaps (firstLevel = 0, count?: number) {
if (firstLevel >= this._mipmaps.length) {
return;
@@ -348,7 +356,7 @@ export class TextureCube extends SimpleTexture {
}
/**
* @en Destroy this texture, clear all mipmaps and release GPU resources
* @en Destroys this texture, clear all mipmaps and release GPU resources
* @zh 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。
*/
public destroy () {
+3 -4
View File
@@ -25,11 +25,10 @@
import { AudioPlayer } from 'pal/audio';
import { AudioClip, AudioMeta } from './audio-clip';
import { CompleteCallback, IDownloadParseOptions } from '../asset/asset-manager/shared';
import downloader from '../asset/asset-manager/downloader';
import factory from '../asset/asset-manager/factory';
export function loadAudioPlayer (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) {
export function loadAudioPlayer (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)) {
AudioPlayer.load(url, {
audioLoadMode: options.audioLoadMode,
}).then((player) => {
@@ -47,8 +46,8 @@ export function loadAudioPlayer (url: string, options: IDownloadParseOptions, on
function createAudioClip (id: string,
data: AudioMeta,
options: IDownloadParseOptions,
onComplete: CompleteCallback<AudioClip>) {
options: Record<string, any>,
onComplete: ((err: Error | null, data?: AudioClip | null) => void)) {
const out = new AudioClip();
out._nativeUrl = id;
out._nativeAsset = data;
+7 -7
View File
@@ -26,12 +26,12 @@ import { IExposedAttributes } from './utils/attribute-defines';
/**
* Class slash stores information collected from decorators.
* Once class decorator entered, class definition begins. It process the stash and remove it.
* Once the class decorator entered, the class definition begins. It processes the stash and removes it.
*/
export interface ClassStash {
/**
* When extract default values under TypeScript environment,
* we have to construct an object of current class and get its member values.
* When extracting default values under the TypeScript environment,
* We have to construct an object of the current class and get its member values.
* This field stores the create-once object.
*/
default?: unknown;
@@ -48,7 +48,7 @@ export interface ClassStash {
/**
* The error properties.
* We record them here to ensure only once error report is given to each property.
* We record them here to ensure only once an error report is given to each property.
*/
errorProps?: Record<PropertyKey, true>;
}
@@ -85,17 +85,17 @@ export enum PropertyStashInternalFlag {
* Indicates this property is reflected using "standalone property decorators" such as
* `@editable`, `@visible`, `serializable`.
* All standalone property decorators would set this flag;
* non standalone property decorators won't set this flag.
* non-standalone property decorators won't set this flag.
*/
STANDALONE = 1 << 0,
/**
* Indicates this property is visible, if no other explicit visibility decorators(`@visible`s) attached.
* Indicates this property is visible, if no other explicit visibility decorators(`@visible`s) are attached.
*/
IMPLICIT_VISIBLE = 1 << 1,
/**
* Indicates this property is serializable, if no other explicit visibility decorators(`@serializable`s) attached.
* Indicates this property is serializable, if no other explicit visibility decorators(`@serializable`s) are attached.
*/
IMPLICIT_SERIALIZABLE = 1 << 2,
}
+8 -6
View File
@@ -56,7 +56,7 @@ function pushUnique (array, item) {
}
}
// both getter and prop must register the name into __props__ array
// both getter and prop must register the name into `__props__` array
function appendProp (cls, name) {
if (DEV) {
// if (!IDENTIFIER_RE.test(name)) {
@@ -197,10 +197,10 @@ function define (className, baseClass, options) {
window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
}
// Note: `options.ctor` should be same as `cls` except if
// Note: `options.ctor` should be the same as `cls` except if
// cc-class is defined by `cc.Class({/* ... */})`.
// In such case, `options.ctor` may be `undefined`.
// So we can not use `options.ctor`. Instead we should use `cls` which is the "real" registered cc-class.
// So we can not use `options.ctor`. Instead, we should use `cls` which is the "real" registered cc-class.
EditorExtends.emit('class-registered', cls, frame, className);
}
@@ -243,7 +243,7 @@ function getNewValueTypeCodeJit (value) {
// TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCodeJit to misc.js or a new source file
// convert a normal string including newlines, quotes and unicode characters into a string literal
// convert a normal string including newlines, quotes and Unicode characters into a string literal
// ready to use in JavaScript source
function escapeForJS (s) {
return JSON.stringify(s)
@@ -358,7 +358,7 @@ CCClass.Attr = attributeUtils;
CCClass.attr = attributeUtils.attr;
/**
* Returns if the class is a cc-class or is fast defined.
* Returns if the class is a cc-class or is fast-defined.
* @param constructor The constructor of the class.
* @returns Judge result.
* @engineInternal
@@ -478,7 +478,9 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas
if ('default' in attributes) {
(attrs || initAttrs())[`${propertyNamePrefix}default`] = attributes.default;
} else if (((EDITOR && !window.Build) || TEST) && warnOnNoDefault && !(attributes.get || attributes.set)) {
warnID(3654, className, propertyName);
// TODO: we close this warning for now:
// issue: https://github.com/cocos/3d-tasks/issues/14887
// warnID(3654, className, propertyName);
}
const parseSimpleAttribute = (attributeName: keyof IAcceptableAttributes, expectType: string) => {
+4 -6
View File
@@ -38,7 +38,7 @@ export const deserializeTag = Symbol('[[Deserialize]]');
export interface SerializationInput {
/**
* Reads a property from input.
* Reads a property from the input.
* @param name Property name.
* @returns The property's value, after deserialized.
*/
@@ -76,19 +76,17 @@ export interface SerializationOutput {
export type SerializationContext = {
/**
* The main serializing asset or root node in the scene/prefab passed to serialization procedure.
* The main serializing asset or root node in the scene/prefab passed to the serialization procedure.
*/
root: unknown;
/**
* True if the serialization procedure is targeting CCON.
*/
toCCON: boolean;
/**
* Customized arguments passed to serialization procedure.
*/
customArguments: Record<PropertyKey, unknown>
customArguments: Record<PropertyKey, unknown>;
};
/**
@@ -108,7 +106,7 @@ export interface CustomSerializable {
}
/**
* Enables the custom serialize/deserialize method only if the (de)serialize procedure is targeting CCON.
* Enables the custom to serialize/deserialize method only if the (de)serialize procedure is targeting CCON.
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
*/
export const enableIfCCON: MethodDecorator = <T>(
+5 -5
View File
@@ -28,7 +28,7 @@ import { makeEditorClassDecoratorFn, makeSmartEditorClassDecorator, emptySmartCl
/**
* @en Declare that the current component relies on another type of component.
* If the required component doesn't exist, the engine will create a new empty instance of the required component and add to the node.
* If the required component doesn't exist, the engine will create a new empty instance of the required component and add it to the node.
* @zh 为声明为 CCClass 的组件添加依赖的其它组件。当组件添加到节点上时,如果依赖的组件不存在,引擎将会自动将依赖组件添加到同一个节点,防止脚本出错。该设置在运行时同样有效。
* @param requiredComponent The required component type
* @example
@@ -46,10 +46,10 @@ import { makeEditorClassDecoratorFn, makeSmartEditorClassDecorator, emptySmartCl
export const requireComponent: (requiredComponent: Function | Function[]) => ClassDecorator = makeEditorClassDecoratorFn('requireComponent');
/**
* @en Set the component priority, it decides at which order the life cycle functions of components will be invoked. Smaller priority get invoked before larger priority.
* @en Set the component priority, it decides at which order the life cycle functions of components will be invoked. Smaller priority gets invoked before larger priority.
* This will affect `onLoad`, `onEnable`, `start`, `update` and `lateUpdate`, but `onDisable` and `onDestroy` won't be affected.
* @zh 设置脚本生命周期方法调用的优先级。优先级小于 0 的组件将会优先执行,优先级大于 0 的组件将会延后执行。优先级仅会影响 onLoad, onEnable, start, update 和 lateUpdate,而 onDisable 和 onDestroy 不受影响。
* @param priority - The execution order of life cycle methods for Component. Smaller priority get invoked before larger priority.
* @param priority - The execution order of life cycle methods for Component. Smaller priority gets invoked before larger priority.
* @example
* ```ts
* import { _decorator, Component } from 'cc';
@@ -65,7 +65,7 @@ export const requireComponent: (requiredComponent: Function | Function[]) => Cla
export const executionOrder: (priority: number) => ClassDecorator = makeEditorClassDecoratorFn('executionOrder');
/**
* @en Forbid add multiple instances of the component to the same node.
* @en Forbid adds multiple instances of the component to the same node.
* @zh 防止多个相同类型(或子类型)的组件被添加到同一个节点。
* @example
* ```ts
@@ -83,4 +83,4 @@ export const disallowMultiple: ClassDecorator & ((yes?: boolean) => ClassDecorat
export const allowReplicated: ClassDecorator = (ctor) => {
CCClass.Attr.setClassAttr(ctor, 'replicated', 'visible', true);
}
};
+18 -18
View File
@@ -30,7 +30,7 @@ import { PropertyStash, PropertyStashInternalFlag } from '../class-stash';
import { LegacyPropertyDecorator, emptyDecorator, makeSmartEditorClassDecorator, makeEditorClassDecoratorFn, emptySmartClassDecorator, emptyDecoratorFn } from './utils';
/**
* @en Makes a CCClass that inherit from component execute in edit mode.<br/>
* @en Makes a CCClass that inherits from component execute in edit mode.<br/>
* By default, all components are only executed in play mode,<br/>
* which means they will not have their callback functions executed while the Editor is in edit mode.<br/>
* @zh 允许继承自 Component 的 CCClass 在编辑器里执行。<br/>
@@ -52,7 +52,7 @@ export const executeInEditMode: ClassDecorator & ((yes?: boolean) => ClassDecora
/**
* @en Add the current component to the specific menu path in `Add Component` selector of the inspector panel
* @zh 将当前组件添加到组件菜单中,方便用户查找。例如 "Rendering/CameraCtrl"。
* @param path - The path is the menu represented like a pathname. For example the menu could be "Rendering/CameraCtrl".
* @param path - The path is the menu represented like a pathname. For example, the menu could be "Rendering/CameraCtrl".
* @example
* ```ts
* import { _decorator, Component } from 'cc';
@@ -69,7 +69,7 @@ export const menu: (path: string) => ClassDecorator = DEV ? makeEditorClassDe
/**
* @en When [[_decorator.executeInEditMode]] is set,
* this decorator will make the editor running in high FPS mode when a node with the component is focused
* This decorator will make the editor run in high FPS mode when a node with the component is focused
* @zh 当指定了 [[_decorator.executeInEditMode]] 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。
* @example
* ```ts
@@ -89,7 +89,7 @@ export const playOnFocus: ClassDecorator & ((yes?: boolean) => ClassDecorator) =
/**
* @en Use a customized inspector page in the **inspector**
* @zh 自定义当前组件在 **属性检查器** 中渲染时所用的 UI 页面描述。
* @param url The url of the page definition in js
* @param url The URL of the page definition in js
* @example
* ```ts
* import { _decorator, Component } from 'cc';
@@ -124,10 +124,10 @@ export const inspector: (url: string) => ClassDecorator = DEV ? makeEditorCla
export const icon: (url: string) => ClassDecorator = DEV ? makeEditorClassDecoratorFn('icon') : emptyDecoratorFn;
/**
* @en Define the help documentation url,
* if given, the component section in the **Inspector** will have a help documentation icon reference to the web page given.
* @en Define the help documentation URL,
* if given, the component section in the **Inspector** will have a help documentation icon refers to the web page given.
* @zh 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。
* @param url The url of the help documentation
* @param url The URL of the help documentation
* @example
* ```ts
* import { _decorator, Component } from 'cc';
@@ -170,7 +170,7 @@ export const visible: (condition: boolean | (() => boolean)) => LegacyPropertyDe
/**
* @en
* Sets the property to be read only in editor.
* Sets the property to be read-only in the editor.
* @zh
* 设置该属性在编辑器中仅是可读的。
*/
@@ -180,7 +180,7 @@ export const readOnly: LegacyPropertyDecorator = !DEV
/**
* @en
* Sets the display name of the property in editor.
* Sets the display name of the property in the editor.
* @zh
* 设置该属性在编辑器中的显示名称。
* @param text 显示名称。
@@ -215,7 +215,7 @@ export const group: (options: NonNullable<IExposedAttributes['group']>) => Legac
/**
* @en
* Sets the allowed range of the property in editor.
* Sets the allowed range of the property in the editor.
* @zh
* 设置该属性在编辑器中允许设置的范围。
* @param values 范围。
@@ -227,7 +227,7 @@ export const range: (values: [number, number, number] | [number, number]) => Leg
/**
* @en
* Sets the allowed min value of the property in editor.
* Sets the allowed min value of the property in the editor.
* @zh
* 设置该属性在编辑器中允许的最小值。
* @param value 最小值。
@@ -238,7 +238,7 @@ export const rangeMin: (value: number) => LegacyPropertyDecorator = !DEV
/**
* @en
* Sets the allowed max value of the property in editor.
* Sets the allowed max value of the property in the editor.
* @zh
* 设置该属性在编辑器中允许的最大值。
* @param value 最大值。
@@ -249,7 +249,7 @@ export const rangeMax: (value: number) => LegacyPropertyDecorator = !DEV
/**
* @en
* Sets the step of the property in editor.
* Sets the step of the property in the editor.
* @zh
* 设置该属性在编辑器中的步进值。
* @param value 步进值。
@@ -261,7 +261,7 @@ export const rangeStep: (value: number) => LegacyPropertyDecorator = !DEV
/**
* @en
* Enable a slider be given to coordinate the property in editor.
* Enable a slider to be given to coordinate the property in the editor.
* @zh
* 允许在编辑器中提供滑动条来调节值
* @engineInternal
@@ -272,7 +272,7 @@ export const slide: LegacyPropertyDecorator = !DEV
/**
* @en
* Sets the display order of the property in editor.
* Sets the display order of the property in the editor.
* @zh
* 设置该属性在编辑器中的显示顺序。
* @param order 显示顺序。
@@ -284,7 +284,7 @@ export const displayOrder: (order: number) => LegacyPropertyDecorator = !DEV
/**
* @en
* Sets the unit of the property in editor.
* Sets the unit of the property in the editor.
* @zh
* 设置该属性在编辑器中的计量单位。
* @param name 计量单位的名称。
@@ -299,7 +299,7 @@ export const unit: (name:
/**
* @en
* Sets to convert the value into radian before feed it to the property in editor.
* Sets to convert the value into radian before feeding it to the property in the editor.
* @zh
* 设置在编辑器中赋值该属性前将值先转换为弧度制。
*/
@@ -319,7 +319,7 @@ export const multiline: LegacyPropertyDecorator = !DEV
/**
* @en
* Sets the property so that it does not interop with the animation parts in editor.
* Sets the property so that it does not interop with the animation parts in the editor.
* @zh
* 设置该属性不参与编辑器中动画相关的交互。
* @engineInternal
+10 -5
View File
@@ -120,7 +120,7 @@ function getDefaultFromInitializer (initializer: Initializer) {
// string boolean number function undefined null
return value;
} else {
// The default attribute will not be used in ES6 constructor actually,
// The default attribute will not be used in the ES6 constructor actually,
// so we don't need to simplify into `{}` or `[]` or vec2 completely.
return initializer;
}
@@ -246,19 +246,24 @@ function setDefaultValue<T> (
propertyStash: PropertyStash,
classConstructor: new () => T,
propertyKey: PropertyKey,
descriptorOrInitializer: BabelPropertyDecoratorDescriptor | Initializer | undefined,
descriptorOrInitializer: BabelPropertyDecoratorDescriptor | Initializer | undefined | null,
) {
if (descriptorOrInitializer) {
if (descriptorOrInitializer !== undefined) {
if (typeof descriptorOrInitializer === 'function') {
propertyStash.default = getDefaultFromInitializer(descriptorOrInitializer);
} else if (descriptorOrInitializer === null) {
// For some decorated properties we haven't specified the default value, then the initializer should be null.
// We fall back to the behavior of v3.6.3, where we don't specify the default value automatically.
// propertyStash.default = undefined;
} else if (descriptorOrInitializer.initializer) {
// In case of Babel, if an initializer is given for class field.
// In the case of Babel, if an initializer is given for a class field.
// That initializer is passed to `descriptor.initializer`.
propertyStash.default = getDefaultFromInitializer(descriptorOrInitializer.initializer);
}
} else {
// In case of TypeScript, we can not directly capture the initializer.
// In the case of TypeScript, we can not directly capture the initializer.
// We have to be hacking to extract the value.
// We should fall back to the TypeScript case only when `descriptorOrInitializer` is undefined.
const actualDefaultValues = classStash.default || (classStash.default = extractActualDefaultValues(classConstructor));
// eslint-disable-next-line no-prototype-builtins
if ((actualDefaultValues as any).hasOwnProperty(propertyKey)) {
+3 -3
View File
@@ -29,7 +29,7 @@ import { PropertyStash, PropertyStashInternalFlag } from '../class-stash';
import { getOrCreateSerializationMetadata } from '../serialization-metadata';
/**
* True if serialization feature is enabled in current environment.
* True if the serialization feature is enabled in the current environment.
* @engineInternal
*/
const WITH_SERIALIZATION = EDITOR || TEST;
@@ -72,9 +72,9 @@ function setImplicitSerializable (propertyStash: PropertyStash) {
/**
* @en
* Marks the target class as "uniquely referenced" which means, in the aspect of serialization,
* no more than one objects should reference to same instance of that class.
* no more than one object should reference the same instance of that class.
* When serializing references to objects of such class,
* they're treated as different object even they point to actually the same.
* they're treated as different objects even if they point to actually the same.
* While deserializing, these two references would point two distinct objects.
* For example:
* ```ts
+9 -7
View File
@@ -33,14 +33,16 @@ export type BabelPropertyDecoratorDescriptor = PropertyDescriptor & { initialize
/**
* @en
* The signature compatible with both TypeScript legacy decorator and Babel legacy decorator.
* The third argument is `descriptor` in Babel case.
* For some engine internal optimized deocorators, the third argument is initializer.
* The signature is compatible with both the TypeScript legacy decorator and the Babel legacy decorator.
* The third argument is `descriptor` in the Babel case.
* For some engine internally optimized decorators, the third argument is the initializer.
* @zh
* 该签名同时兼容 TypeScript legacy 装饰器以及 Babel legacy 装饰器。
* 第三个参数在 Babel 情况下,会传入 descriptor。对于一些被优化的引擎内部装饰器,会传入 initializer。
*/
export type LegacyPropertyDecorator = (target: Record<string, any>, propertyKey: string | symbol, descriptorOrInitializer?: BabelPropertyDecoratorDescriptor | Initializer) => void;
export type LegacyPropertyDecorator = (
target: Record<string, any>, propertyKey: string | symbol, descriptorOrInitializer?: BabelPropertyDecoratorDescriptor | Initializer | null,
) => void;
/**
* @en
@@ -52,7 +54,7 @@ export const emptyDecorator: ClassDecorator & LegacyPropertyDecorator = () => {}
/**
* @en
* A function which ignore all arguments and return the `emptyDecorator`.
* A function that ignores all arguments and returns the `emptyDecorator`.
* @zh
* 一个忽略所有参数并且返回 `emptyDecorator` 的函数。
*/
@@ -73,7 +75,7 @@ export const emptySmartClassDecorator = makeSmartClassDecorator(() => {});
* - `@x`
* - `@x(arg0)`
*
* and forward both the decorated class and the `arg0` (in first form, `arg0` is forward as `undefined`) to
* and forward both the decorated class and the `arg0` (in the first form, `arg0` is forwarded as `undefined`) to
* `decorate`.
* @zh
* 创建一个智能类装饰器,它能正确地处理以下形式的装饰器语法:
@@ -111,7 +113,7 @@ function writeEditorClassProperty<TValue> (constructor: AnyFunction, propertyNam
/**
* @en
* Make a function which accept an argument value and return a class decorator.
* Make a function that accepts an argument value and returns a class decorator.
* The decorator sets the editor property `propertyName`, on the decorated class, into that argument value.
* @zh
* 创建一个函数,该函数接受一个参数值并返回一个类装饰器。
+2 -2
View File
@@ -31,10 +31,10 @@ import { assertIsTrue } from './utils/asserts';
// Functions and classes exposed from this module are useful to
// make a class to be `EditorExtendableObject`.
//
// These helpers are used internally, don't expose them to user.
// These helpers are used internally, don't expose them to the user.
/**
* Creates a mixin class which inherits from specific base class and implements the `EditorExtendableObject` interface.
* Creates a mixin class that inherits from the specific base class and implements the `EditorExtendableObject` interface.
* @param Base The base class.
* @param className Assign an optional cc class name. If the base class is not cc class, this param is required.
* @returns The mixin class.
+5 -5
View File
@@ -23,12 +23,12 @@
*/
/**
* Tag to visit editor extras of an object. Never concern about its value please.
* Tag to visit editor extras of an object. Never be concerned about its value, please.
*/
export const editorExtrasTag = '__editorExtras__';
/**
* Engine classes with this kind of signatures are integrated with editor extendability.
* Engine classes with this kind of signature are integrated with editor extendability.
* @internal
*/
export interface EditorExtendableObject {
@@ -37,10 +37,10 @@ export interface EditorExtendableObject {
* The editor extras on this object.
*
* BE CAREFUL: this property is currently governed by Cocos Creator Editor.
* Its definition is not visible and is unknown to both engine code or users codes,
* they SHALL NOT operates it.
* Its definition is not visible and is unknown to both engine code and users codes,
* they SHALL NOT operate it.
*
* You should use editor extras tag to visit this property.
* You should use the editor extras tag to visit this property.
* @example
* ```ts
* import { editorExtrasTag } from 'cc';
+10 -10
View File
@@ -68,7 +68,7 @@ export function createAttrs (subclass: any) {
* Tag the class with any meta attributes, then return all current attributes assigned to it.
* This function holds only the attributes, not their implementations.
* @param constructor The class or instance. If instance, the attribute will be dynamic and only available for the specified instance.
* @param propertyName The name of property or function, used to retrieve the attributes.
* @param propertyName The name of the property or function, used to retrieve the attributes.
* @private
*/
export function attr (constructor: any, propertyName: string): { [attributeName: string]: any; } {
@@ -84,7 +84,7 @@ export function attr (constructor: any, propertyName: string): { [attributeName:
}
/**
* Returns a readonly meta object.
* Returns a read-only meta-object.
*/
export function getClassAttrs (constructor: any) {
return (constructor.hasOwnProperty('__attrs__') && constructor.__attrs__) || createAttrs(constructor);
@@ -111,14 +111,14 @@ export class PrimitiveType<T> {
/**
* @en
* Indicates that the editor should treats this property or array element as a Integer value.
* Indicates that the editor should treat this property or array element as an Integer value.
* @zh
* 指定编辑器以整数形式对待该属性或数组元素。
* @example
* ```ts
* import { CCInteger, _decorator } from "cc";
*
* // in class definition:
* // in the class definition:
*
* @_decorator.property({type: CCInteger})
* count = 0;
@@ -133,14 +133,14 @@ legacyCC.CCInteger = CCInteger;
/**
* @en
* Indicates that the editor should treats this property or array element as a Float value.
* Indicates that the editor should treat this property or array element as a Float value.
* @zh
* 指定编辑器以浮点数形式对待该属性或数组元素。
* @example
* ```ts
* import { CCFloat, _decorator } from "cc";
*
* // in class definition:
* // in the class definition:
*
* @_decorator.property({type: CCFloat})
* x = 0;
@@ -162,14 +162,14 @@ if (EDITOR) {
/**
* @en
* Indicates that the editor should treats this property or array element as a Boolean value.
* Indicates that the editor should treat this property or array element as a Boolean value.
* @zh
* 指定编辑器以布尔值形式对待该属性或数组元素。
*
* @example
* ```ts
* import { CCBoolean, _decorator } from "cc";
* // in class definition
* // in the class definition
* @_decorator.property({type: CCBoolean})
* isTrue = false;
*
@@ -183,14 +183,14 @@ legacyCC.CCBoolean = CCBoolean;
/**
* @en
* Indicates that the editor should treats this property or array element as a String value.
* Indicates that the editor should treat this property or array element as a String value.
* @zh
* 指定编辑器以字符串形式对待该属性或数组元素。
* @example
* ```ts
* import { CCString, _decorator } from "cc";
*
* // in class definition
* // in the class definition
*
* @_decorator.property({type: CCString})
* name = '';
@@ -65,7 +65,7 @@ export class CompactValueTypeArray {
public static ElementType = ElementType;
/**
* Offset into buffer, in bytes.
* Offset into the buffer, in bytes.
*/
@serializable
private _byteOffset = 0;
+3 -3
View File
@@ -31,10 +31,10 @@ import { errorID } from '../../platform/debug';
* 此函数的行为等价于返回了一个新的枚举,其成员囊括了所有源枚举的成员。
* 这些枚举的成员必须各不相同(包括成员名和值),否则行为是未定义的。
* @en
* Combine arbitray number of enumerations.
* It behaves like an enumeration having members that is a combination of members of the source enumerations
* Combine an arbitrary number of enumerations.
* It behaves like an enumeration having members that are a combination of members of the source enumerations
* is returned.
* These enumerations shall have non-overlaped member names or member values.
* These enumerations shall have non-overlapped member names or member values.
* If not, the behavior is undefined.
* @example
* ```ts
+36 -1
View File
@@ -26,7 +26,7 @@ import { CCClass } from '../data/class';
import { ValueType } from '../value-types/value-type';
import { Quat } from './quat';
import { IMat3Like, IMat4Like, IQuatLike, IVec2Like, IVec3Like } from './type-define';
import { EPSILON } from './utils';
import { EPSILON, HALF_PI } from './utils';
import { Vec3 } from './vec3';
import { legacyCC } from '../global-exports';
@@ -623,6 +623,41 @@ export class Mat3 extends ValueType {
);
}
/**
* @en Convert Matrix to euler angle, resulting angle y, z in the range of [-PI, PI],
* x in the range of [-PI/2, PI/2], the rotation order is YXZ.
* @zh 将矩阵转换成欧拉角, 返回角度 y,z 在 [-PI, PI] 区间内, x 在 [-PI/2, PI/2] 区间内,旋转顺序为 YXZ.
*/
public static toEuler (matrix: Mat3, v: Vec3): boolean {
//a[col][row]
const a00 = matrix.m00; const a01 = matrix.m01; const a02 = matrix.m02;
const a10 = matrix.m03; const a11 = matrix.m04; const a12 = matrix.m05;
const a20 = matrix.m06; const a21 = matrix.m07; const a22 = matrix.m08;
// from http://www.geometrictools.com/Documentation/EulerAngles.pdf
// YXZ order
if (a21 < 0.999) {
if (a21 > -0.999) {
v.x = Math.asin(-a21);
v.y = Math.atan2(a20, a22);
v.z = Math.atan2(a01, a11);
return true;
} else {
// Not unique. YA - ZA = atan2(r01,r00)
v.x = HALF_PI;
v.y = Math.atan2(a10, a00);
v.z = 0.0;
return false;
}
} else {
// Not unique. YA + ZA = atan2(-r01,r00)
v.x = -HALF_PI;
v.y = Math.atan2(-a10, a00);
v.z = 0.0;
return false;
}
}
/**
* @en Value at column 0 row 0 of the matrix.
* @zh 矩阵第 0 列第 0 行的元素。
+20 -29
View File
@@ -2024,7 +2024,7 @@ export class Mat4 extends ValueType {
out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);
// account for refections
// account for reflections
if (Mat3.determinant(m3_1) < 0) { out.x *= -1; }
return out;
}
@@ -2035,36 +2035,27 @@ export class Mat4 extends ValueType {
* @param out Vector to receive rotation component
*/
public getRotation (out: Quat) {
const trace = this.m00 + this.m05 + this.m10;
let S = 0;
if (trace > 0) {
S = Math.sqrt(trace + 1.0) * 2;
out.w = 0.25 * S;
out.x = (this.m06 - this.m09) / S;
out.y = (this.m08 - this.m02) / S;
out.z = (this.m01 - this.m04) / S;
} else if ((this.m00 > this.m05) && (this.m00 > this.m10)) {
S = Math.sqrt(1.0 + this.m00 - this.m05 - this.m10) * 2;
out.w = (this.m06 - this.m09) / S;
out.x = 0.25 * S;
out.y = (this.m01 + this.m04) / S;
out.z = (this.m08 + this.m02) / S;
} else if (this.m05 > this.m10) {
S = Math.sqrt(1.0 + this.m05 - this.m00 - this.m10) * 2;
out.w = (this.m08 - this.m02) / S;
out.x = (this.m01 + this.m04) / S;
out.y = 0.25 * S;
out.z = (this.m06 + this.m09) / S;
} else {
S = Math.sqrt(1.0 + this.m10 - this.m00 - this.m05) * 2;
out.w = (this.m01 - this.m04) / S;
out.x = (this.m08 + this.m02) / S;
out.y = (this.m06 + this.m09) / S;
out.z = 0.25 * S;
// Extract rotation matrix first
const sx = Vec3.set(v3_1, this.m00, this.m01, this.m02).length();
const sy = Vec3.set(v3_1, this.m04, this.m05, this.m06).length();
const sz = Vec3.set(v3_1, this.m08, this.m09, this.m10).length();
m3_1.m00 = this.m00 / sx;
m3_1.m01 = this.m01 / sx;
m3_1.m02 = this.m02 / sx;
m3_1.m03 = this.m04 / sy;
m3_1.m04 = this.m05 / sy;
m3_1.m05 = this.m06 / sy;
m3_1.m06 = this.m08 / sz;
m3_1.m07 = this.m09 / sz;
m3_1.m08 = this.m10 / sz;
const det = Mat3.determinant(m3_1);
if (det < 0) {
m3_1.m00 *= -1;
m3_1.m01 *= -1;
m3_1.m02 *= -1;
}
return out;
return Quat.fromMat3(out, m3_1);
}
/**
+44 -27
View File
@@ -396,8 +396,8 @@ export class Quat extends ValueType {
}
/**
* @en Normalize the given quaternion
* @zh 归一化四元数
* @en Normalize the given quaternion, returns a zero quaternion if input is a zero quaternion.
* @zh 归一化四元数,输入零四元数将会返回零四元数。
*/
public static normalize<Out extends IQuatLike> (out: Out, a: Out) {
let len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
@@ -407,6 +407,11 @@ export class Quat extends ValueType {
out.y = a.y * len;
out.z = a.z * len;
out.w = a.w * len;
} else {
out.x = 0;
out.y = 0;
out.z = 0;
out.w = 0;
}
return out;
}
@@ -452,43 +457,43 @@ export class Quat extends ValueType {
* @en Calculates the quaternion with the three-dimensional transform matrix, considering no scale included in the matrix
* @zh 根据三维矩阵信息计算四元数,默认输入矩阵不含有缩放信息
*/
public static fromMat3<Out extends IQuatLike> (out: Out, m: Mat3) {
public static fromMat3<Out extends IQuatLike> (out: Out, m: Mat3) {
const {
m00, m03, m06,
m01, m04, m07,
m02, m05, m08,
m00, m03: m01, m06: m02,
m01: m10, m04: m11, m07: m12,
m02: m20, m05: m21, m08: m22,
} = m;
const trace = m00 + m04 + m08;
const trace = m00 + m11 + m22;
if (trace > 0) {
const s = 0.5 / Math.sqrt(trace + 1.0);
out.w = 0.25 / s;
out.x = (m05 - m07) * s;
out.y = (m06 - m02) * s;
out.z = (m01 - m03) * s;
} else if ((m00 > m04) && (m00 > m08)) {
const s = 2.0 * Math.sqrt(1.0 + m00 - m04 - m08);
out.x = (m21 - m12) * s;
out.y = (m02 - m20) * s;
out.z = (m10 - m01) * s;
} else if ((m00 > m11) && (m00 > m22)) {
const s = 0.5 / Math.sqrt(1.0 + m00 - m11 - m22);
out.w = (m05 - m07) / s;
out.x = 0.25 * s;
out.y = (m03 + m01) / s;
out.z = (m06 + m02) / s;
} else if (m04 > m08) {
const s = 2.0 * Math.sqrt(1.0 + m04 - m00 - m08);
out.w = (m21 - m12) * s;
out.x = 0.25 / s;
out.y = (m01 + m10) * s;
out.z = (m02 + m20) * s;
} else if (m11 > m22) {
const s = 0.5 / Math.sqrt(1.0 + m11 - m00 - m22);
out.w = (m06 - m02) / s;
out.x = (m03 + m01) / s;
out.y = 0.25 * s;
out.z = (m07 + m05) / s;
out.w = (m02 - m20) * s;
out.x = (m01 + m10) * s;
out.y = 0.25 / s;
out.z = (m12 + m21) * s;
} else {
const s = 2.0 * Math.sqrt(1.0 + m08 - m00 - m04);
const s = 0.5 / Math.sqrt(1.0 + m22 - m00 - m11);
out.w = (m01 - m03) / s;
out.x = (m06 + m02) / s;
out.y = (m07 + m05) / s;
out.z = 0.25 * s;
out.w = (m10 - m01) * s;
out.x = (m02 + m20) * s;
out.y = (m12 + m21) * s;
out.z = 0.25 / s;
}
return out;
@@ -613,6 +618,18 @@ export class Quat extends ValueType {
return out;
}
/**
* @en Converts the quaternion to euler angles, result angle y, z in the range of [-180, 180], x in the range of [-90, 90], the rotation order is YXZ
* @zh 根据四元数计算欧拉角,返回角度 yz 在 [-180, 180], x 在 [-90, 90],旋转顺序为 YXZ
*/
public static toEulerInYXZOrder (out: Vec3, q: IQuatLike) {
Mat3.fromQuat(m3_1, q);
Mat3.toEuler(m3_1, out);
out.x = toDegree(out.x);
out.y = toDegree(out.y);
out.z = toDegree(out.z);
}
/**
* @en Converts quaternion to an array
* @zh 四元数转数组
+3
View File
@@ -31,6 +31,9 @@ const _d2r = Math.PI / 180.0;
const _r2d = 180.0 / Math.PI;
export const HALF_PI = Math.PI * 0.5;
export const TWO_PI = Math.PI * 2.0;
export const EPSILON = 0.000001;
/**
+24 -21
View File
@@ -265,8 +265,8 @@ export class Vec2 extends ValueType {
}
/**
* @en Sets the normalized vector to the out vector
* @zh 归一化向量
* @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector.
* @zh 归一化向量,输入零向量将会返回零向量。
*/
public static normalize <Out extends IVec2Like, Vec2Like extends IVec2Like> (out: Out, a: Vec2Like) {
const x = a.x;
@@ -276,6 +276,9 @@ export class Vec2 extends ValueType {
len = 1 / Math.sqrt(len);
out.x = x * len;
out.y = y * len;
} else {
out.x = 0;
out.y = 0;
}
return out;
}
@@ -301,7 +304,7 @@ export class Vec2 extends ValueType {
*/
public static cross <Out extends IVec2Like> (out: Vec3, a: Out, b: Out): Vec3;
public static cross (out: IVec2Like | Vec3, a: IVec2Like, b?: IVec2Like) : number | Vec3 {
public static cross (out: IVec2Like | Vec3, a: IVec2Like, b?: IVec2Like): number | Vec3 {
if (out instanceof Vec3) {
out.x = out.y = 0;
out.z = a.x * b!.y - a.y * b!.x;
@@ -412,19 +415,20 @@ export class Vec2 extends ValueType {
}
/**
* @en Calculates the radian angle between two vectors
* @zh 求两向量夹角弧度
* @en Calculates the radian angle between two vectors, returns zero if either vector is a zero vector.
* @zh 求两向量夹角弧度,任意一个向量是零向量则返回零。
*/
public static angle <Out extends IVec2Like> (a: Out, b: Out) {
Vec2.normalize(v2_1, a);
Vec2.normalize(v2_2, b);
const cosine = Vec2.dot(v2_1, v2_2);
if (cosine > 1.0) {
return 0;
}
if (cosine < -1.0) {
return Math.PI;
const magSqr1 = a.x * a.x + a.y * a.y;
const magSqr2 = b.x * b.x + b.y * b.y;
if (magSqr1 === 0 || magSqr2 === 0) {
return 0.0;
}
const dot = a.x * b.x + a.y * b.y;
let cosine = dot / (Math.sqrt(magSqr1 * magSqr2));
cosine = clamp(cosine, -1.0, 1.0);
return Math.acos(cosine);
}
@@ -751,24 +755,23 @@ export class Vec2 extends ValueType {
}
/**
* @en Calculates radian angle between two vectors
* @zh 获取当前向量和指定向量之间的角度。
* @param other specified vector
* @return The angle between the current vector and the specified vector (in radians); if there are zero vectors in the current vector and the specified vector, 0 is returned.
* @en Calculates radian angle between two vectors, returns zero if either vector is a zero vector.
* @zh 获取当前向量和指定向量之间的角度,任意一个向量是零向量则返回零。
* @param other specified vector.
* @return The angle between the current vector and the specified vector.
*/
public angle (other: Vec2) {
const magSqr1 = this.lengthSqr();
const magSqr2 = other.lengthSqr();
if (magSqr1 === 0 || magSqr2 === 0) {
console.warn('Can\'t get angle between zero vector');
return 0.0;
}
const dot = this.dot(other);
let theta = dot / (Math.sqrt(magSqr1 * magSqr2));
theta = clamp(theta, -1.0, 1.0);
return Math.acos(theta);
let cosine = dot / (Math.sqrt(magSqr1 * magSqr2));
cosine = clamp(cosine, -1.0, 1.0);
return Math.acos(cosine);
}
/**
+16 -13
View File
@@ -305,8 +305,8 @@ export class Vec3 extends ValueType {
}
/**
* @en Sets the normalized vector to the out vector
* @zh 归一化向量
* @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector.
* @zh 归一化向量,输入零向量将会返回零向量。
*/
public static normalize<Out extends IVec3Like> (out: Out, a: IVec3Like) {
const x = a.x;
@@ -319,6 +319,10 @@ export class Vec3 extends ValueType {
out.x = x * len;
out.y = y * len;
out.z = z * len;
} else {
out.x = 0;
out.y = 0;
out.z = 0;
}
return out;
}
@@ -699,15 +703,16 @@ export class Vec3 extends ValueType {
* @zh 求两向量夹角弧度
*/
public static angle (a: IVec3Like, b: IVec3Like) {
Vec3.normalize(v3_1, a);
Vec3.normalize(v3_2, b);
const cosine = Vec3.dot(v3_1, v3_2);
if (cosine > 1.0) {
return 0;
}
if (cosine < -1.0) {
return Math.PI;
const magSqr1 = a.x * a.x + a.y * a.y + a.z * a.z;
const magSqr2 = b.x * b.x + b.y * b.y + b.z * b.z;
if (magSqr1 === 0 || magSqr2 === 0) {
return 0.0;
}
const dot = a.x * b.x + a.y * b.y + a.z * b.z;
let cosine = dot / (Math.sqrt(magSqr1 * magSqr2));
cosine = clamp(cosine, -1.0, 1.0);
return Math.acos(cosine);
}
@@ -1088,6 +1093,7 @@ export class Vec3 extends ValueType {
this.y = y * len;
this.z = z * len;
}
return this;
}
@@ -1109,9 +1115,6 @@ export class Vec3 extends ValueType {
}
}
const v3_1 = new Vec3();
const v3_2 = new Vec3();
CCClass.fastDefine('cc.Vec3', Vec3, { x: 0, y: 0, z: 0 });
legacyCC.Vec3 = Vec3;
+7 -2
View File
@@ -313,8 +313,8 @@ export class Vec4 extends ValueType {
}
/**
* @en Sets the normalized vector to the out vector
* @zh 归一化向量
* @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector.
* @zh 归一化向量,输入零向量将会返回零向量。
*/
public static normalize <Out extends IVec4Like> (out: Out, a: Out) {
const x = a.x;
@@ -328,6 +328,11 @@ export class Vec4 extends ValueType {
out.y = y * len;
out.z = z * len;
out.w = w * len;
} else {
out.x = 0;
out.y = 0;
out.z = 0;
out.w = 0;
}
return out;
}
-85
View File
@@ -1,85 +0,0 @@
/*
Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { fastRemoveAt } from '../utils/array';
import { ScalableContainer } from './scalable-container';
/**
* @en ContainerManager is a sequence container that stores ScalableContainers.
* It will shrink all managed ScalableContainer in a fixed interval.
*/
class ContainerManager {
private _pools: ScalableContainer[] = [];
private _lastShrinkPassed = 0;
/**
* @en Shrink interval in seconds.
*/
public shrinkTimeSpan = 5;
/**
* @en Add a ScalableContainer. Will add the same ScalableContainer instance once.
* @param pool @en The ScalableContainer to add.
*/
addContainer (pool: ScalableContainer) {
if (pool._poolHandle !== -1) return;
pool._poolHandle = this._pools.length;
this._pools.push(pool);
}
/**
* @en Remove a ScalableContainer.
* @param pool @en The ScalableContainer to remove.
*/
removeContainer (pool: ScalableContainer) {
if (pool._poolHandle === -1) return;
this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle;
fastRemoveAt(this._pools, pool._poolHandle);
pool._poolHandle = -1;
}
/**
* @en Try to shrink all managed ScalableContainers.
*/
tryShrink () {
for (let i = 0; i < this._pools.length; i++) {
this._pools[i].tryShrink();
}
}
/**
* @en An update function invoked every frame.
* @param dt @en Delta time of frame interval in secondes.
*/
update (dt: number) {
this._lastShrinkPassed += dt;
if (this._lastShrinkPassed > this.shrinkTimeSpan) {
this.tryShrink();
this._lastShrinkPassed -= this.shrinkTimeSpan;
}
}
}
/**
* @en A global ContainerManager instance.
*/
export const containerManager = new ContainerManager();

Some files were not shown because too many files have changed in this diff Show More