Merge remote-tracking branch 'origin/3d' into 3d

This commit is contained in:
Yun Hsiao Wu
2020-06-03 16:16:07 +08:00
157 changed files with 4314 additions and 3425 deletions
+1 -1
View File
@@ -41,7 +41,7 @@
"@typescript-eslint/adjacent-overload-signatures": "off",
"@typescript-eslint/array-type": ["warn", {
"default": "array-simple"
"default": "array"
}],
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/ban-ts-ignore": "warn",
+3
View File
@@ -9,12 +9,15 @@
"deinterleave",
"deserialize",
"earcut",
"eventify",
"eventified",
"forin",
"glsl",
"grayscale",
"IGFX",
"lerp",
"lerpable",
"lightmap",
"mipmaps",
"octree",
"OPENGL",
+2
View File
@@ -91,3 +91,5 @@ declare type Getter = () => any;
declare type Setter = (value: any) => void;
declare const Buffer: any;
declare type EnumAlias<EnumT> = EnumT[keyof EnumT];
+4
View File
@@ -2012,3 +2012,7 @@ Can't getGFXSampler with out device
### 10001
The sub-mesh contains %d vertices, which beyonds the capability (%d vertices most) of renderer of your platform.
### 10002
Sub-mesh may include at most %d morph targets, but you specified %d.
+8 -8
View File
@@ -34,7 +34,7 @@ import { legacyCC } from '../../core/global-exports';
export class AudioPlayerDOM extends AudioPlayer {
protected _volume = 1;
protected _loop = false;
protected _oneShoting = false;
protected _oneShotOngoing = false;
protected _audio: HTMLAudioElement;
protected _cbRegistered = false;
@@ -82,7 +82,7 @@ export class AudioPlayerDOM extends AudioPlayer {
this._audio.loop = this._loop;
// callback on audio ended
this._audio.addEventListener('ended', () => {
if (this._oneShoting) { return; }
if (this._oneShotOngoing) { return; }
this._state = PlayingState.STOPPED;
this._audio!.currentTime = 0;
this._eventTarget.emit('ended');
@@ -111,7 +111,7 @@ export class AudioPlayerDOM extends AudioPlayer {
if (!this._audio || this._state !== PlayingState.PLAYING) { return; }
this._audio.pause();
this._state = PlayingState.STOPPED;
this._oneShoting = false;
this._oneShotOngoing = false;
}
public stop () {
@@ -120,7 +120,7 @@ export class AudioPlayerDOM extends AudioPlayer {
if (this._state !== PlayingState.PLAYING) { return; }
this._audio.pause();
this._state = PlayingState.STOPPED;
this._oneShoting = false;
this._oneShotOngoing = false;
}
public playOneShot (volume = 1) {
@@ -130,17 +130,17 @@ export class AudioPlayerDOM extends AudioPlayer {
if (!clip) { return; }
clip.currentTime = 0;
clip.volume = volume;
if (this._oneShoting) { return; }
if (this._oneShotOngoing) { return; }
clip.loop = false;
this._oneShoting = true;
this._oneShotOngoing = true;
clip.play().then(() => {
clip.addEventListener('ended', () => {
clip.currentTime = 0;
clip.volume = this._volume;
clip.loop = this._loop;
this._oneShoting = false;
this._oneShotOngoing = false;
}, { once: true });
}).catch(() => { this._oneShoting = false; });
}).catch(() => { this._oneShotOngoing = false; });
}
public setCurrentTime (val: number) {
File diff suppressed because one or more lines are too long
@@ -105,7 +105,7 @@ export class SkinningModelUnit {
}
/**
* @en Convevient setter, copying all necessary information from target skinning model component.
* @en Convenient setter, copying all necessary information from target skinning model component.
* @zh 复制目标 SkinningModelComponent 的所有属性到本单元,方便快速配置。
*/
@property({ type: SkinningModelComponent })
@@ -206,7 +206,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent {
public _onMaterialModified (idx: number, material: Material | null) {
this.cookMaterials();
super._onMaterialModified(idx, this.getMaterial(idx));
super._onMaterialModified(idx, this.getMaterialInstance(idx));
}
public cook () {
@@ -219,7 +219,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent {
if (!this._batchMaterial) {
this._batchMaterial = this.getMaterial(0);
}
const mat = this.getMaterial(0);
const mat = this.getMaterialInstance(0);
if (!mat || !this._batchMaterial || !this._batchMaterial.effectAsset) {
console.warn('incomplete batch material!'); return;
}
@@ -303,16 +303,16 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent {
}
}
if (!isValid || !this._skinningRoot) {
return;
}
if (this._mesh) {
this._mesh.destroyRenderingMesh();
} else {
this._mesh = new Mesh();
}
if (!isValid || !this._skinningRoot) {
return;
}
let posOffset = 0;
let posFormat = GFXFormat.UNKNOWN;
let normalOffset = 0;
@@ -503,74 +503,90 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent {
private _createUnitMesh (unitIdx: number, mesh: Mesh) {
// add batch ID to this temp mesh
// first, update bookkeepping
let uvOffset = 0;
let uvFormat = GFXFormat.UNKNOWN;
let bundleIdx = 0;
for (; bundleIdx < mesh.struct.vertexBundles.length; bundleIdx++) {
const bundle = mesh.struct.vertexBundles[bundleIdx];
uvOffset = bundle.view.offset;
uvFormat = GFXFormat.UNKNOWN;
for (let a = 0; a < bundle.attributes.length; a++) {
const attr = bundle.attributes[a];
if (attr.name === GFXAttributeName.ATTR_TEX_COORD) {
uvFormat = attr.format;
break;
}
uvOffset += GFXFormatInfos[attr.format].size;
}
if (uvFormat) { break; }
}
// first, update bookkeeping
const newMeshStruct: Mesh.IStruct = JSON.parse(JSON.stringify(mesh.struct));
let newOffset = 0;
const oldBundle = mesh.struct.vertexBundles[bundleIdx];
const newBundle = newMeshStruct.vertexBundles[bundleIdx]; // put the new UVs in the same bundle with original UVs
newBundle.attributes.push(batch_id);
newBundle.attributes.push(batch_uv);
newBundle.view.offset = newOffset;
newBundle.view.length += newBundle.view.count * batch_extras_size;
newBundle.view.stride += batch_extras_size;
newOffset += newBundle.view.length;
const modifiedBundles: Record<number, [GFXFormat, number]> = {};
for (let p = 0; p < mesh.struct.primitives.length; p++) {
const primitive = mesh.struct.primitives[p];
let uvOffset = 0;
let uvFormat = GFXFormat.UNKNOWN;
let bundleIdx = 0;
for (; bundleIdx < primitive.vertexBundelIndices.length; bundleIdx++) {
const bundle = mesh.struct.vertexBundles[primitive.vertexBundelIndices[bundleIdx]];
uvOffset = bundle.view.offset;
uvFormat = GFXFormat.UNKNOWN;
for (let a = 0; a < bundle.attributes.length; a++) {
const attr = bundle.attributes[a];
if (attr.name === GFXAttributeName.ATTR_TEX_COORD) {
uvFormat = attr.format;
break;
}
uvOffset += GFXFormatInfos[attr.format].size;
}
if (uvFormat) { break; }
}
if (modifiedBundles[bundleIdx] !== undefined) { continue; }
modifiedBundles[bundleIdx] = [ uvFormat, uvOffset ];
const newBundle = newMeshStruct.vertexBundles[bundleIdx]; // put the new UVs in the same bundle with original UVs
newBundle.attributes.push(batch_id);
newBundle.attributes.push(batch_uv);
newBundle.view.offset = 0;
newBundle.view.length += newBundle.view.count * batch_extras_size;
newBundle.view.stride += batch_extras_size;
}
let totalLength = 0;
for (let b = 0; b < newMeshStruct.vertexBundles.length; b++) {
totalLength += newMeshStruct.vertexBundles[b].view.length;
}
for (let p = 0; p < newMeshStruct.primitives.length; p++) {
const pm = newMeshStruct.primitives[p];
if (pm.indexView) {
pm.indexView.offset = newOffset;
newOffset += pm.indexView.length;
pm.indexView.offset = totalLength;
totalLength += pm.indexView.length;
}
}
// now, we ride!
const src = mesh.data!; let oldOffset = 0;
const newMeshData = new Uint8Array(newOffset);
const dataView = new DataView(newMeshData.buffer);
const uvs = readBuffer(new DataView(src.buffer), uvFormat, uvOffset, oldBundle.view.length, oldBundle.view.stride);
const oldView = oldBundle.view;
const newView = newBundle.view;
let oldStride = oldView.stride;
let newStride = newView.stride;
oldOffset = oldView.offset;
newOffset = newView.offset;
for (let j = 0; j < newView.count; j++) {
const srcVertex = src.subarray(oldOffset, oldOffset + oldStride);
newMeshData.set(srcVertex, newOffset);
// insert batch ID
dataView.setFloat32(newOffset + oldStride, unitIdx, legacyCC.sys.isLittleEndian);
// insert batch UV
dataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], legacyCC.sys.isLittleEndian);
dataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], legacyCC.sys.isLittleEndian);
newOffset += newStride; oldOffset += oldStride;
const newMeshData = new Uint8Array(totalLength);
const oldMeshData = mesh.data!;
const newDataView = new DataView(newMeshData.buffer);
const oldDataView = new DataView(oldMeshData.buffer);
const isLittleEndian = legacyCC.sys.isLittleEndian;
for (const b in modifiedBundles) {
const newBundle = newMeshStruct.vertexBundles[b];
const oldBundle = mesh.struct.vertexBundles[b];
const [ uvFormat, uvOffset ] = modifiedBundles[b];
const uvs = readBuffer(oldDataView, uvFormat, uvOffset, oldBundle.view.length, oldBundle.view.stride);
const oldView = oldBundle.view;
const newView = newBundle.view;
const oldStride = oldView.stride;
const newStride = newView.stride;
let oldOffset = oldView.offset;
let newOffset = newView.offset;
for (let j = 0; j < newView.count; j++) {
const srcVertex = oldMeshData.subarray(oldOffset, oldOffset + oldStride);
newMeshData.set(srcVertex, newOffset);
// insert batch ID
newDataView.setFloat32(newOffset + oldStride, unitIdx, );
// insert batch UV
newDataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], isLittleEndian);
newDataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], isLittleEndian);
newOffset += newStride;
oldOffset += oldStride;
}
}
for (let k = 0; k < newMeshStruct.primitives.length; k++) {
const oldPrimitive = mesh.struct.primitives[k];
const newPrimitive = newMeshStruct.primitives[k];
if (oldPrimitive.indexView && newPrimitive.indexView) {
oldStride = oldPrimitive.indexView.stride;
newStride = newPrimitive.indexView.stride;
oldOffset = oldPrimitive.indexView.offset;
newOffset = newPrimitive.indexView.offset;
const oldStride = oldPrimitive.indexView.stride;
const newStride = newPrimitive.indexView.stride;
let oldOffset = oldPrimitive.indexView.offset;
let newOffset = newPrimitive.indexView.offset;
for (let j = 0; j < newPrimitive.indexView.count; j++) {
const srcIndices = src.subarray(oldOffset, oldOffset + oldStride);
const srcIndices = oldMeshData.subarray(oldOffset, oldOffset + oldStride);
newMeshData.set(srcIndices, newOffset);
newOffset += newStride; oldOffset += oldStride;
newOffset += newStride;
oldOffset += oldStride;
}
}
}
@@ -650,3 +650,12 @@ export class CameraComponent extends Component {
}
}
}
export namespace CameraComponent {
export type ProjectionType = EnumAlias<typeof ProjectionType>;
export type FOVAxis = EnumAlias<typeof FOVAxis>;
export type ClearFlag = EnumAlias<typeof ClearFlag>;
export type Aperture = EnumAlias<typeof Aperture>;
export type Shutter = EnumAlias<typeof Shutter>;
export type ISO = EnumAlias<typeof ISO>;
}
@@ -1,155 +0,0 @@
/**
* @hidden
*/
import { ccclass } from '../../data/class-decorator';
import { GFXClearFlag } from '../../gfx/define';
import { toRadian } from '../../math';
import { Camera } from '../../renderer';
import { CameraComponent } from './camera-component';
import { CAMERA_EDITOR_MASK } from '../../pipeline/define';
import { legacyCC } from '../../global-exports';
@ccclass('cc.EditorCameraComponent')
export class EditorCameraComponent extends CameraComponent {
private _uiEditorCamera: Camera | null = null;
set projection (val) {
super.projection = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.projectionType = val;
}
}
set fov (val) {
super.fov = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.fov = toRadian(val);
}
}
set orthoHeight (val) {
super.orthoHeight = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.orthoHeight = val;
}
}
set near (val) {
super.near = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.nearClip = val;
}
}
set far (val) {
super.far = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.farClip = val;
}
}
set clearColor (val) {
super.clearColor = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.clearColor = val;
}
}
set clearDepth (val) {
super.clearDepth = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.clearDepth = val;
}
}
set clearStencil (val) {
super.clearStencil = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.clearStencil = val;
}
}
set clearFlags (val) {
super.clearFlags = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.clearFlag = val;
}
}
set rect (val) {
super.rect = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.viewport = val;
}
}
set screenScale (val) {
super.screenScale = val;
if (this._uiEditorCamera) {
this._uiEditorCamera.screenScale = val;
}
}
public onLoad () {
super.onLoad();
this._inEditorMode = true;
}
public onEnable () {
super.onEnable();
if (this._uiEditorCamera) {
legacyCC.director.root!.ui.renderScene.addCamera(this._uiEditorCamera);
this._uiEditorCamera.enabled = true;
}
}
public onDisable () {
super.onDisable();
if (this._uiEditorCamera) {
legacyCC.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera);
}
}
public onDestroy () {
super.onDestroy();
if (this._uiEditorCamera) {
legacyCC.director.root!.destroyCamera(this._uiEditorCamera);
this._uiEditorCamera = null;
}
}
protected _createCamera () {
const priorCamera = this._camera;
super._createCamera();
if (this._camera !== priorCamera && this._camera) {
if (this._uiEditorCamera) {
legacyCC.director.root!.destroyCamera(this._uiEditorCamera);
this._uiEditorCamera = null;
}
this._uiEditorCamera = legacyCC.director.root!.createCamera();
this._uiEditorCamera!.initialize({
name: 'Editor UICamera',
node: this._camera.node,
projection: this._projection,
window: legacyCC.director.root!.mainWindow,
priority: this._priority + 1,
flows: ['UIFlow'],
});
this._uiEditorCamera!.enabled = true;
this._uiEditorCamera!.visibility = CAMERA_EDITOR_MASK;
this._uiEditorCamera!.viewport = this._camera.viewport;
this._uiEditorCamera!.fov = this._camera.fov;
this._uiEditorCamera!.nearClip = this._camera.nearClip;
this._uiEditorCamera!.farClip = this._camera.farClip;
this._uiEditorCamera!.clearColor = this._camera.clearColor;
this._uiEditorCamera!.clearDepth = this._camera.clearDepth;
this._uiEditorCamera!.clearStencil = this._camera.clearStencil;
this._uiEditorCamera!.clearFlag = GFXClearFlag.DEPTH_STENCIL;
}
}
}
+1 -2
View File
@@ -31,7 +31,6 @@ import { legacyCC } from '../../global-exports';
import { BatchedSkinningModelComponent, SkinningModelUnit } from './batched-skinning-model-component';
import { CameraComponent } from './camera-component';
import { DirectionalLightComponent } from './directional-light-component';
import { EditorCameraComponent } from './editor-camera-component';
import { LightComponent } from './light-component';
import { ModelComponent } from './model-component';
import { RenderableComponent } from './renderable-component';
@@ -56,7 +55,7 @@ export {
// cc.AnimationComponent = AnimationComponent;
legacyCC.CameraComponent = CameraComponent;
legacyCC.EditorComponent = EditorCameraComponent;
// legacyCC.EditorComponent = EditorCameraComponent;
legacyCC.RenderableComponent = RenderableComponent;
legacyCC.ModelComponent = ModelComponent;
legacyCC.SkinningModelComponent = SkinningModelComponent;
@@ -271,3 +271,8 @@ export class LightComponent extends Component {
}
}
}
export namespace LightComponent {
export type Type = EnumAlias<typeof LightType>;
export type PhotometricTerm = EnumAlias<typeof PhotometricTerm>;
}
+54 -25
View File
@@ -41,6 +41,7 @@ import { builtinResMgr } from '../builtin';
import { RenderableComponent } from './renderable-component';
import { MorphRenderingInstance } from '../../assets/morph';
import { legacyCC } from '../../global-exports';
import { assertIsTrue } from '../../data/utils/asserts';
/**
* @en Shadow projection mode.
@@ -77,8 +78,10 @@ class ModelLightmapSettings {
protected _bakeable: boolean = false;
@property
protected _castShadow: boolean = false;
@property
protected _recieveShadow: boolean = false;
@property({
formerlySerializedAs: '_recieveShadow',
})
protected _receiveShadow: boolean = false;
@property
protected _lightmapSize: number = 64;
@@ -109,16 +112,16 @@ class ModelLightmapSettings {
}
/**
* @en recieve shadow.
* @en receive shadow.
* @zh 是否接受阴影。
*/
@property
get recieveShadow () {
return this._recieveShadow;
get receiveShadow () {
return this._receiveShadow;
}
set recieveShadow (val) {
this._recieveShadow = val;
set receiveShadow (val) {
this._receiveShadow = val;
}
/**
@@ -202,7 +205,15 @@ export class ModelComponent extends RenderableComponent {
return this._model;
}
@property
@property({
visible: function (this: ModelComponent) {
return !!(
this.mesh &&
this.mesh.struct.morph &&
this.mesh.struct.morph.subMeshMorphs.some((subMeshMorph) => !!subMeshMorph)
);
},
})
get enableMorph () {
return this._enableMorph;
}
@@ -211,8 +222,9 @@ export class ModelComponent extends RenderableComponent {
this._enableMorph = value;
}
protected _modelType: typeof MorphModel;
protected _model: MorphModel | null = null;
protected _modelType: typeof Model;
protected _model: Model | null = null;
private _morphInstance: MorphRenderingInstance | null = null;
@@ -221,7 +233,7 @@ export class ModelComponent extends RenderableComponent {
constructor () {
super();
this._modelType = MorphModel;
this._modelType = Model;
}
public onLoad () {
@@ -272,12 +284,12 @@ export class ModelComponent extends RenderableComponent {
}
}
public _updateLightmap (lightmap: Texture2D|null, uoff: number, voff: number, uscale: number, vscale: number) {
public _updateLightmap (lightmap: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number) {
this.lightmapSettings.texture = lightmap;
this.lightmapSettings.uvParam.x = uoff;
this.lightmapSettings.uvParam.y = voff;
this.lightmapSettings.uvParam.z = uscale;
this.lightmapSettings.uvParam.w = vscale;
this.lightmapSettings.uvParam.x = uOff;
this.lightmapSettings.uvParam.y = vOff;
this.lightmapSettings.uvParam.z = uScale;
this.lightmapSettings.uvParam.w = vScale;
if (this.model !== null) {
this.model.updateLightingmap(this.lightmapSettings.texture, this.lightmapSettings.uvParam);
@@ -304,12 +316,21 @@ export class ModelComponent extends RenderableComponent {
}
protected _createModel () {
this._model = (legacyCC.director.root as Root).createModel(this._modelType);
const preferMorphOverPlain = !!this._morphInstance;
// Note we only change to use `MorphModel` if
// we are required to render morph and the `this._modelType` is exactly the basic `Model`.
// We do this since the `this._modelType` might be changed in classes derived from `ModelComponent`.
// We shall not overwrite it.
// Please notice that we do not enforce that
// derived classes should use a morph-able model type(i.e. model type derived from `MorphModel`).
// So we should take care of the edge case.
const modelType = (preferMorphOverPlain && this._modelType === Model) ? MorphModel : this._modelType;
this._model = (legacyCC.director.root as Root).createModel(modelType);
this._model.visFlags = this.visibility;
this._model.initialize(this.node);
this._models.length = 0;
this._models.push(this._model);
if (this._morphInstance) {
if (this._morphInstance && this._model instanceof MorphModel) {
this._model.setMorphRendering(this._morphInstance);
}
}
@@ -319,10 +340,10 @@ export class ModelComponent extends RenderableComponent {
return;
}
const scene = this._getRenderScene();
if (this._model!.scene != null) {
if (this._model.scene != null) {
this._detachFromScene();
}
scene.addModel(this._model!);
scene.addModel(this._model);
}
protected _detachFromScene () {
@@ -377,7 +398,7 @@ export class ModelComponent extends RenderableComponent {
return builtinResMgr.get<Material>('missing-material');
}
protected _onVisiblityChange (val: number) {
protected _onVisibilityChange (val: number) {
if (!this._model) { return; }
this._model.visFlags = val;
}
@@ -386,10 +407,12 @@ export class ModelComponent extends RenderableComponent {
if (!this._model) { return; }
if (this._shadowCastingMode === ModelShadowCastingMode.OFF) {
this._model.castShadow = false;
} else if (this._shadowCastingMode === ModelShadowCastingMode.ON) {
this._model.castShadow = true;
} else {
console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`);
assertIsTrue(
this._shadowCastingMode === ModelShadowCastingMode.ON,
`ShadowCastingMode ${this._shadowCastingMode} is not supported.`,
);
this._model.castShadow = true;
}
}
@@ -436,7 +459,9 @@ export class ModelComponent extends RenderableComponent {
this._morphInstance.setWeights(iSubMesh, weights);
}
this._model?.setMorphRendering(this._morphInstance);
if (this._model && this._model instanceof MorphModel) {
this._model.setMorphRendering(this._morphInstance);
}
}
private _syncMorphWeights (subMeshIndex: number) {
@@ -450,3 +475,7 @@ export class ModelComponent extends RenderableComponent {
subMeshMorphInstance.renderResources.setWeights(subMeshMorphInstance.weights);
}
}
export namespace ModelComponent {
export type ShadowCastingMode = EnumAlias<typeof ModelShadowCastingMode>;
}
@@ -34,7 +34,7 @@ export class RenderableComponent extends Component {
set visibility (val) {
this._visFlags = val;
this._onVisiblityChange(val);
this._onVisibilityChange(val);
}
@property({
@@ -204,6 +204,6 @@ export class RenderableComponent extends Component {
protected _clearMaterials () {
}
protected _onVisiblityChange (val) {
protected _onVisibilityChange (val) {
}
}
+51 -92
View File
@@ -28,58 +28,17 @@
*/
import { Component } from '../components/component';
import { ccclass, help, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator';
import { Event, EventTarget } from '../event';
import { CallbacksInvoker, ICallbackTable } from '../event/callbacks-invoker';
import { applyMixins, IEventTarget } from '../event/event-target-factory';
import { ccclass, executeInEditMode, executionOrder, help, menu, property } from '../data/class-decorator';
import { Eventify } from '../event/eventify';
import { warnID } from '../platform/debug';
import * as ArrayUtils from '../utils/array';
import { createMap } from '../utils/js-typed';
import { ccenum } from '../value-types/enum';
import { AnimationClip } from './animation-clip';
import { AnimationState } from './animation-state';
import { AnimationState, EventType } from './animation-state';
import { CrossFade } from './cross-fade';
import { EDITOR, TEST } from 'internal:constants';
import { legacyCC } from '../global-exports';
/**
* @en The event type supported by Animation
* @zh Animation 支持的事件类型。
*/
export enum EventType {
/**
* @en Emit when begin playing animation
* @zh 开始播放时触发。
*/
PLAY = 'play',
/**
* @en Emit when stop playing animation
* @zh 停止播放时触发。
*/
STOP = 'stop',
/**
* @en Emit when pause animation
* @zh 暂停播放时触发。
*/
PAUSE = 'pause',
/**
* @en Emit when resume animation
* @zh 恢复播放时触发。
*/
RESUME = 'resume',
/**
* @en If animation repeat count is larger than 1, emit when animation play to the last frame
* @zh 假如动画循环次数大于 1,当动画播放到最后一帧时触发。
*/
LASTFRAME = 'lastframe',
/**
* @en Emit when finish playing animation
* @zh 动画播放完成时触发。
*/
FINISHED = 'finished',
}
ccenum(EventType);
/**
* 动画组件管理动画状态来控制动画的播放。
* 它提供了方便的接口用来预创建指定动画剪辑的动画状态,并提供了一系列事件:
@@ -95,7 +54,7 @@ ccenum(EventType);
@executionOrder(99)
@executeInEditMode
@menu('Components/Animation')
export class AnimationComponent extends Component implements IEventTarget {
export class AnimationComponent extends Eventify(Component) {
/**
* 获取此动画组件的自有动画剪辑。
* 动画组件开始运行时会为每个自有动画剪辑创建动画状态。
@@ -181,14 +140,12 @@ export class AnimationComponent extends Component implements IEventTarget {
})
public playOnLoad = false;
public _callbackTable: ICallbackTable = createMap(true);
protected _crossFade = new CrossFade();
protected _nameToState: { [name: string]: AnimationState; } = createMap(true);
protected _nameToState: Record<string, AnimationState> = createMap(true);
@property({ type: [AnimationClip] })
protected _clips: Array<(AnimationClip | null)> = [];
protected _clips: (AnimationClip | null)[] = [];
@property
protected _defaultClip: AnimationClip | null = null;
@@ -322,6 +279,7 @@ export class AnimationComponent extends Component implements IEventTarget {
public removeState (name: string) {
const state = this._nameToState[name];
if (state) {
state.allowLastFrameEvent(false);
state.stop();
delete this._nameToState[name];
}
@@ -354,11 +312,12 @@ export class AnimationComponent extends Component implements IEventTarget {
* @param {Boolean} [force=false] - If force is true, then will always remove the clip and any animation states based on it.
*/
public removeClip (clip: AnimationClip, force?: boolean) {
let state: AnimationState | undefined;
for (const name of Object.keys(this._nameToState)) {
state = this._nameToState[name];
let removalState: AnimationState | undefined;
for (const name in this._nameToState) {
const state = this._nameToState[name];
const stateClip = state.clip;
if (stateClip === clip) {
removalState = state;
break;
}
}
@@ -371,8 +330,8 @@ export class AnimationComponent extends Component implements IEventTarget {
}
}
if (state && state.isPlaying) {
if (force) { state.stop(); }
if (removalState && removalState.isPlaying) {
if (force) { removalState.stop(); }
else {
if (!TEST) { warnID(3903); }
return;
@@ -381,8 +340,8 @@ export class AnimationComponent extends Component implements IEventTarget {
this._clips = this._clips.filter((item) => item !== clip);
if (state) {
delete this._nameToState[state.name];
if (removalState) {
delete this._nameToState[removalState.name];
}
}
@@ -411,12 +370,18 @@ export class AnimationComponent extends Component implements IEventTarget {
* animation.on('play', this.onPlay, this);
* ```
*/
public on (type: string, callback: (type: string, state: AnimationState) => void, target?: Object) {
const ret = EventTarget.prototype.on.call(this, type, callback, target);
if (type === 'lastframe') {
for (const stateName of Object.keys(this._nameToState)) {
this._nameToState[stateName]!._lastframeEventOn = true;
}
public on<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any) {
const ret = super.on(type, callback, thisArg);
if (type === EventType.LASTFRAME) {
this._syncAllowLastFrameEvent();
}
return ret;
}
public once<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any) {
const ret = super.once(type, callback, thisArg);
if (type === EventType.LASTFRAME) {
this._syncAllowLastFrameEvent();
}
return ret;
}
@@ -435,33 +400,13 @@ export class AnimationComponent extends Component implements IEventTarget {
* animation.off('play', this.onPlay, this);
* ```
*/
public off (type: string, callback: Function, target?: Object) {
if (type === 'lastframe') {
const nameToState = this._nameToState;
for (const name of Object.keys(nameToState)) {
const state = nameToState[name]!;
state._lastframeEventOn = false;
}
public off (type: EventType, callback?: Function, thisArg?: any) {
super.off(type, callback, thisArg);
if (type === EventType.LASTFRAME) {
this._syncDisallowLastFrameEvent();
}
EventTarget.prototype.off.call(this, type, callback, target);
}
/**
* @en IEventTarget implementations, they will be overwrote with the same implementation in EventTarget by applyMixins
* @zh IEventTarget 实现,它们将被 applyMixins 在 EventTarget 中用相同的实现覆盖。
*/
public targetOff (keyOrTarget?: string | Object | undefined): void {}
public once (type: string, callback: Function, target?: Object | undefined): Function | undefined {
return;
}
public dispatchEvent (event: Event): void {}
public hasEventListener (key: string, callback?: Function | undefined, target?: Object | undefined): boolean {
return false;
}
public removeAll (keyOrTarget?: string | Object | undefined): void {}
public emit (key: string, ...args: any[]): void {}
protected _createState (clip: AnimationClip, name?: string) {
return new AnimationState(clip, name);
}
@@ -469,6 +414,7 @@ export class AnimationComponent extends Component implements IEventTarget {
protected _doCreateState (clip: AnimationClip, name: string) {
const state = this._createState(clip, name);
state._setEventTarget(this);
state.allowLastFrameEvent(this.hasEventListener(EventType.LASTFRAME));
if (this.node) {
state.initialize(this.node);
}
@@ -502,14 +448,27 @@ export class AnimationComponent extends Component implements IEventTarget {
}
}
}
private _syncAllowLastFrameEvent () {
if (this.hasEventListener(EventType.LASTFRAME)) {
for (const stateName in this._nameToState) {
this._nameToState[stateName].allowLastFrameEvent(true);
}
}
}
private _syncDisallowLastFrameEvent () {
if (!this.hasEventListener(EventType.LASTFRAME)) {
for (const stateName in this._nameToState) {
this._nameToState[stateName].allowLastFrameEvent(false);
}
}
}
}
// for restore on and off
const {on, off} = AnimationComponent.prototype;
applyMixins(AnimationComponent, [CallbacksInvoker, EventTarget]);
// restore
AnimationComponent.prototype.on = on;
AnimationComponent.prototype.off = off;
export namespace AnimationComponent {
export type EventType = EnumAlias<typeof EventType>;
}
legacyCC.AnimationComponent = AnimationComponent;
+57 -11
View File
@@ -13,6 +13,13 @@ import { BlendStateBuffer } from './skeletal-animation-blending';
import { AnimationState } from './animation-state';
import { CrossFade } from './cross-fade';
import { legacyCC } from '../global-exports';
import { IJointTransform, deleteTransform, getTransform, getWorldMatrix } from '../renderer/models/skinning-model';
import { Socket } from './skeletal-animation-component';
interface ISocketData {
target: Node;
transform: IJointTransform;
}
@ccclass
export class AnimationManager extends System {
@@ -23,9 +30,14 @@ export class AnimationManager extends System {
public static ID = 'animation';
private _anims = new MutableForwardIterator<AnimationState>([]);
private _delayEvents: Array<{target: Node; func: string; args: any[]}> = [];
private _delayEvents: {
fn: Function;
thisArg: any;
args: any[];
}[] = [];
private _blendStateBuffer: BlendStateBuffer = new BlendStateBuffer();
private _crossFades: CrossFade[] = [];
private _sockets: ISocketData[] = [];
public addCrossFade (crossFade: CrossFade) {
this._crossFades.push(crossFade);
@@ -36,8 +48,10 @@ export class AnimationManager extends System {
}
public update (dt: number) {
for (const crossFade of this._crossFades) {
crossFade.update(dt);
const { _delayEvents, _crossFades, _sockets } = this;
for (let i = 0, l = _crossFades.length; i < l; i++) {
_crossFades[i].update(dt);
}
const iterator = this._anims;
const array = iterator.array;
@@ -49,12 +63,17 @@ export class AnimationManager extends System {
}
this._blendStateBuffer.apply();
const events = this._delayEvents;
for (let i = 0, l = events.length; i < l; i++) {
const event = events[i];
event.target[event.func].apply(event.target, event.args);
const stamp = legacyCC.director.getTotalFrames();
for (let i = 0, l = _sockets.length; i < l; i++) {
const { target, transform } = _sockets[i];
target.matrix = getWorldMatrix(transform, stamp);
}
events.length = 0;
for (let i = 0, l = _delayEvents.length; i < l; i++) {
const event = _delayEvents[i];
event.fn.apply(event.thisArg, event.args);
}
_delayEvents.length = 0;
}
public destruct () {
@@ -77,13 +96,40 @@ export class AnimationManager extends System {
}
}
public pushDelayEvent (target: Node, func: string, args: any[]) {
public pushDelayEvent (fn: Function, thisArg: any, args: any[]) {
this._delayEvents.push({
target,
func,
fn,
thisArg,
args,
});
}
public addSockets (root: Node, sockets: Socket[]) {
for (let i = 0; i < sockets.length; ++i) {
const socket = sockets[i];
if (this._sockets.find((s) => s.target === socket.target)) { continue; }
const targetNode = root.getChildByPath(socket.path);
const transform = socket.target && targetNode && getTransform(targetNode, root);
if (transform) {
this._sockets.push({ target: socket.target!, transform });
}
}
}
public removeSockets (root: Node, sockets: Socket[]) {
for (let i = 0; i < sockets.length; ++i) {
const socketToRemove = sockets[i];
for (let j = 0; j < this._sockets.length; ++j) {
const socket = this._sockets[j];
if (socket.target === socketToRemove.target) {
deleteTransform(socket.transform.node);
this._sockets[j] = this._sockets[this._sockets.length - 1];
this._sockets.length--;
break;
}
}
}
}
}
director.on(Director.EVENT_INIT, () => {
+92 -79
View File
@@ -27,35 +27,64 @@
* @category animation
*/
import { EventArgumentsOf, EventCallbackOf } from '../event/defines';
import { Node } from '../scene-graph/node';
import { AnimationClip, IRuntimeCurve } from './animation-clip';
import { AnimationComponent } from './animation-component';
import { AnimCurve, RatioSampler } from './animation-curve';
import { createBoundTarget, createBufferedTarget, IBufferedTarget, IBoundTarget } from './bound-target';
import { Playable } from './playable';
import { WrapMode, WrapModeMask, WrappedInfo } from './types';
import { error } from '../platform/debug';
import { EDITOR } from 'internal:constants';
import { HierarchyPath, TargetPath, evaluatePath } from './target-path';
import { HierarchyPath, evaluatePath } from './target-path';
import { BlendStateBuffer, createBlendStateWriter, IBlendStateWriter } from './skeletal-animation-blending';
import { legacyCC } from '../global-exports';
import { ccenum } from '../value-types/enum';
enum PropertySpecialization {
NodePosition,
NodeScale,
NodeRotation,
None,
/**
* @en The event type supported by Animation
* @zh Animation 支持的事件类型。
*/
export enum EventType {
/**
* @en Emit when begin playing animation
* @zh 开始播放时触发。
*/
PLAY = 'play',
/**
* @en Emit when stop playing animation
* @zh 停止播放时触发。
*/
STOP = 'stop',
/**
* @en Emit when pause animation
* @zh 暂停播放时触发。
*/
PAUSE = 'pause',
/**
* @en Emit when resume animation
* @zh 恢复播放时触发。
*/
RESUME = 'resume',
/**
* @en If animation repeat count is larger than 1, emit when animation play to the last frame.
* @zh 假如动画循环次数大于 1,当动画播放到最后一帧时触发。
*/
LASTFRAME = 'lastframe',
/**
* @en Triggered when finish playing animation.
* @zh 动画完成播放时触发。
*/
FINISHED = 'finished',
}
ccenum(EventType);
export class ICurveInstance {
public commonTargetIndex?: number;
private _curve: AnimCurve;
private _boundTarget: IBoundTarget;
private _rootTarget: any;
private _rootTargetProperty?: string;
private _cached?: any[];
private _curveDetail: Omit<IRuntimeCurve, 'sampler'>;
constructor (
@@ -66,7 +95,6 @@ export class ICurveInstance {
this._curveDetail = runtimeCurve;
this._boundTarget = boundTarget;
this._rootTarget = target;
}
public applySample (ratio: number, index: number, lerpRequired: boolean, samplerResultCache, weight: number) {
@@ -127,15 +155,6 @@ function makeSamplerSharedGroup (sampler: RatioSampler | null): ISamplerSharedGr
const InvalidIndex = -1;
export interface IAnimationEventDefinitionMap {
'finished': (animationState: AnimationState) => void;
'lastframe': (animationState: AnimationState) => void;
'play': (animationState: AnimationState) => void;
'pause': (animationState: AnimationState) => void;
'resume': (animationState: AnimationState) => void;
'stop': (animationState: AnimationState) => void;
}
/**
* @en
* The AnimationState gives full control over animation playback process.
@@ -242,12 +261,6 @@ export class AnimationState extends Playable {
this._delayTime = this._delay = value;
}
/**
* @en The curves list.
* @zh 曲线列表。
*/
// public curves: AnimCurve[] = [];
// http://www.w3.org/TR/web-animations/#idl-def-AnimationTiming
/**
@@ -278,8 +291,6 @@ export class AnimationState extends Playable {
public frameRate = 0;
public _lastframeEventOn = false;
protected _wrapMode = WrapMode.Normal;
protected _repeatCount = 1;
@@ -305,15 +316,16 @@ export class AnimationState extends Playable {
/**
* May be `null` due to failed to initialize.
*/
protected _commonTargetStatuses: Array<null | {
protected _commonTargetStatuses: (null | {
target: IBufferedTarget;
changed: boolean;
}> = [];
})[] = [];
protected _curveLoaded = false;
protected _ignoreIndex = InvalidIndex;
private _blendStateBuffer: BlendStateBuffer | null = null;
private _blendStateWriters: IBlendStateWriter[] = [];
private _isBlendStateWriterInitialized = false;
private _allowLastFrame = false;
constructor (clip: AnimationClip, name = '') {
super();
@@ -368,7 +380,7 @@ export class AnimationState extends Playable {
this._samplerSharedGroups.push(samplerSharedGroup);
}
let rootTarget: any = undefined;
let rootTarget: any;
if (typeof propertyCurve.commonTarget === 'undefined') {
rootTarget = root;
} else {
@@ -416,64 +428,59 @@ export class AnimationState extends Playable {
this._destroyBlendStateWriters();
}
public _emit (type, state) {
if (this._target && this._target.isValid) {
this._target.emit(type, type, state);
}
/**
* @deprecated Since V1.1.1, animation states were no longer defined as event targets.
* To process animation events, use `AnimationComponent` instead.
*/
public emit (...args: any[]) {
legacyCC.director.getAnimationManager().pushDelayEvent(this._emit, this, args);
}
public emit<K extends string> (type: K, ...args: EventArgumentsOf<K, IAnimationEventDefinitionMap>): void;
public emit (...restargs: any[]) {
const args = new Array(restargs.length);
for (let i = 0, l = args.length; i < l; i++) {
args[i] = restargs[i];
}
legacyCC.director.getAnimationManager().pushDelayEvent(this, '_emit', args);
}
public on<K extends string> (type: K, callback: EventCallbackOf<K, IAnimationEventDefinitionMap>, target?: any): void;
/**
* @deprecated Since V1.1.1, animation states were no longer defined as event targets.
* To process animation events, use `AnimationComponent` instead.
*/
public on (type: string, callback: Function, target?: any) {
if (this._target && this._target.isValid) {
if (type === 'lastframe') {
this._lastframeEventOn = true;
}
return this._target.on(type, callback, target);
}
else {
} else {
return null;
}
}
public once<K extends string> (type: K, callback: EventCallbackOf<K, IAnimationEventDefinitionMap>, target?: any): void;
/**
* @deprecated Since V1.1.1, animation states were no longer defined as event targets.
* To process animation events, use `AnimationComponent` instead.
*/
public once (type: string, callback: Function, target?: any) {
if (this._target && this._target.isValid) {
if (type === 'lastframe') {
this._lastframeEventOn = true;
}
return this._target.once(type, (event) => {
callback.call(target, event);
this._lastframeEventOn = false;
});
}
else {
return this._target.once(type, callback, target);
} else {
return null;
}
}
/**
* @deprecated Since V1.1.1, animation states were no longer defined as event targets.
* To process animation events, use `AnimationComponent` instead.
*/
public off (type: string, callback: Function, target?: any) {
if (this._target && this._target.isValid) {
if (type === 'lastframe') {
if (!this._target.hasEventListener(type)) {
this._lastframeEventOn = false;
}
}
this._target.off(type, callback, target);
}
}
/**
* @zh
* 是否允许触发 `LastFrame` 事件。
* @en
* Whether `LastFrame` should be triggered.
* @param allowed True if the last frame events may be triggered.
*/
public allowLastFrameEvent (allowed: boolean) {
this._allowLastFrame = allowed;
}
public _setEventTarget (target) {
this._target = target;
}
@@ -613,7 +620,7 @@ export class AnimationState extends Playable {
// sample
const info = this.sample();
if (this._lastframeEventOn) {
if (this._allowLastFrame) {
let lastInfo;
if (!this._lastWrapInfo) {
lastInfo = this._lastWrapInfo = new WrappedInfo(info);
@@ -622,7 +629,7 @@ export class AnimationState extends Playable {
}
if (this.repeatCount > 1 && ((info.iterations | 0) > (lastInfo.iterations | 0))) {
this.emit('lastframe', this);
this.emit(EventType.LASTFRAME, this);
}
lastInfo.set(info);
@@ -630,7 +637,7 @@ export class AnimationState extends Playable {
if (info.stopped) {
this.stop();
this.emit('finished', this);
this.emit(EventType.FINISHED, this);
}
}
@@ -647,13 +654,13 @@ export class AnimationState extends Playable {
}
}
if (this._lastframeEventOn) {
if (this._allowLastFrame) {
if (this._lastIterations === undefined) {
this._lastIterations = ratio;
}
if ((this.time > 0 && this._lastIterations > ratio) || (this.time < 0 && this._lastIterations < ratio)) {
this.emit('lastframe', this);
this.emit(EventType.LASTFRAME, this);
}
this._lastIterations = ratio;
@@ -667,24 +674,24 @@ export class AnimationState extends Playable {
this.setTime(0);
this._delayTime = this._delay;
this._onReplayOrResume();
this.emit('play', this);
this.emit(EventType.PLAY, this);
}
protected onStop () {
if (!this.isPaused) {
this._onPauseOrStop();
}
this.emit('stop', this);
this.emit(EventType.STOP, this);
}
protected onResume () {
this._onReplayOrResume();
this.emit('resume', this);
this.emit(EventType.RESUME, this);
}
protected onPause () {
this._onPauseOrStop();
this.emit('pause', this);
this.emit(EventType.PAUSE, this);
}
protected _sampleCurves (ratio: number) {
@@ -818,13 +825,19 @@ export class AnimationState extends Playable {
lastIndex += direction;
legacyCC.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]);
legacyCC.director.getAnimationManager().pushDelayEvent(this._fireEvent, this, [lastIndex]);
} while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length);
}
this._lastWrapInfoEvent.set(wrapInfo);
}
private _emit (type, state) {
if (this._target && this._target.isValid) {
this._target.emit(type, type, state);
}
}
private _fireEvent (index: number) {
if (!this._targetNode || !this._targetNode.isValid) {
return;
+5 -4
View File
@@ -44,10 +44,6 @@ export class CrossFade extends Playable {
let absoluteWeight = 1.0;
let deadFadingBegin = this._fadings.length;
for (let iFading = 0; iFading < this._fadings.length; ++iFading) {
if (absoluteWeight === 0) {
deadFadingBegin = iFading;
break;
}
const fading = this._fadings[iFading];
fading.easeTime += deltaTime;
const relativeWeight = clamp01(fading.easeTime / fading.easeDuration);
@@ -56,6 +52,11 @@ export class CrossFade extends Playable {
if (fading.target.state) {
fading.target.state.weight += weight;
}
if (fading.easeTime >= fading.easeDuration) {
deadFadingBegin = iFading + 1;
fading.easeTime = fading.easeDuration;
break;
}
}
// Kill fadings having no lifetime.
@@ -80,7 +80,7 @@ export type IBlendStateWriter = IValueProxyFactory & {
destroy: () => void;
};
export function createBlendStateWriter<P extends BlendingProperty>(
export function createBlendStateWriter<P extends BlendingProperty> (
blendState: BlendStateBuffer,
node: Node,
property: P,
@@ -98,18 +98,18 @@ export function createBlendStateWriter<P extends BlendingProperty>(
let isConstCacheValid = false;
let lastWeight = -1;
return {
initialize: function () {
initialize () {
if (!propertyBlendState) {
propertyBlendState = blendState.ref(node, property);
}
},
destroy: function () {
destroy () {
if (propertyBlendState) {
blendState.deRef(node, property);
propertyBlendState = null;
}
},
forTarget: (_) => {
forTarget: () => {
return {
set: (value: BlendingPropertyValue<P>) => {
if (!propertyBlendState) {
@@ -120,7 +120,7 @@ export function createBlendStateWriter<P extends BlendingProperty>(
if (weight !== 1 ||
weight !== lastWeight) {
// If there are multi writer for this property at this time,
// or if the weight has been changed since last write,
// or if the weight has been changed since last write,
// we should invalidate the cache.
isConstCacheValid = false;
} else if (isConstCacheValid) {
@@ -38,6 +38,7 @@ import { SkelAnimDataHub } from './skeletal-animation-data-hub';
import { SkeletalAnimationState } from './skeletal-animation-state';
import { getWorldTransformUntilRoot } from './transform-utils';
import { legacyCC } from '../global-exports';
import { AnimationManager } from './animation-manager';
@ccclass('cc.SkeletalAnimationComponent.Socket')
export class Socket {
@@ -78,7 +79,7 @@ function collectRecursively (node: Node, prefix = '', out: string[] = []) {
/**
* @en
* Skeletal animaiton component, offers the following features on top of [[AnimationComponent]]:
* Skeletal animation component, offers the following features on top of [[AnimationComponent]]:
* * Choice between baked animation and real-time calculation, to leverage efficiency and expressiveness.
* * Joint socket system: Create any socket node directly under the animation component root node,
* find your target joint and register both to the socket list, so that the socket node would be in-sync with the joint.
@@ -111,6 +112,11 @@ export class SkeletalAnimationComponent extends AnimationComponent {
return this._sockets;
}
set sockets (val) {
if (!this._useBakedAnimation) {
const animMgr = legacyCC.director.getAnimationManager() as AnimationManager;
animMgr.removeSockets(this.node, this._sockets);
animMgr.addSockets(this.node, val);
}
this._sockets = val;
this.rebuildSocketAnimations();
}
@@ -139,6 +145,8 @@ export class SkeletalAnimationComponent extends AnimationComponent {
comp.setUseBakedAnimation(this._useBakedAnimation);
}
}
if (this._useBakedAnimation) { (legacyCC.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); }
else { (legacyCC.director.getAnimationManager() as AnimationManager).addSockets(this.node, this._sockets); }
}
@property
@@ -150,6 +158,7 @@ export class SkeletalAnimationComponent extends AnimationComponent {
public onDestroy () {
super.onDestroy();
(legacyCC.director.root.dataPoolManager as DataPoolManager).jointAnimationInfo.destroy(this.node.uuid);
(legacyCC.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets);
}
public start () {
@@ -33,12 +33,12 @@ import { AnimationClip, IObjectCurveData } from './animation-clip';
import { HierarchyPath, isCustomPath, isPropertyPath } from './target-path';
import { legacyCC } from '../global-exports';
type CurveData = Vec3 | Quat | Mat4;
type CurveData = Vec3[] | Quat[] | Mat4[];
type ConvertedProps = Record<string, IPropertyCurve>;
interface IPropertyCurve {
keys: number;
values: CurveData[];
values: CurveData;
}
interface ISkeletalCurveInfo {
frames: number;
@@ -115,20 +115,27 @@ function convertToSkeletalCurves (clip: AnimationClip): IConvertedData {
function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, frames: number) {
const keys = clip.keys[curve.keys];
const values: CurveData[] = [];
const values: CurveData = [];
if (!keys || keys.length === 1) {
for (let i = 0; i < frames; i++) {
values[i] = curve.values[0].clone(); // never forget to clone
}
} else {
const isQuat = curve.values[0] instanceof Quat;
for (let i = 0, idx = 0; i < frames; i++) {
let time = i / clip.sample;
while (keys[idx] <= time) { idx++; }
if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; }
else if (idx === 0) { idx = 1; }
const from = curve.values[idx - 1].clone() as any;
from.lerp(curve.values[idx], clamp01((time - keys[idx - 1]) / (keys[idx] - keys[idx - 1])));
values[i] = from;
let time = i / clip.sample;
while (keys[idx] <= time) { idx++; }
if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; }
else if (idx === 0) { idx = 1; }
const from = curve.values[idx - 1].clone();
const denom = keys[idx] - keys[idx - 1];
const ratio = denom ? clamp01((time - keys[idx - 1]) / denom) : 1;
if (isQuat) {
(from as Quat).slerp(curve.values[idx] as Quat, ratio);
} else {
(from as Vec3).lerp(curve.values[idx] as Vec3, ratio);
}
values[i] = from;
}
}
curve.values = values;
@@ -30,13 +30,11 @@
import { SkinningModelComponent } from '../3d/framework/skinning-model-component';
import { Mat4, Quat, Vec3 } from '../math';
import { IAnimInfo, JointAnimationInfo } from '../renderer/models/skeletal-animation-utils';
import { deleteTransform, getTransform, getWorldMatrix, IJointTransform } from '../renderer/models/skinning-model';
import { Node } from '../scene-graph/node';
import { AnimationClip, IRuntimeCurve } from './animation-clip';
import { AnimationState } from './animation-state';
import { SkeletalAnimationComponent, Socket } from './skeletal-animation-component';
import { SkelAnimDataHub } from './skeletal-animation-data-hub';
import { getWorldTransformUntilRoot } from './transform-utils';
import { legacyCC } from '../global-exports';
const m4_1 = new Mat4();
@@ -50,7 +48,6 @@ interface ITransform {
interface ISocketData {
target: Node;
transform: IJointTransform;
frames: ITransform[];
}
@@ -103,7 +100,7 @@ export class SkeletalAnimationState extends AnimationState {
this._comps[i].uploadAnimation(this.clip);
}
} else {
this._sampleCurves = this._sampleCurvesRealTime;
this._sampleCurves = super._sampleCurves;
this.duration = this._clip.duration;
if (!this._curvesInited) {
this._curveLoaded = false;
@@ -114,44 +111,52 @@ export class SkeletalAnimationState extends AnimationState {
}
public rebuildSocketCurves (sockets: Socket[]) {
for (let i = 0; i < this._sockets.length; ++i) {
const socket = this._sockets[i];
deleteTransform(socket.transform.node);
}
this._sockets.length = 0;
if (!this._targetNode) { return null; }
const root = this._targetNode;
for (let i = 0; i < sockets.length; ++i) {
const socket = sockets[i];
const targetNode = root.getChildByPath(socket.path);
const transform = targetNode && getTransform(targetNode, root);
if (!transform || !socket.target) { continue; }
const sourceData = SkelAnimDataHub.getOrExtract(this.clip).data;
// find lowest joint animation
if (!socket.target) { continue; }
const clipData = SkelAnimDataHub.getOrExtract(this.clip);
let animPath = socket.path;
let source = sourceData[animPath];
let animNode = targetNode!;
let source = clipData.data[animPath];
let animNode = targetNode;
let downstream: Mat4 | undefined;
while (!source) {
const idx = animPath.lastIndexOf('/');
animPath = animPath.substring(0, idx);
source = sourceData[animPath];
animNode = animNode.parent!;
source = clipData.data[animPath];
if (animNode) {
if (!downstream) { downstream = Mat4.identity(m4_2); }
Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale);
Mat4.multiply(downstream, m4_1, downstream);
animNode = animNode.parent;
}
if (idx < 0) { break; }
}
// create animation data
const socketData: ISocketData = {
target: socket.target, transform,
frames: source.worldMatrix.values.map(() => ({ pos: new Vec3(), rot: new Quat(), scale: new Vec3() })),
};
const frames = source.worldMatrix.values as Mat4[];
const data = socketData.frames;
// apply downstream default pose
getWorldTransformUntilRoot(targetNode!, animNode, m4_1);
for (let j = 0; j < socketData.frames.length; j++) {
const m = frames[j]; const dst = data[j];
Mat4.toRTS(Mat4.multiply(m4_2, m, m4_1), dst.rot, dst.pos, dst.scale);
const curveData: Mat4[] | undefined = source && source.worldMatrix.values as Mat4[];
const frames = clipData.info.frames;
const transforms: ITransform[] = [];
for (let f = 0; f < frames; f++) {
let mat: Mat4;
if (curveData && downstream) { // curve & static two-way combination
mat = Mat4.multiply(m4_1, curveData[f], downstream);
} else if (curveData) { // there is a curve directly controlling the joint
mat = curveData[f];
} else if (downstream) { // fallback to default pose if no animation curve can be found upstream
mat = downstream;
} else { // bottom line: render the original mesh as-is
mat = Mat4.IDENTITY;
}
const tfm = { pos: new Vec3(), rot: new Quat(), scale: new Vec3() };
Mat4.toRTS(mat, tfm.rot, tfm.pos, tfm.scale);
transforms.push(tfm);
}
this._sockets.push(socketData);
this._sockets.push({
target: socket.target,
frames: transforms,
});
}
}
@@ -167,13 +172,4 @@ export class SkeletalAnimationState extends AnimationState {
target.setRTS(rot, pos, scale);
}
}
private _sampleCurvesRealTime (ratio: number) {
super._sampleCurves(ratio);
const stamp = legacyCC.director.getTotalFrames();
for (let i = 0; i < this._sockets.length; ++i) {
const { target, transform } = this._sockets[i];
target.matrix = getWorldMatrix(transform, stamp);
}
}
}
+8 -8
View File
@@ -4,14 +4,14 @@
import { ccclass, property } from '../data/class-decorator';
import { Node } from '../scene-graph/node';
import { error } from '../platform/debug';
import { warn } from '../platform/debug';
export type PropertyPath = string | number;
export interface ICustomTargetPath {
/**
* If errors are encountered, `null` should be returned.
* @param target
* @param target
*/
get(target: any): any;
}
@@ -37,12 +37,12 @@ export class HierarchyPath implements ICustomTargetPath {
public get (target: Node) {
if (!(target instanceof Node)) {
error(`Target of hierarchy path shall be Node.`);
warn(`Target of hierarchy path should be of type Node.`);
return null;
}
const result = target.getChildByPath(this.path);
if (!result) {
error(`Node "${target.name}" has no path "${this.path}"`);
warn(`Node "${target.name}" has no path "${this.path}"`);
return null;
}
return result;
@@ -60,12 +60,12 @@ export class ComponentPath implements ICustomTargetPath {
public get (target: Node) {
if (!(target instanceof Node)) {
error(`Target of component path shall be Node.`);
warn(`Target of component path should be of type Node.`);
return null;
}
const result = target.getComponent(this.component);
if (!result) {
error(`Node "${target.name}" has no component "${this.component}"`);
warn(`Node "${target.name}" has no component "${this.component}"`);
return null;
}
return result;
@@ -83,7 +83,7 @@ export function evaluatePath (root: any, ...paths: TargetPath[]) {
const path = paths[iPath];
if (isPropertyPath(path)) {
if (!(path in result)) {
error(`Target object has no property "${path}"`);
warn(`Target object has no property "${path}"`);
return null;
} else {
result = result[path];
@@ -96,4 +96,4 @@ export function evaluatePath (root: any, ...paths: TargetPath[]) {
}
}
return result;
}
}
+3 -36
View File
@@ -28,12 +28,8 @@
* @category asset
*/
import { ccclass, property, string } from '../data/class-decorator';
import { Event } from '../event';
import { CallbacksInvoker } from '../event/callbacks-invoker';
import { EventTarget } from '../event/event-target';
import { applyMixins, IEventTarget } from '../event/event-target-factory';
import { createMap } from '../utils/js-typed';
import { ccclass, property } from '../data/class-decorator';
import { Eventify } from '../event';
import { RawAsset } from './raw-asset';
import { Node } from '../scene-graph';
import { legacyCC } from '../global-exports';
@@ -60,7 +56,7 @@ import { legacyCC } from '../global-exports';
* @extends RawAsset
*/
@ccclass('cc.Asset')
export class Asset extends RawAsset implements IEventTarget {
export class Asset extends Eventify(RawAsset) {
/**
* @en Indicates whether its dependent raw assets can support deferred load if the owner scene (or prefab) is marked as `asyncLoadAssets`.
@@ -112,33 +108,6 @@ export class Asset extends RawAsset implements IEventTarget {
private _file: any = null;
constructor (...args: ConstructorParameters<typeof RawAsset>) {
super(...args);
}
/**
* @en
* IEventTarget implementations, they will be overwrote with the same implementation in EventTarget by applyMixins
* @zh
* IEventTarget 实现,它们将被 applyMixins 在 EventTarget 中用相同的实现覆盖
*/
// tslint:disable-next-line: member-ordering
public _callbackTable = createMap(true);
public on (type: string, callback: Function, target?: Object | undefined): Function | undefined {
return;
}
public off (type: string, callback?: Function | undefined, target?: Object | undefined): void {}
public targetOff (keyOrTarget?: string | Object | undefined): void {}
public once (type: string, callback: Function, target?: Object | undefined): Function | undefined {
return;
}
public dispatchEvent (event: Event): void {}
public hasEventListener (key: string, callback?: Function | undefined, target?: Object | undefined): boolean {
return false;
}
public removeAll (keyOrTarget?: string | Object | undefined): void {}
public emit (key: string, ...args: any[]): void {}
/**
* @en
* Returns the url of this asset's native object, if none it will returns an empty string.
@@ -265,8 +234,6 @@ export class Asset extends RawAsset implements IEventTarget {
public createNode? (callback: CreateNodeCallback): void;
}
applyMixins(Asset, [CallbacksInvoker, EventTarget]);
/**
* @param error - null or the error info
* @param node - the created node or null
+8 -9
View File
@@ -78,7 +78,7 @@ export class ImageAsset extends Asset {
* 此图像资源的图像数据。
*/
get data () {
const data = (this._nativeData as IMemoryImageSource)._data;
const data = this._nativeData && (this._nativeData as IMemoryImageSource)._data;
return ArrayBuffer.isView(data) ? data : this._nativeData as (HTMLCanvasElement | HTMLImageElement);
}
@@ -200,14 +200,13 @@ export class ImageAsset extends Asset {
}
}
// destroy() {
// if (cc.macro.CLEANUP_IMAGE_CACHE) {
// if (this._data instanceof HTMLImageElement) {
// this._data.src = "";
// cc.loader.removeItem(this._data.id);
// }
// }
// }
public destroy (): boolean {
if (this.data && this.data instanceof HTMLImageElement) {
this.data.src = "";
legacyCC.loader.removeItem(this.data.id);
}
return super.destroy();
}
// SERIALIZATION
+4 -2
View File
@@ -132,7 +132,9 @@ export class RenderingSubMesh {
* (用于射线检测的)几何信息。
*/
get geometricInfo () {
if (this._geometricInfo) { return this._geometricInfo; }
if (this._geometricInfo) {
return this._geometricInfo;
}
if (this.mesh === undefined) {
return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } };
}
@@ -747,7 +749,7 @@ export class Mesh extends Asset {
* @returns 是否验证成功。若验证选项为 `true` 且验证未通过则返回 `false`,否则返回 `true`。
*/
public merge (mesh: Mesh, worldMatrix?: Mat4, validate?: boolean): boolean {
if (validate !== undefined && validate) {
if (validate) {
if (!this.loaded || !mesh.loaded || !this.validateMergingMesh(mesh)) {
return false;
}
+6 -1
View File
@@ -8,7 +8,7 @@ import { Texture2D } from './texture-2d';
import { ImageAsset } from './image-asset';
import { samplerLib } from '../renderer/core/sampler-lib';
import { UBOMorph, UniformPositionMorphTexture, UniformNormalMorphTexture, UniformTangentMorphTexture } from '../pipeline/define';
import { warn } from '../platform/debug';
import { warn, warnID } from '../platform/debug';
import { MorphRendering, SubMeshMorph, Morph, MorphRenderingInstance } from './morph';
import { assertIsNonNullable, assertIsTrue } from '../data/utils/asserts';
import { nextPow2 } from '../math/bits';
@@ -43,6 +43,11 @@ export class StdMorphRendering implements MorphRendering {
continue;
}
if (subMeshMorph.targets.length > UBOMorph.MAX_MORPH_TARGET_COUNT) {
warnID(10002, UBOMorph.MAX_MORPH_TARGET_COUNT, subMeshMorph.targets.length);
continue;
}
if (preferCpuComputing) {
this._subMeshRenderings[iSubMesh] = new CpuComputing(
this._mesh,
+5
View File
@@ -13,6 +13,7 @@ import { ImageAsset } from './image-asset';
import { TextureBase } from './texture-base';
import { DEV } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { macro } from '../platform/macro';
const _regions: GFXBufferTextureCopy[] = [{
buffStride: 0,
@@ -151,6 +152,10 @@ export class SimpleTexture extends TextureBase {
}
this.uploadData(data, level, arrayIndex);
this._checkTextureLoaded();
if (macro.CLEANUP_IMAGE_CACHE) {
image.destroy();
}
};
if (image.loaded) {
upload();
+23 -9
View File
@@ -51,6 +51,19 @@ export class Skeleton extends Asset {
@property
private _hash = 0;
private _invBindposes: Mat4[] | null = null;
/**
* 所有关节的路径。该数组的长度始终与 `this.bindposes` 的长度相同。
*/
get joints () {
return this._joints;
}
set joints (value) {
this._joints = value;
}
/**
* 所有关节的绑定姿势矩阵。该数组的长度始终与 `this.joints` 的长度相同。
*/
@@ -62,15 +75,16 @@ export class Skeleton extends Asset {
this._bindposes = value;
}
/**
* 所有关节的路径。该数组的长度始终与 `this.bindposes` 的长度相同。
*/
get joints () {
return this._joints;
}
set joints (value) {
this._joints = value;
get inverseBindposes () {
if (!this._invBindposes) {
this._invBindposes = [];
for (let i = 0; i < this._bindposes.length; i++) {
const inv = new Mat4();
Mat4.invert(inv, this._bindposes[i]);
this._invBindposes.push(inv);
}
}
return this._invBindposes;
}
get hash () {
+19
View File
@@ -38,6 +38,8 @@ import { RenderTexture } from './render-texture';
import { TextureBase } from './texture-base';
import { EDITOR } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { ImageAsset, ImageSource } from './image-asset';
import { Texture2D } from './texture-2d';
const INSET_LEFT = 0;
const INSET_TOP = 1;
@@ -182,6 +184,23 @@ 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
*/
public static createWithImage (imageSourceOrImageAsset: ImageSource | ImageAsset) {
const img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset);
const tex = new Texture2D();
tex.image = img;
const spf = new SpriteFrame();
spf.texture = tex;
return spf;
}
/**
* @en
* Top border of the sprite.
+3 -2
View File
@@ -32,6 +32,7 @@ import { assertID, error } from '../platform/debug';
import { loader } from '../load-pipeline/CCLoader';
import { ImageAsset, ImageSource } from './image-asset';
import { DEBUG } from 'internal:constants';
import { IItem } from '../load-pipeline/loading-items';
export type LoadImageCallback<T> = (
this: T | undefined,
@@ -46,7 +47,7 @@ export type LoadImageCallback<T> = (
* @param target 回调函数的 `this` 参数。
* @returns 图像资源,返回时可能还未完成加载;加载完成或失败时会调用回调函数。
*/
export function loadImage<T> (url: string, callback?: LoadImageCallback<T>, target?: T) {
export function loadImage<T extends object> (url: string, callback?: LoadImageCallback<T>, target?: T) {
assertID(!!url, 3103);
let imageAsset = loader.getRes<ImageAsset>(url);
@@ -96,7 +97,7 @@ export function cacheImage (url: string, image: ImageSource) {
content: imageAsset,
complete: false,
};
loader.flowOut(item);
loader.flowOut(item as IItem);
return imageAsset;
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ export default class System implements ISchedulable {
return this._id;
}
public static sortByPriority (a:System, b:System) {
public static sortByPriority (a: System, b: System) {
if (a._priority < b._priority) {
return 1;
}
@@ -50,8 +50,8 @@ const _worldPos = new Vec3();
const CanvasClearFlag = Enum({
SOLID_COLOR: GFXClearFlag.ALL,
DEPTH_STENCIL: GFXClearFlag.DEPTH_STENCIL,
NONE: GFXClearFlag.NONE,
DEPTH_ONLY: GFXClearFlag.DEPTH_STENCIL,
DONT_CLEAR: GFXClearFlag.NONE,
});
const RenderMode = Enum({
@@ -232,7 +232,7 @@ export class CanvasComponent extends Component {
@property({
type: CanvasClearFlag,
})
protected _clearFlag = CanvasClearFlag.NONE;
protected _clearFlag = CanvasClearFlag.DONT_CLEAR;
@property
protected _color = new Color(0, 0, 0, 0);
@property({
@@ -43,6 +43,7 @@ const _vec2b = new Vec2();
const _mat4_temp = new Mat4();
const _matrix = new Mat4();
const _worldMatrix = new Mat4();
const _zeroMatrix = new Mat4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
const _rect = new Rect();
/**
* @en
@@ -397,6 +398,9 @@ export class UITransformComponent extends Component {
this.node.getWorldMatrix(_worldMatrix);
Mat4.invert(_mat4_temp, _worldMatrix);
if (Mat4.strictEquals(_mat4_temp, _zeroMatrix)) {
return false;
}
Vec2.transformMat4(testPt, cameraPt, _mat4_temp);
testPt.x += this._anchorPoint.x * w;
testPt.y += this._anchorPoint.y * h;
+76 -150
View File
@@ -25,7 +25,9 @@
*/
/**
* @category core/data
* @category core/_decorator
* @en Some TypeScript decorators for class and data definition
* @zh 一些用来定义类和数据的 TypeScript 装饰器
*/
// const FIX_BABEL6 = true;
@@ -36,17 +38,7 @@
// tslint:disable:max-line-length
// tslint:disable:no-empty-interface
/**
* Some JavaScript decorators which can be accessed with "cc._decorator".
* 一些 JavaScript 装饰器,目前可以通过 "cc._decorator" 来访问。
* (这些 API 仍不完全稳定,有可能随着 JavaScript 装饰器的标准实现而调整)
*
* @submodule _decorator
* @module _decorator
* @main
*/
// inspired by toddlxt (https://github.com/toddlxt/Creator-TypeScript-Boilerplate)
// inspired by @toddlxt (https://github.com/toddlxt/Creator-TypeScript-Boilerplate)
import * as js from '../utils/js';
import './class';
@@ -56,6 +48,7 @@ import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from './utils/
import { error, errorID, warnID } from '../platform/debug';
import { DEV } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { Component } from '../components/component';
// caches for class construction
const CACHE_KEY = '__ccclassCache__';
@@ -243,10 +236,9 @@ function genProperty (ctor, properties, propName, options, desc, cache) {
}
/**
* 将标准写法的 [ES6 Class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) 声明为 CCClass,具体用法请参阅[类型定义](/docs/creator/scripting/class/)。
*
* @method ccclass
* @param {String} [name] - The class name used for serialization.
* @en Declare a standard ES6 or TS Class as a CCClass, please refer to the [document](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html)
* @zh 将标准写法的 ES6 或者 TS Class 声明为 CCClass,具体用法请参阅[类型定义](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html)。
* @param name - The class name used for serialization.
* @example
* ```typescript
* const {ccclass} = cc._decorator;
@@ -264,8 +256,7 @@ function genProperty (ctor, properties, propName, options, desc, cache) {
* }
* ```
*/
export const ccclass = checkCtorArgument(function (ctor, name) {
export const ccclass: any | ((name?: string) => Function) = checkCtorArgument(function (ctor, name) {
// if (FIX_BABEL6) {
// eval('if(typeof _classCallCheck==="function"){_classCallCheck=function(){};}');
// }
@@ -315,25 +306,29 @@ export type SimplePropertyType = Function | string | typeof CCString | typeof CC
export type PropertyType = SimplePropertyType | SimplePropertyType[];
/**
* @zh cc 属性选项。
* @zh CCClass 属性选项。
* @en CCClass property options
*/
export interface IPropertyOptions extends IExposedAttributes {
}
/**
* @zh 标注属性为 cc 属性。
* @param options 选项。
* @en Declare as a CCClass property with options
* @zh 声明属性为 CCClass 属性。
* @param options property options
*/
export function property (options?: IPropertyOptions): PropertyDecorator;
/**
* @en Declare as a CCClass property with the property type
* @zh 标注属性为 cc 属性。<br/>
* 等价于`@property({type})`。
* @param type cc 属性的类型。
* @param type A {{ccclass}} type or a {{ValueType}}
*/
export function property (type: PropertyType): PropertyDecorator;
/**
* @en Declare as a CCClass property
* @zh 标注属性为 cc 属性。<br/>
* 等价于`@property()`。
*/
@@ -382,13 +377,11 @@ function createDummyDecorator (argCheckFunc) {
}
/**
* Makes a CCClass that inherit from component execute in edit mode.<br/>
* @en Makes a CCClass that inherit 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/>
* 允许继承自 Component 的 CCClass 在编辑器里执行。<br/>
* @zh 允许继承自 Component 的 CCClass 在编辑器里执行。<br/>
* 默认情况下,所有 Component 都只会在运行时才会执行,也就是说它们的生命周期回调不会在编辑器里触发。
*
* @method executeInEditMode
* @example
* ```typescript
* const {ccclass, executeInEditMode} = cc._decorator;
@@ -403,47 +396,46 @@ function createDummyDecorator (argCheckFunc) {
export const executeInEditMode = (DEV ? createEditorDecorator : createDummyDecorator)(checkCtorArgument, 'executeInEditMode', true);
/**
* 为声明为 CCClass 的组件添加依赖的其它组件。当组件添加到节点上时,如果依赖的组件不存在,引擎将会自动将依赖组件添加到同一个节点,防止脚本出错。该设置在运行时同样有效。
*
* @method requireComponent
* @param {Component} requiredComponent
* @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.
* @zh 为声明为 CCClass 的组件添加依赖的其它组件。当组件添加到节点上时,如果依赖的组件不存在,引擎将会自动将依赖组件添加到同一个节点,防止脚本出错。该设置在运行时同样有效。
* @param requiredComponent The required component type
* @example
* ```typescript
* const {ccclass, requireComponent} = cc._decorator;
* import {_decorator, SpriteComponent, Component} from cc;
* import {ccclass, requireComponent} from _decorator;
*
* @ccclass
* @requireComponent(cc.SpriteComponent)
* class SpriteCtrl extends cc.Component {
* @ccclass
* @requireComponent(SpriteComponent)
* class SpriteCtrl extends Component {
* // ...
* }
* ```
*/
export const requireComponent = createEditorDecorator(checkCompArgument, 'requireComponent');
export const requireComponent: (requiredComponent: Function) => Function = createEditorDecorator(checkCompArgument, 'requireComponent');
/**
* 将当前组件添加到组件菜单中,方便用户查找。例如 "Rendering/CameraCtrl"。
*
* @method menu
* @param {String} path - The path is the menu represented like a pathname.
* For example the menu could be "Rendering/CameraCtrl".
* @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".
* @example
* ```typescript
* const {ccclass, menu} = cc._decorator;
*
* @ccclass
* @menu("Rendering/CameraCtrl")
* @ccclass
* @menu("Rendering/CameraCtrl")
* class NewScript extends cc.Component {
* // ...
* }
* ```
*/
export const menu = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'menu');
export const menu: (path: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'menu');
/**
* 设置脚本生命周期方法调用的优先级。优先级小于 0 的组件将会优先执行,优先级大于 0 的组件将会延后执行。优先级仅会影响 onLoad, onEnable, start, update 和 lateUpdate,而 onDisable 和 onDestroy 不受影响。
*
* @method executionOrder
* @param {Number} order - The execution order of lifecycle methods for Component. Those less than 0 will execute before while those greater than 0 will execute after.
* @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.
* 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.
* @example
* ```typescript
* const {ccclass, executionOrder} = cc._decorator;
@@ -455,18 +447,17 @@ export const menu = (DEV ? createEditorDecorator : createDummyDecorator)(checkSt
* }
* ```
*/
export const executionOrder = createEditorDecorator(checkNumberArgument, 'executionOrder');
export const executionOrder: (priority: number) => Function = createEditorDecorator(checkNumberArgument, 'executionOrder');
/**
* 防止多个相同类型(或子类型)的组件被添加到同一个节点。
*
* @method disallowMultiple
* @en Forbid add multiple instances of the component to the same node.
* @zh 防止多个相同类型(或子类型)的组件被添加到同一个节点。
* @example
* ```typescript
* const {ccclass, disallowMultiple} = cc._decorator;
*
* @ccclass
* @disallowMultiple
* @ccclass
* @disallowMultiple
* class CameraCtrl extends cc.Component {
* // ...
* }
@@ -475,16 +466,15 @@ export const executionOrder = createEditorDecorator(checkNumberArgument, 'execut
export const disallowMultiple = (DEV ? createEditorDecorator : createDummyDecorator)(checkCtorArgument, 'disallowMultiple');
/**
* 当指定了 "executeInEditMode" 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。
*
* @method playOnFocus
* @en When {{executeInEditMode}} is set, this decorator will decide when a node with the component is on focus whether the editor should running in high FPS mode.
* @zh 当指定了 "executeInEditMode" 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。
* @example
* ```typescript
* const {ccclass, playOnFocus, executeInEditMode} = cc._decorator;
*
* @ccclass
* @executeInEditMode
* @playOnFocus
* @ccclass
* @executeInEditMode
* @playOnFocus
* class CameraCtrl extends cc.Component {
* // ...
* }
@@ -493,28 +483,26 @@ export const disallowMultiple = (DEV ? createEditorDecorator : createDummyDecora
export const playOnFocus = (DEV ? createEditorDecorator : createDummyDecorator)(checkCtorArgument, 'playOnFocus');
/**
* 自定义当前组件在 **属性检查器** 中渲染时所用的网页 url。
*
* @method inspector
* @param {String} url
* @en Use a customized inspector page in the **inspector**
* @zh 自定义当前组件在 **属性检查器** 中渲染时所用的 UI 页面描述。
* @param url The url of the page definition in js
* @example
* ```typescript
* const {ccclass, inspector} = cc._decorator;
*
* @ccclass
* @inspector("packages://inspector/inspectors/comps/camera-ctrl.js")
* @ccclass
* @inspector("packages://inspector/inspectors/comps/camera-ctrl.js")
* class NewScript extends cc.Component {
* // ...
* }
* ```
*/
export const inspector = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'inspector');
export const inspector: (url: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'inspector');
/**
* 自定义当前组件在编辑器中显示的图标 url。
*
* @method icon
* @param {String} url
* @en Define the icon of the component.
* @zh 自定义当前组件在编辑器中显示的图标 url。
* @param url
* @private
* @example
* ```typescript
@@ -527,117 +515,55 @@ export const inspector = (DEV ? createEditorDecorator : createDummyDecorator)(ch
* }
* ```
*/
export const icon = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'icon');
export const icon: (url: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'icon');
/**
* 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。
*
* @method help
* @param {String} url
* @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.
* @zh 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。
* @param url The url of the help documentation
* @example
* ```typescript
* const {ccclass, help} = cc._decorator;
*
* @ccclass
* @help("app://docs/html/components/spine.html")
* @ccclass
* @help("app://docs/html/components/spine.html")
* class NewScript extends cc.Component {
* // ...
* }
* ```
*/
export const help = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'help');
export const help: (url: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'help');
// Other Decorators
/**
* @en
* NOTE:<br>
* The old mixins implemented in cc.Class(ES5) behaves exact the same as multiple inheritance.
* But since ES6, class constructor can't be function-called and class methods become non-enumerable,
* so we can not mix in ES6 Classes.<br>
* See:<br>
* [https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32](https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32)<br>
* One possible solution (but IDE unfriendly):<br>
* [http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes](http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/)<br>
* <br>
* NOTE:<br>
* You must manually call mixins constructor, this is different from cc.Class(ES5).
* @zh
* *注意:<br>
 * 在cc.Class(ES5)中实现的旧mixin的行为与多重继承完全相同。
 * 但是从ES6开始,类构造函数不能被函数调用,类方法变得不可枚举,
 * 所以我们不能混合使用ES6类。<br>
 * 参看:<br>
 * [https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32](https://esdiscuss.org/topic/traits-are-now-impossible-in-ES6-直到-ES7,因为-rev32)点击
 * 一种可能的解决方案(但对 IDE 不友好):<br>
 * [http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes](http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/)结果
 * <br>
 * 注意:<br>
 * 您必须手动调用mixins构造函数,这与cc.Class(ES5)不同。
*
* @method mixins
* @param {Function} ...ctor - constructors to mix, only support ES5 constructors or classes defined by using `cc.Class`,
* not support ES6 Classes.
* @example
* ```typescript
* const {ccclass, mixins} = cc._decorator;
*
* class Animal { ... }
*
* const Fly = cc.Class({
* constructor () { ... }
* });
*
* @ccclass
* @mixins(cc.EventTarget, Fly)
* class Bird extends Animal {
* constructor () {
* super();
*
* // You must manually call mixins constructor, this is different from cc.Class(ES5)
* cc.EventTarget.call(this);
* Fly.call(this);
* }
* // ...
* }
* ```
*/
export function mixins (...constructors: Function[]) {
const mixins: Function[] = [];
for (let i = 0; i < constructors.length; i++) {
mixins[i] = constructors[i];
}
return function (ctor) {
const cache = getClassCache(ctor, 'mixins');
if (cache) {
getSubDict(cache, 'proto').mixins = mixins;
}
};
}
/**
* 将该属性标记为 cc 整数。
* @en Declare the property as integer
* @zh 将该属性标记为整数。
*/
export const integer = type(CCInteger);
/**
* 将该属性标记为 cc 浮点数。
* @en Declare the property as float
* @zh 将该属性标记为浮点数。
*/
export const float = type(CCFloat);
/**
* 将该属性标记为 cc 布尔值。
* @en Declare the property as boolean
* @zh 将该属性标记为布尔值。
*/
export const boolean = type(CCBoolean);
/**
* 将该属性标记为 cc 字符串。
* @en Declare the property as string
* @zh 将该属性标记为字符串。
*/
export const string = type(CCString);
/**
* 标记该属性的类型。
* @param type 指定类型。
* @en Declare the property as the given type
* @zh 标记该属性的类型。
* @param type
*/
export function type (type: Function): PropertyDecorator;
+1 -90
View File
@@ -25,7 +25,7 @@
*/
/**
* @category core/data
* @hidden
*/
// tslint:disable:only-arrow-functions
@@ -895,95 +895,6 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6?:
});
}
/**
* @en Defines a CCClass using the given specification
* @zh 定义一个 CCClass,传入参数必须是一个包含类型参数的字面量对象
*
* @method Class
*
* @param {Object} [options]
* @param {String} [options.name] - The class name used for serialization.
* @param {Function} [options.extends] - The base class.
* @param {Function} [options.ctor] - The constructor.
* @param {Function} [options.__ctor__] - The same as ctor, but less encapsulated.
* @param {Object} [options.properties] - The property definitions.
* @param {Object} [options.statics] - The static members.
* @param {Function[]} [options.mixins]
*
* @param {Object} [options.editor] - attributes for Component listed below.
* @param {Boolean} [options.editor.executeInEditMode=false] - Allows the current component to run in edit mode. By default, all components are executed only at runtime, meaning that they will not have their callback functions executed while the Editor is in edit mode.
* @param {Function} [options.editor.requireComponent] - Automatically add required component as a dependency.
* @param {String} [options.editor.menu] - The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera".
* @param {Number} [options.editor.executionOrder=0] - The execution order of lifecycle methods for Component. Those less than 0 will execute before while those greater than 0 will execute after. The order will only affect onLoad, onEnable, start, update and lateUpdate while onDisable and onDestroy will not be affected.
* @param {Boolean} [options.editor.disallowMultiple] - If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node.
* @param {Boolean} [options.editor.playOnFocus=false] - This property is only available when executeInEditMode is set. If specified, the editor's scene view will keep updating this node in 60 fps when it is selected, otherwise, it will update only if necessary.
* @param {String} [options.editor.inspector] - Customize the page url used by the current component to render in the Properties.
* @param {String} [options.editor.icon] - Customize the icon that the current component displays in the editor.
* @param {String} [options.editor.help] - The custom documentation URL
*
* @param {Function} [options.update] - lifecycle method for Component, see {{#crossLink "Component/update:method"}}{{/crossLink}}
* @param {Function} [options.lateUpdate] - lifecycle method for Component, see {{#crossLink "Component/lateUpdate:method"}}{{/crossLink}}
* @param {Function} [options.onLoad] - lifecycle method for Component, see {{#crossLink "Component/onLoad:method"}}{{/crossLink}}
* @param {Function} [options.start] - lifecycle method for Component, see {{#crossLink "Component/start:method"}}{{/crossLink}}
* @param {Function} [options.onEnable] - lifecycle method for Component, see {{#crossLink "Component/onEnable:method"}}{{/crossLink}}
* @param {Function} [options.onDisable] - lifecycle method for Component, see {{#crossLink "Component/onDisable:method"}}{{/crossLink}}
* @param {Function} [options.onDestroy] - lifecycle method for Component, see {{#crossLink "Component/onDestroy:method"}}{{/crossLink}}
* @param {Function} [options.onFocusInEditor] - lifecycle method for Component, see {{#crossLink "Component/onFocusInEditor:method"}}{{/crossLink}}
* @param {Function} [options.onLostFocusInEditor] - lifecycle method for Component, see {{#crossLink "Component/onLostFocusInEditor:method"}}{{/crossLink}}
* @param {Function} [options.resetInEditor] - lifecycle method for Component, see {{#crossLink "Component/resetInEditor:method"}}{{/crossLink}}
* @param {Function} [options.onRestore] - for Component only, see {{#crossLink "Component/onRestore:method"}}{{/crossLink}}
* @param {Function} [options._getLocalBounds] - for Component only, see {{#crossLink "Component/_getLocalBounds:method"}}{{/crossLink}}
*
* @return {Function} - the created class
*
* @example
* ```typescript
* // define base class
* var Node = cc.Class();
* // define sub class
* var Sprite = cc.Class({
* name: 'Sprite',
* extends: Node,
*
* ctor: function () {
* this.url = "";
* this.id = 0;
* },
*
* statics: {
* // define static members
* count: 0,
* getBounds: function (spriteList) {
* // compute bounds...
* }
* },
*
* properties {
* width: {
* default: 128,
* type: 'Integer',
* tooltip: 'The width of sprite'
* },
* height: 128,
* size: {
* get: function () {
* return cc.v2(this.width, this.height);
* }
* }
* },
*
* load: function () {
* // load this.url...
* };
* });
*
* // instantiate
*
* var obj = new Sprite();
* obj.url = 'sprite.png';
* obj.load();
* ```
*/
function CCClass (options) {
options = options || {};
+1 -1
View File
@@ -25,7 +25,7 @@
*/
/**
* @category core/data
* @hidden
*/
import { warnID } from '../platform/debug';
+1 -1
View File
@@ -25,7 +25,7 @@
*/
/**
* @category core/data
* @hidden
*/
// Some helper methods for compile instantiation code
+10 -10
View File
@@ -35,6 +35,8 @@ import { js } from '../utils';
import { errorID, warn } from '../platform/debug';
import { DEV } from 'internal:constants';
import { legacyCC } from '../global-exports';
import Prefab from '../assets/prefab';
import { Node } from '../scene-graph/node';
// @ts-ignore
const Destroyed = CCObject.Flags.Destroyed;
@@ -46,12 +48,9 @@ const objsToClearTmpVar: any = []; // used to reset _iN$t variable
/**
* @en Clones the object `original` and returns the clone, or instantiate a node from the Prefab.
* @zh 克隆指定的任意类型的对象,或者从 Prefab 实例化出新节点。
*
* (Instantiate 时,function 和 dom 等非可序列化对象会直接保留原有引用,Asset 会直接进行浅拷贝,可序列化类型会进行深拷贝。)
*
* @method instantiate
* @param {Prefab|Node|Object} original - An existing object that you want to make a copy of.
* @return {Node|Object} the newly instantiated object
* @param original - An existing object that you want to make a copy of.
* @return {} the newly instantiated object
* @example
* ```typescript
* // instantiate node from prefab
@@ -64,7 +63,7 @@ const objsToClearTmpVar: any = []; // used to reset _iN$t variable
* node.parent = scene;
* ```
*/
function instantiate (original, internal_force?) {
function instantiate (original: Prefab|Node|Object, internal_force?: Node|Object): Node | null {
if (!internal_force) {
if (typeof original !== 'object' || Array.isArray(original)) {
if (DEV) {
@@ -98,8 +97,10 @@ function instantiate (original, internal_force?) {
// @param {Object} [instantiated] - If supplied, _instantiate just need to initialize the instantiated object,
// no need to create new object by itself.
// @returns {Object} - the instantiated object
// @ts-ignore
if (original._instantiate) {
legacyCC.game._isCloning = true;
// @ts-ignore
clone = original._instantiate();
legacyCC.game._isCloning = false;
return clone;
@@ -119,16 +120,15 @@ function instantiate (original, internal_force?) {
return clone;
}
/**
/*
* @en
* Do instantiate object, the object to instantiate must be non-nil.
* @zh
* 这是一个通用的 instantiate 方法,可能效率比较低。
* 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。
* 值得注意的是,这个方法不可重入。
*
* @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。
* @param {Node} [parent] - 只有在该对象下的场景物体会被克隆。
* @param obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。
* @param parent - 只有在该对象下的场景物体会被克隆。
* @return {Object}
* @private
*/
+6 -23
View File
@@ -156,9 +156,6 @@ function compileDestruct (obj, ctor) {
* The base class of most of all the objects in Fireball.
* @zh
* 大部分对象的基类。
* @class Object
*
* @main
* @private
*/
class CCObject {
@@ -236,8 +233,6 @@ class CCObject {
* 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。<br>
* 因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。<br>
* 如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。
*
* @property {Boolean} isValid
* @default true
* @readOnly
* @example
@@ -251,7 +246,7 @@ class CCObject {
* cc.log(node.isValid); // false, destroyed in the end of last frame
* ```
*/
get isValid () {
get isValid (): boolean {
return !(this._objFlags & Destroyed);
}
@@ -265,7 +260,7 @@ class CCObject {
* 销毁该对象,并释放所有它对其它对象的引用。<br/>
* 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。
* 您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
* @return {Boolean} whether it is the first time the destroy being called
* @return whether it is the first time the destroy being called
* @example
* ```
* obj.destroy();
@@ -381,7 +376,7 @@ if (EDITOR) {
}
});
/**
/*
* The customized serialization for this object. (Editor Only)
* @method _serialize
* @param {Boolean} exporting
@@ -392,7 +387,7 @@ if (EDITOR) {
prototype._serialize = null;
}
/**
/*
* Init this object from the custom serialized data.
* @method _deserialize
* @param {Object} data - the serialized json data
@@ -401,7 +396,7 @@ if (EDITOR) {
*/
// @ts-ignore
prototype._deserialize = null;
/**
/*
* Called before the object being destroyed.
* @method _onPreDestroy
* @private
@@ -414,7 +409,6 @@ CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 });
/**
* Bit mask that controls object states.
* @enum Object.Flags
* @static
* @private
*/
js.value(CCObject, 'Flags', {
@@ -425,14 +419,12 @@ js.value(CCObject, 'Flags', {
/**
* @en The object will not be saved.
* @zh 该对象将不会被保存。
* @property {Number} DontSave
*/
DontSave,
/**
* @en The object will not be saved when building a player.
* @zh 构建项目时,该对象将不会被保存。
* @property {Number} EditorOnly
*/
EditorOnly,
@@ -455,7 +447,6 @@ js.value(CCObject, 'Flags', {
/**
* @en The node is deactivating.
* @zh 节点正在反激活的过程中。
* @property Deactivating
* @private
*/
Deactivating,
@@ -463,8 +454,6 @@ js.value(CCObject, 'Flags', {
/**
* @en The lock node, when the node is locked, cannot be clicked in the scene.
* @zh 锁定节点,锁定后场景内不能点击
*
* @property LockedInEditor
* @private
*/
LockedInEditor,
@@ -485,7 +474,6 @@ js.value(CCObject, 'Flags', {
/// **
// * @en This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags().
// * @zh 该标记只读,它只能被用作 scene.addEntity()的一个参数。
// * @property {Number} HideInEditor
// */
HideInHierarchy,
@@ -496,7 +484,6 @@ js.value(CCObject, 'Flags', {
// * @zh
// * 在游戏视图,层级,场景视图等等...中隐藏该对象。
// * 该标记只读,它只能被用作 scene.addEntity()的一个参数。
// * @property {Number} Hide
// */
// Hide: Hide,
@@ -519,11 +506,7 @@ js.value(CCObject, 'Flags', {
IsSizeLocked,
});
/**
* @module cc
*/
/**
/*
* @en
* Checks whether the object is non-nil and not yet destroyed.<br>
* When an object's `destroy` is called, it is actually destroyed after the end of this frame.
+16 -5
View File
@@ -227,7 +227,7 @@ export class CallbacksInvoker {
* @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target
* @param keyOrTarget - The event type or target with which the listeners will be removed
*/
public removeAll (keyOrTarget?: string | Object) {
public removeAll (keyOrTarget: string | Object) {
if (typeof keyOrTarget === 'string') {
// remove by key
const list = this._callbackTable[keyOrTarget];
@@ -298,9 +298,13 @@ export class CallbacksInvoker {
* @zh 派发一个指定事件,并传递需要的参数
* @en Trigger an event directly with the event name and necessary arguments.
* @param key - event type
* @param args - Arguments when the event triggered
* @param arg0 - The first argument to be passed to the callback
* @param arg1 - The second argument to be passed to the callback
* @param arg2 - The third argument to be passed to the callback
* @param arg3 - The fourth argument to be passed to the callback
* @param arg4 - The fifth argument to be passed to the callback
*/
public emit (key: string, ...args: any[]) {
public emit (key: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) {
const list: CallbackList = this._callbackTable[key]!;
if (list) {
const rootInvoker = !list.isInvoking;
@@ -317,10 +321,10 @@ export class CallbacksInvoker {
this.off(key, callback, target);
}
if (target) {
callback.call(target, ...args);
callback.call(target, arg0, arg1, arg2, arg3, arg4);
}
else {
callback(...args);
callback(arg0, arg1, arg2, arg3, arg4);
}
}
}
@@ -333,6 +337,13 @@ export class CallbacksInvoker {
}
}
}
/**
* 移除所有回调。
*/
public clear () {
this._callbackTable = createMap(true);
}
}
if (TEST) {
+11 -155
View File
@@ -31,168 +31,24 @@
import * as js from '../utils/js';
import { CallbacksInvoker } from './callbacks-invoker';
import { legacyCC } from '../global-exports';
import { Eventify } from './eventify';
const fastRemove = js.array.fastRemove;
export interface ITargetImpl extends Object {
__eventTargets?: Object[];
node?: ITargetImpl;
}
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class Empty {};
/**
* !#en
* @en
* EventTarget is an object to which an event is dispatched when something has occurred.
* Entity are the most common event targets, but other objects can be event targets too.
* [[Node]]s are the most common event targets, but other objects can be event targets too.
* If a class cannot extend from EventTarget, it can consider using [[Eventify]].
*
* Event targets are an important part of the Fireball event model.
* The event target serves as the focal point for how events flow through the scene graph.
* When an event such as a mouse click or a keypress occurs, Fireball dispatches an event object
* into the event flow from the root of the hierarchy. The event object then makes its way through
* the scene graph until it reaches the event target, at which point it begins its return trip through
* the scene graph. This round-trip journey to the event target is conceptually divided into three phases:
* - The capture phase comprises the journey from the root to the last node before the event target's node
* - The target phase comprises only the event target node
* - The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the tree
* See also: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
*
* Event targets can implement the following methods:
* - _getCapturingTargets
* - _getBubblingTargets
*
* If a class cannot extend from EventTarget, it can consider implements IEventTarget interface.
*
* !#zh
* 事件目标是具有注册监听器、派发事件能力的类,Node 是最常见的事件目标,
* @zh
* 事件目标是具有注册监听器、派发事件能力的类,[[Node]] 是最常见的事件目标,
* 但是其他类也可以继承自事件目标以获得管理监听器和派发事件的能力。
* 如果无法继承自 EventTarget,也可以考虑自实现 IEventTarget
* 如果无法继承自 EventTarget,也可以使用 [[Eventify]]
*/
export class EventTarget extends CallbacksInvoker {
/**
* @en
* Register an callback of a specific event type on the EventTarget.
* This type of event should be triggered via `emit`.
* @zh
* 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
* @return - Just returns the incoming callback so you can save the anonymous function easier.
* @example
* eventTarget.on('fire', function () {
* cc.log("fire in the hole");
* }, node);
*/
public on (type: string, callback: Function, target?: Object) {
if (!callback) {
legacyCC.errorID(6800);
return;
}
export const EventTarget = Eventify(Empty);
if (!this.hasEventListener(type, callback, target)) {
super.on(type, callback, target);
const targetImpl = target as ITargetImpl;
if (target) {
if (targetImpl.__eventTargets) {
targetImpl.__eventTargets.push(this);
} else if (targetImpl.node && targetImpl.node.__eventTargets) {
targetImpl.node.__eventTargets.push(this);
}
}
}
return callback;
}
/**
* @en
* Removes the listeners previously registered with the same type, callback, target and or useCapture,
* if only type is passed as parameter, all listeners registered with that type will be removed.
* @zh
* 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。
*
* @param type - A string representing the event type being removed.
* @param callback - The callback to remove.
* @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
* @example
* // register fire eventListener
* var callback = eventTarget.on('fire', function () {
* cc.log("fire in the hole");
* }, target);
* // remove fire event listener
* eventTarget.off('fire', callback, target);
* // remove all fire event listeners
* eventTarget.off('fire');
*/
public off (type: string, callback?: Function, target?: Object) {
if (!callback) {
this.removeAll(type);
}
else {
super.off(type, callback, target);
const targetImpl = target as ITargetImpl;
if (target) {
if (targetImpl.__eventTargets) {
fastRemove(targetImpl.__eventTargets, this);
} else if (targetImpl.node && targetImpl.node.__eventTargets) {
fastRemove(targetImpl.node.__eventTargets, this);
}
}
}
}
/**
* @en Removes all callbacks previously registered with the same target (passed as parameter).
* This is not for removing all listeners in the current event target,
* and this is not for removing all listeners the target parameter have registered.
* It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter.
* @zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。
* 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。
* 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。
* @param target - The target to be searched for all related listeners
*/
public targetOff (keyOrTarget?: string | Object) {
this.removeAll(keyOrTarget);
}
/**
* @en
* Register an callback of a specific event type on the EventTarget,
* the callback will remove itself after the first time it is triggered.
* @zh
* 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
* @example
* eventTarget.once('fire', function () {
* cc.log("this is the callback and will be invoked only once");
* }, node);
*/
public once (type: string, callback: Function, target?: Object) {
if (!callback) {
legacyCC.errorID(6800);
return;
}
if (!this.hasEventListener(type, callback, target)) {
super.on(type, callback, target, true);
const targetImpl = target as ITargetImpl;
if (target) {
if (targetImpl.__eventTargets) {
targetImpl.__eventTargets.push(this);
} else if (targetImpl.node && targetImpl.node.__eventTargets) {
targetImpl.node.__eventTargets.push(this);
}
}
}
return callback;
}
}
export type EventTarget = InstanceType<typeof EventTarget>;
legacyCC.EventTarget = EventTarget;
+207
View File
@@ -0,0 +1,207 @@
/**
* @category event
*/
import { fastRemove } from '../utils/array';
import { CallbacksInvoker } from './callbacks-invoker';
import { createMap } from '../utils/js';
type Constructor<T = {}> = new (...args: any[]) => T;
type EventType = string;
const {
prototype: {
on: callbacksInvokerOn,
off: callbacksInvokerOff,
},
} = CallbacksInvoker;
/**
* @zh
* 实现该接口的对象具有处理事件的能力。
* @en
* Objects those implement this interface have essentially the capability to process events.
*/
export interface IEventified {
/**
* @zh 检查指定事件是否已注册回调。
* @en Checks whether there is correspond event listener registered on the given event.
* @param type - Event type.
* @param callback - Callback function when event triggered.
* @param target - Callback callee.
*/
hasEventListener (type: string, callback?: Function, target?: object): boolean;
/**
* @en
* Register an callback of a specific event type on the EventTarget.
* This type of event should be triggered via `emit`.
* @zh
* 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param thisArg - The target (this object) to invoke the callback, can be null
* @return - Just returns the incoming callback so you can save the anonymous function easier.
* @example
* eventTarget.on('fire', function () {
* cc.log("fire in the hole");
* }, node);
*/
on<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any): typeof callback;
/**
* @en
* Register an callback of a specific event type on the EventTarget,
* the callback will remove itself after the first time it is triggered.
* @zh
* 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
* @example
* eventTarget.once('fire', function () {
* cc.log("this is the callback and will be invoked only once");
* }, node);
*/
once<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any): typeof callback;
/**
* @en
* Removes the listeners previously registered with the same type, callback, target and or useCapture,
* if only type is passed as parameter, all listeners registered with that type will be removed.
* @zh
* 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。
*
* @param type - A string representing the event type being removed.
* @param callback - The callback to remove.
* @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
* @example
* // register fire eventListener
* var callback = eventTarget.on('fire', function () {
* cc.log("fire in the hole");
* }, target);
* // remove fire event listener
* eventTarget.off('fire', callback, target);
* // remove all fire event listeners
* eventTarget.off('fire');
*/
off<TFunction extends Function> (type: EventType, callback?: TFunction, thisArg?: any): void;
/**
* @en Removes all callbacks previously registered with the same target (passed as parameter).
* This is not for removing all listeners in the current event target,
* and this is not for removing all listeners the target parameter have registered.
* It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter.
* @zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。
* 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。
* 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。
* @param typeOrTarget - The target to be searched for all related listeners
*/
targetOff (typeOrTarget: string | object): void;
/**
* @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。
* @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target
* @param typeOrTarget - The event type or target with which the listeners will be removed
*/
removeAll (typeOrTarget: string | object): void;
/**
* @zh 派发一个指定事件,并传递需要的参数
* @en Trigger an event directly with the event name and necessary arguments.
* @param type - event type
* @param args - Arguments when the event triggered
*/
emit (type: EventType, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void;
}
/**
* @en Generate a new class from the given base class, after polyfill all functionalities in [[IEventified]] as if it's extended from [[EventTarget]]
* @zh 生成一个类,该类继承自指定的基类,并以和 [[EventTarget]] 等同的方式实现了 [[IEventified]] 的所有接口。
* @param base The base class
* @example
* ```ts
* class Base { say() { console.log('Hello!'); } }
* class MyClass extends Eventify(Base) { }
* function (o: MyClass) {
* o.say(); // Ok: Extend from `Base`
* o.emit('sing', 'The ghost'); // Ok: `MyClass` implements IEventified
* }
* ```
*/
export function Eventify<TBase> (base: Constructor<TBase>): Constructor<TBase & IEventified> {
class Eventified extends (base as unknown as any) {
private _callbackTable = createMap(true);
public on<Callback extends Function> (type: EventType, callback: Callback, target?: object) {
if (!this.hasEventListener(type, callback, target)) {
callbacksInvokerOn.call(this, type, callback, target);
if (target) {
this._registerThisIntoTarget(target);
}
}
return callback;
}
public once<Callback extends Function> (type: EventType, callback: Callback, target?: object) {
if (!this.hasEventListener(type, callback, target)) {
callbacksInvokerOn.call(this, type, callback, target, true);
if (target) {
this._registerThisIntoTarget(target);
}
}
return callback;
}
public off (type: EventType, callback?: Function, target?: object) {
if (!callback) {
this.removeAll(type);
} else {
callbacksInvokerOff.call(this, type, callback, target);
if (target) {
this._unregisterThisIntoTarget(target);
}
}
}
public targetOff (typeOrTarget: string | object) {
this.removeAll(typeOrTarget);
}
private _registerThisIntoTarget (target: ITargetImpl) {
if (target.__eventTargets) {
target.__eventTargets.push(this);
} else if (target.node && target.node.__eventTargets) {
target.node.__eventTargets.push(this);
}
}
private _unregisterThisIntoTarget (target: ITargetImpl) {
if (target.__eventTargets) {
fastRemove(target.__eventTargets, this);
} else if (target.node && target.node.__eventTargets) {
fastRemove(target.node.__eventTargets, this);
}
}
};
// Mixin with `CallbacksInvokers`'s prototype
const propertyDescriptors = Object.getOwnPropertyDescriptors(CallbacksInvoker.prototype);
for (const propertyName in propertyDescriptors) {
if (!(propertyName in Eventified.prototype)) {
Object.defineProperty(Eventified.prototype, propertyName, propertyDescriptors[propertyName]);
}
}
return Eventified as unknown as any;
}
interface ITargetImpl extends Object {
__eventTargets?: any[];
node?: ITargetImpl;
}
+1
View File
@@ -30,3 +30,4 @@
export { default as Event } from './event';
export { EventTarget } from './event-target';
export { Eventify } from './eventify';
+35 -14
View File
@@ -434,7 +434,7 @@ export class Game extends EventTarget {
this._paused = true;
// Pause main loop
if (this._intervalId) {
window.cancelAnimationFrame(this._intervalId);
window.cAF(this._intervalId);
this._intervalId = 0;
}
// Because JSB platforms never actually stops the swap chain,
@@ -443,12 +443,12 @@ export class Game extends EventTarget {
let swapbuffers = 3;
const cb = () => {
if (--swapbuffers > 1) {
window.requestAnimationFrame(cb);
window.rAF(cb);
}
const root = legacyCC.director.root;
root.frameMove(0); root.device.present();
};
window.requestAnimationFrame(cb);
window.rAF(cb);
}
}
@@ -633,7 +633,7 @@ export class Game extends EventTarget {
else {
this.setRenderPipeline(asset);
}
this.emit(Game.EVENT_GAME_INITED);
this._safeEmit(Game.EVENT_GAME_INITED);
if (useSplash) {
splashScreen.loadFinish = true;
}
@@ -643,7 +643,7 @@ export class Game extends EventTarget {
});
}
else {
this.emit(Game.EVENT_GAME_INITED);
this._safeEmit(Game.EVENT_GAME_INITED);
if (useSplash) {
splashScreen.loadFinish = true;
}
@@ -735,20 +735,27 @@ export class Game extends EventTarget {
if (JSB) {
jsb.setPreferredFramesPerSecond(frameRate);
window.rAF = window.requestAnimationFrame;
window.cAF = window.cancelAnimationFrame;
}
else {
else {
if (this._intervalId) {
window.cAF(this._intervalId);
this._intervalId = 0;
}
if (frameRate !== 60 && frameRate !== 30) {
window.requestAnimationFrame = this._stTime;
window.cancelAnimationFrame = this._ctTime;
window.rAF = this._stTime;
window.cAF = this._ctTime;
}
else {
window.requestAnimationFrame = window.requestAnimationFrame ||
window.rAF = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
this._stTime;
window.cancelAnimationFrame = window.cancelAnimationFrame ||
window.cAF = window.cancelAnimationFrame ||
window.cancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
@@ -784,7 +791,7 @@ export class Game extends EventTarget {
callback = (time: number) => {
if (this._paused) { return; }
this._intervalId = window.requestAnimationFrame(callback);
this._intervalId = window.rAF(callback);
if (!JSB && frameRate === 30) {
skip = !skip;
if (skip) {
@@ -795,11 +802,11 @@ export class Game extends EventTarget {
};
if (this._intervalId) {
window.cancelAnimationFrame(this._intervalId);
window.cAF(this._intervalId);
this._intervalId = 0;
}
this._intervalId = window.requestAnimationFrame(callback);
this._intervalId = window.rAF(callback);
this._paused = false;
}
@@ -1015,7 +1022,21 @@ export class Game extends EventTarget {
}
this._rendererInitialized = true;
this.emit(Game.EVENT_RENDERER_INITED);
this._safeEmit(Game.EVENT_RENDERER_INITED);
}
private _safeEmit (event) {
if (EDITOR) {
try {
this.emit(event);
}
catch (e) {
console.warn(e);
}
}
else {
this.emit(event);
}
}
}
+92 -73
View File
@@ -324,17 +324,34 @@ const ray_capsule = (function () {
* ray-subMesh intersect detect.
* @zh
* 射线和子三角网格的相交性检测。
* @param {ray} ray
* @param {RenderingSubMesh} subMesh
* @param {IRaySubMeshOptions} options
* @return {number} 0 or !0
*/
const ray_subMesh = (function () {
const tri = triangle.create();
const deOpt: IRaySubMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY };
const tr: IRaySubMeshResult = { distance: 0, vertexIndex0: 0, vertexIndex1: 0, vertexIndex2: 0 };
let minDis = 0;
const broadphase = (ray: ray, submesh: RenderingSubMesh) => {
const min = submesh.geometricInfo.boundingBox.min;
const max = submesh.geometricInfo.boundingBox.max;
return ray_aabb2(ray, min, max);
const fillResult = (m: ERaycastMode, d: number, i0: number, i1: number, i2: number, r?: IRaySubMeshResult[]) => {
if (m == ERaycastMode.CLOSEST) {
if (minDis > d || minDis == 0) {
minDis = d;
if (r) {
if (r.length == 0) {
r.push({ distance: d, vertexIndex0: i0 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 });
} else {
r[0].distance = d; r[0].vertexIndex0 = i0 / 3; r[0].vertexIndex1 = i1 / 3; r[0].vertexIndex2 = i2 / 3;
}
}
}
} else {
minDis = d;
if (r) r.push({ distance: d, vertexIndex0: i0 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 });
}
}
const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, ray: ray, opt: IRaySubMeshOptions) => {
if (pm === GFXPrimitiveMode.TRIANGLE_LIST) {
const cnt = ib.length;
@@ -346,25 +363,9 @@ const ray_subMesh = (function () {
Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
const dist = intersect.ray_triangle(ray, tri, opt.doubleSided);
if (dist == 0 || dist > opt.distance!) continue;
if (opt.mode == ERaycastMode.CLOSEST) {
if (minDis > dist || minDis == 0) {
minDis = dist;
tr.distance = dist;
tr.vertexIndex0 = i0;
tr.vertexIndex1 = i1;
tr.vertexIndex2 = i2;
if (opt.result && j + 3 < cnt)
opt.result.push({ distance: tr.distance, vertexIndex0: tr.vertexIndex0, vertexIndex1: tr.vertexIndex1, vertexIndex2: tr.vertexIndex2 });
}
} else if (opt.mode == ERaycastMode.ALL) {
minDis = dist;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
} else {
minDis = dist;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
return minDis;
}
if (dist == 0 || dist > opt.distance) continue;
fillResult(opt.mode, dist, i0, i1, i2, opt.result);
if (opt.mode == ERaycastMode.ANY) return dist;
}
} else if (pm === GFXPrimitiveMode.TRIANGLE_STRIP) {
const cnt = ib.length - 2;
@@ -378,18 +379,9 @@ const ray_subMesh = (function () {
Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
rev = ~rev;
const dist = intersect.ray_triangle(ray, tri, opt.doubleSided);
if (dist == 0 || dist > opt.distance!) continue;
if (opt.mode == ERaycastMode.CLOSEST) {
if (minDis < dist) continue;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
} else if (opt.mode == ERaycastMode.ALL) {
minDis = dist;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
} else {
minDis = dist;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
return minDis;
}
if (dist == 0 || dist > opt.distance) continue;
fillResult(opt.mode, dist, i0, i1, i2, opt.result);
if (opt.mode == ERaycastMode.ANY) return dist;
}
} else if (pm === GFXPrimitiveMode.TRIANGLE_FAN) {
const cnt = ib.length - 1;
@@ -401,32 +393,25 @@ const ray_subMesh = (function () {
Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
const dist = intersect.ray_triangle(ray, tri, opt.doubleSided);
if (dist == 0 || dist > opt.distance!) continue;
if (opt.mode == ERaycastMode.CLOSEST) {
if (minDis < dist) continue;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
} else if (opt.mode == ERaycastMode.ALL) {
minDis = dist;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
} else {
minDis = dist;
if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 });
return minDis;
}
if (dist == 0 || dist > opt.distance) continue;
fillResult(opt.mode, dist, i0, i1, i2, opt.result);
if (opt.mode == ERaycastMode.ANY) return dist;
}
}
return minDis;
};
return function (ray: ray, submesh: RenderingSubMesh, option?: IRaySubMeshOptions) {
minDis = 0;
if (submesh.geometricInfo.positions.length == 0) return minDis;
const opt = option == undefined ? deOpt : option;
if (!opt.doNotZeroMin) minDis = 0;
if (submesh.geometricInfo.positions.length == 0) return;
if (broadphase(ray, submesh)) {
const min = submesh.geometricInfo.boundingBox.min;
const max = submesh.geometricInfo.boundingBox.max;
if (ray_aabb2(ray, min, max)) {
const pm = submesh.primitiveMode;
const { positions: vb, indices: ib } = submesh.geometricInfo!;
narrowphase(vb, ib!, pm, ray, opt);
}
return minDis != 0;
return minDis;
}
})();
@@ -435,27 +420,44 @@ const ray_subMesh = (function () {
* ray-mesh intersect detect.
* @zh
* 射线和三角网格资源的相交性检测。
* @param {ray} ray
* @param {Mesh} mesh
* @param {IRayMeshOptions} options
* @return {number} 0 or !0
*/
const ray_mesh = (function () {
const deOpt: IRayMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY, doNotZeroMin: true };
let minDis = 0;
const deOpt: IRayMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY };
return function (ray: ray, mesh: Mesh, option?: IRayMeshOptions) {
minDis = 0;
const opt = option == undefined ? deOpt : option;
const length = mesh.renderingSubMeshes.length;
let result = false;
const min = mesh.struct.minPosition;
const max = mesh.struct.maxPosition;
if (min && max && !ray_aabb2(ray, min, max)) return false;
if (min && max && !ray_aabb2(ray, min, max)) return minDis;
for (let i = 0; i < length; i++) {
const sm = mesh.renderingSubMeshes[i];
if (ray_subMesh(ray, sm, opt)) {
result = true;
if (opt.subIndices) opt.subIndices.push(i);
if (opt.mode == ERaycastMode.ANY) {
return true;
const dis = ray_subMesh(ray, sm, opt);
if (dis) {
if (opt.mode == ERaycastMode.CLOSEST) {
if (minDis == 0 || minDis > dis) {
minDis = dis;
if (opt.subIndices) opt.subIndices[0] = i;
}
} else {
minDis = dis;
if (opt.subIndices) opt.subIndices.push(i);
if (opt.mode == ERaycastMode.ANY) {
return dis;
}
}
}
}
return result;
if (minDis && opt.mode == ERaycastMode.CLOSEST) {
if (opt.result) opt.result.length = 1;
if (opt.subIndices) opt.subIndices.length = 1;
}
return minDis;
}
})();
@@ -464,34 +466,51 @@ const ray_mesh = (function () {
* ray-model intersect detect.
* @zh
* 射线和渲染模型的相交性检测。
* @param {ray} ray
* @param {Model} model
* @param {IRayModelOptions} options
* @return {number} 0 or !0
*/
const ray_model = (function () {
const deOpt: IRayModelOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY, doNotZeroMin: true, doNotTransformRay: false };
let minDis = 0;
const deOpt: IRayModelOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY };
const modelRay = new ray();
const m4 = new Mat4;
const m4 = new Mat4();
return function (r: ray, model: Model, option?: IRayModelOptions) {
minDis = 0;
const opt = option == undefined ? deOpt : option;
const length = model.subModelNum;
let result = false;
const wb = model.worldBounds;
if (wb && !ray_aabb(r, wb)) return minDis;
ray.copy(modelRay, r);
if (!opt.doNotTransformRay) {
if (model.node) {
Mat4.invert(m4, model.node.getWorldMatrix(m4));
Vec3.transformMat4(modelRay.o, r.o, m4);
Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, r.d, m4));
}
const box = model.modelBounds;
if (box && !ray_aabb(modelRay, box)) return false;
for (let i = 0; i < length; i++) {
const sm = model.getSubModel(i).subMeshData;
if (ray_subMesh(modelRay, sm, opt)) {
result = true;
if (opt.subIndices) opt.subIndices.push(i);
if (opt.mode == ERaycastMode.ANY) {
return true;
const dis = ray_subMesh(modelRay, sm, opt);
if (dis) {
if (opt.mode == ERaycastMode.CLOSEST) {
if (minDis == 0 || minDis > dis) {
minDis = dis;
if (opt.subIndices) opt.subIndices[0] = i;
}
} else {
minDis = dis;
if (opt.subIndices) opt.subIndices.push(i);
if (opt.mode == ERaycastMode.ANY) {
return dis;
}
}
}
}
return result;
if (minDis && opt.mode == ERaycastMode.CLOSEST) {
if (opt.result) opt.result.length = 1;
if (opt.subIndices) opt.subIndices.length = 1;
}
return minDis;
}
})();
+109 -5
View File
@@ -2,39 +2,143 @@
* @category geometry
*/
export enum ERaycastMode {
/**
* @en
* The raycast mode.
* @zh
* 射线检测模式。
*/
export enum ERaycastMode {
/**
* @en
* Detect and record all data.
* @zh
* 检测并记录所有的数据。
*/
ALL,
/**
* @en
* Detect all, but record only the most recent data.
* @zh
* 检测所有,但只记录最近的数据。
*/
CLOSEST,
/**
* @en
* Once the test is successful, the test is stopped and the data is recorded only once.
* @zh
* 一旦检测成功就停止检测,只会记录一次数据。
*/
ANY,
}
/**
* @en
* The storage structure of the raycast results.
* @zh
* 射线检测结果的存储结构。
*/
export interface IRaySubMeshResult {
/**
* @en
* The distance between the hit point and the ray.
* @zh
* 击中点和射线的距离。
*/
distance: number;
/**
* @en
* The index of the triangle vertex 0。
* @zh
* 三角形顶点0的索引。
*/
vertexIndex0: number;
/**
* @en
* The index of the triangle vertex 1。
* @zh
* 三角形顶点1的索引
*/
vertexIndex1: number;
/**
* @en
* The index of the triangle vertex 2。
* @zh
* 三角形顶点2的索引
*/
vertexIndex2: number;
}
/**
* @en
* The optional param structure of the `ray_subMesh`.
* @zh
* `ray_subMesh`的可选参数结构。
*/
export interface IRaySubMeshOptions {
/**
* @en
* The raycast mode,`ANY` by default.
* @zh
* 检测模式:[0,1,2]=>[ALL,CLOSEST,ANY]
* 射线检测模式:[0, 1, 2]=>[`ALL`, `CLOSEST`, `ANY`]
*/
mode: ERaycastMode;
/**
* @en
* The maximum distance of the raycast, `Infinity` by default.
* @zh
* 检测的最大距离
* 射线检测的最大距离,默认为`Infinity`。
*/
distance: number;
/**
* @en
* An array used to store the results of a ray detection.
* @zh
* 用于存储射线检测结果的数组。
*/
result?: IRaySubMeshResult[];
/**
* @en
* Whether to detect the double-sided or not,`false` by default.
* @zh
* 是否检测双面,默认为`false`。
*/
doubleSided?: boolean;
doNotZeroMin?: boolean;
}
/**
* @en
* The optional param structure of the `ray_mesh`.
* @zh
* `ray_mesh`的可选参数结构。
*/
export interface IRayMeshOptions extends IRaySubMeshOptions {
/**
* @en
* The index of the sub mesh.
* @zh
* 子网格的索引。
*/
subIndices?: number[];
}
/**
* @en
* The optional param structure of the `ray_model`.
* @zh
* `ray_model`的可选参数结构。
*/
export interface IRayModelOptions extends IRayMeshOptions {
doNotTransformRay?: boolean;
}
+1 -1
View File
@@ -757,6 +757,7 @@ export function GFXFormatSize (format: GFXFormat, width: number, height: number,
case GFXFormat.EAC_R11:
case GFXFormat.EAC_R11SN:
return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
case GFXFormat.ETC2_RGBA8:
case GFXFormat.EAC_RG11:
case GFXFormat.EAC_RG11SN:
return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
@@ -796,7 +797,6 @@ export function GFXFormatSurfaceSize (
size += GFXFormatSize(format, width, height, depth);
width = Math.max(width >> 1, 1);
height = Math.max(height >> 1, 1);
depth = Math.max(depth >> 1, 1);
}
return size;
+30 -6
View File
@@ -38,6 +38,7 @@ import { WebGLGFXDevice } from './webgl-device';
import { IWebGLGPUInputAssembler, IWebGLGPUUniform, WebGLAttrib, WebGLGPUBindingLayout,
WebGLGPUBuffer, WebGLGPUFramebuffer, WebGLGPUInput,
WebGLGPUPipelineState, WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects';
import { WECHAT } from 'internal:constants';
function CmpF32NotEuqal (a: number, b: number): boolean {
const c = a - b;
@@ -178,6 +179,16 @@ export function GFXFormatToWebGLInternalFormat (format: GFXFormat, gl: WebGLRend
case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2;
case GFXFormat.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2;
case GFXFormat.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;
case GFXFormat.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
case GFXFormat.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC;
case GFXFormat.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;
case GFXFormat.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC;
case GFXFormat.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;
case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
@@ -1504,6 +1515,9 @@ export function WebGLCmdFuncBeginRenderPass (
clearDepth: number,
clearStencil: number) {
gfxStateCache.gpuInputAssembler = null;
gfxStateCache.gpuShader = null;
const gl = device.gl;
const cache = device.stateCache;
let clears: GLbitfield = 0;
@@ -2566,8 +2580,6 @@ export function WebGLCmdFuncDraw (device: WebGLGFXDevice, drawInfo: IGFXDrawInfo
const cmdIds = new Array<number>(WebGLCmd.COUNT);
export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) {
cmdIds.fill(0);
gfxStateCache.gpuShader = null;
gfxStateCache.gpuInputAssembler = null;
for (let i = 0; i < cmdPackage.cmds.length; ++i) {
const cmd = cmdPackage.cmds.array[i];
@@ -2703,8 +2715,14 @@ export function WebGLCmdFuncCopyBuffersToTexture (
region.texOffset.x, region.texOffset.y, w, h,
gpuTexture.glFormat, pixels);
} else {
gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel,
gpuTexture.glInternelFmt, w, h, 0, pixels);
if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !WECHAT) {
gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel,
region.texOffset.x, region.texOffset.y, w, h,
gpuTexture.glFormat, pixels);
} else {
gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel,
gpuTexture.glInternelFmt, w, h, 0, pixels);
}
}
}
}
@@ -2731,8 +2749,14 @@ export function WebGLCmdFuncCopyBuffersToTexture (
region.texOffset.x, region.texOffset.y, w, h,
gpuTexture.glFormat, pixels);
} else {
gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel,
gpuTexture.glInternelFmt, w, h, 0, pixels);
if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !WECHAT) {
gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel,
region.texOffset.x, region.texOffset.y, w, h,
gpuTexture.glFormat, pixels);
} else {
gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel,
gpuTexture.glInternelFmt, w, h, 0, pixels);
}
}
}
}
+2 -2
View File
@@ -46,7 +46,7 @@ export class WebGLGFXWindow extends GFXWindow {
storeOp: GFXStoreOp.STORE,
sampleCount: 1,
beginLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL,
endLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL,
endLayout: GFXTextureLayout.PRESENT_SRC,
}],
depthStencilAttachment: {
format : this._depthStencilFmt,
@@ -56,7 +56,7 @@ export class WebGLGFXWindow extends GFXWindow {
stencilStoreOp : GFXStoreOp.STORE,
sampleCount : 1,
beginLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
endLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
endLayout : GFXTextureLayout.PRESENT_SRC,
},
});
+40 -3
View File
@@ -339,6 +339,16 @@ export function GFXFormatToWebGLFormat (format: GFXFormat, gl: WebGL2RenderingCo
case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2;
case GFXFormat.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2;
case GFXFormat.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;
case GFXFormat.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
case GFXFormat.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC;
case GFXFormat.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;
case GFXFormat.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC;
case GFXFormat.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;
case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
@@ -807,8 +817,34 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2GFXDevice, gpuBuffer: W
}
export function WebGL2CmdFuncDestroyBuffer (device: WebGL2GFXDevice, gpuBuffer: WebGL2GPUBuffer) {
const gl = device.gl;
if (gpuBuffer.glBuffer) {
device.gl.deleteBuffer(gpuBuffer.glBuffer);
// Firefox 75+ implicitly unbind whatever buffer there was on the slot sometimes
// can be reproduced in the static batching scene at https://github.com/cocos-creator/test-cases-3d
switch (gpuBuffer.glTarget) {
case gl.ARRAY_BUFFER:
if (device.useVAO && device.stateCache.glVAO) {
gl.bindVertexArray(null);
device.stateCache.glVAO = null;
}
gl.bindBuffer(gl.ARRAY_BUFFER, null);
device.stateCache.glArrayBuffer = null;
break;
case gl.ELEMENT_ARRAY_BUFFER:
if (device.useVAO && device.stateCache.glVAO) {
gl.bindVertexArray(null);
device.stateCache.glVAO = null;
}
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
device.stateCache.glElementArrayBuffer = null;
break;
case gl.UNIFORM_BUFFER:
gl.bindBuffer(gl.UNIFORM_BUFFER, null);
device.stateCache.glUniformBuffer = null;
break;
}
gl.deleteBuffer(gpuBuffer.glBuffer);
gpuBuffer.glBuffer = null;
}
}
@@ -1739,6 +1775,9 @@ export function WebGL2CmdFuncBeginRenderPass (
clearDepth: number,
clearStencil: number) {
gfxStateCache.gpuInputAssembler = null;
gfxStateCache.gpuShader = null;
const gl = device.gl;
const cache = device.stateCache;
@@ -2575,8 +2614,6 @@ export function WebGL2CmdFuncDraw (device: WebGL2GFXDevice, drawInfo: IGFXDrawIn
const cmdIds = new Array<number>(WebGL2Cmd.COUNT);
export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: WebGL2CmdPackage) {
cmdIds.fill(0);
gfxStateCache.gpuShader = null;
gfxStateCache.gpuInputAssembler = null;
for (let i = 0; i < cmdPackage.cmds.length; ++i) {
const cmd = cmdPackage.cmds.array[i];
-1
View File
@@ -256,7 +256,6 @@ export class WebGL2GFXDevice extends GFXDevice {
this._features[GFXFeature.TEXTURE_HALF_FLOAT] = true;
this._features[GFXFeature.FORMAT_R11G11B10F] = true;
this._features[GFXFeature.FORMAT_D24S8] = true;
this._features[GFXFeature.FORMAT_ETC2] = true;
this._features[GFXFeature.MSAA] = true;
this._features[GFXFeature.ELEMENT_INDEX_UINT] = true;
this._features[GFXFeature.INSTANCED_ARRAYS] = true;
+170 -246
View File
@@ -28,7 +28,9 @@
* @category loader
*/
import { Asset, RawAsset } from '../assets';
import { SpriteAtlas } from '../assets/sprite-atlas';
import { Asset } from '../assets/asset';
import { RawAsset } from '../assets/raw-asset'
import { SpriteFrame } from '../assets/sprite-frame';
import { Texture2D } from '../assets/texture-2d';
import { TextureCube } from '../assets/texture-cube';
@@ -45,6 +47,8 @@ import { Pipeline } from './pipeline';
import ReleasedAssetChecker from './released-asset-checker';
import { DEBUG, EDITOR, DEV } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { warnID, errorID, error } from '../platform/debug';
import * as path from '../utils/path';
const assetTables = Object.create(null);
assetTables.assets = new AssetTable();
@@ -56,12 +60,10 @@ function getXMLHttpRequest () {
const _info = { url: null, raw: false };
/**
* @en
* Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url<br>
/*
* @en Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url<br>
* So we gurantee there will be url in result
* @zh
* 通过使用 uuid 查找资源的真实 url 来转换资源,否则将使用 uuid 或原始 url 作为其 url<br>
* @zh 通过使用 uuid 查找资源的真实 url 来转换资源,否则将使用 uuid 或原始 url 作为其 url<br>
* 所以可以保证结果中会有 url
* @param res
*/
@@ -99,48 +101,40 @@ const _sharedResources: any = [];
const _sharedList: any = [];
/**
* @en
* Loader for resource loading process. It's a singleton object.
* @zh
* 资源加载程序,这是一个单例对象。
* @en Loader for resource loading process. The engine automatically initialize its singleton object {{loader}}.
* @zh 资源加载管理器,引擎会自动创建一个单例对象 {{loader}}。
*/
export class CCLoader extends Pipeline {
/**
* @en
* Gets a new XMLHttpRequest instance.
* @zh
* 获取一个新的 XMLHttpRequest 的实例。
* @en Gets a new XMLHttpRequest instance.
* @zh 获取一个新的 XMLHttpRequest 的实例。
*/
public getXMLHttpRequest: Function;
/**
* @en
* The asset loader in cc.loader's pipeline, it's by default the first pipe.<br>
* @en The asset loader in loader's pipeline, it's by default the first pipe.<br>
* It's used to identify an asset's type, and determine how to download it.
* @zh
* cc.loader 中的资源加载器,默认情况下是最先加载的。<br>
* @zh loader 中的资源加载器,默认情况下是最先加载的。<br>
* 用于标识资源的类型,并确定如何加载此资源。
*/
public assetLoader: AssetLoader;
/**
* @en
* The md5 pipe in cc.loader's pipeline, it could be absent if the project isn't build with md5 option.<br>
* @en The md5 pipe in loader's pipeline, it could be absent if the project isn't build with md5 option.<br>
* It's used to modify the url to the real downloadable url with md5 suffix.
* @zh
* cc.loader 中的 md5 加载管道,如果项目没有使用 md5 构建,则此项可能不存在。<br>
* @zh loader 中的 md5 加载管道,如果项目没有使用 md5 构建,则此项可能不存在。<br>
* 用于修改带有 md5 后缀的真实可下载的 URL 。
*/
public md5Pipe: null;
/**
* @en
* The downloader in cc.loader's pipeline, it's by default the second pipe.<br>
* The downloader in loader's pipeline, it's by default the second pipe.<br>
* It's used to download files with several handlers: pure text, image, script, audio, font, uuid.<br>
* You can add your own download function with addDownloadHandlers
* @zh
* cc.loader 中的资源下载程序,默认情况下是第二个加载的。<br>
* loader 中的资源下载程序,默认情况下是第二个加载的。<br>
* 它用于下载带有多个处理程序的文件:纯文本,图像,脚本,音频,字体,uuid。<br>
* 您可以使用 addDownloadHandlers 来添加自己的下载函数
*/
@@ -148,23 +142,27 @@ export class CCLoader extends Pipeline {
/**
* @en
* The loader in cc.loader's pipeline, it's by default the third pipe.<br>
* The loader in loader's pipeline, it's by default the third pipe.<br>
* It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid.<br>
* You can add your own download function with addLoadHandlers
* @zh
* cc.loader 中的资源下载程序,默认情况下是第三个加载的。<br>
* loader 中的资源下载程序,默认情况下是第三个加载的。<br>
* 它用于解析下载的内容及多个处理程序的文件:纯文本,图像,脚本,音频,字体,uuid。<br>
* 您可以使用 addLoadHandlers 来添加自己的下载函数
*/
public loader: Loader;
public onProgress: null;
public _assetTables: any;
/**
* @en The default progression callback during the loading process,
* if no progression callback is passed to {{load}} function, then this default callback will be used.
* @zh Loader 默认的进度回调函数,如果在调用 {{load}} 函数时没有指定进度回调函数的话,会调用默认进度回调函数。
*/
public onProgress: Function | null;
public _assetTables: any;
private _autoReleaseSetting: any;
private _releasedAssetChecker_DEBUG: any;
constructor () {
const assetLoader = new AssetLoader();
const downloader = new Downloader();
// tslint:disable-next-line: no-shadowed-letiable
@@ -176,14 +174,11 @@ export class CCLoader extends Pipeline {
loader,
]);
this.getXMLHttpRequest = getXMLHttpRequest;
this.getXMLHttpRequest = getXMLHttpRequest;
this.assetLoader = assetLoader;
this.md5Pipe = null;
this.downloader = downloader;
this.loader = loader;
this.onProgress = null;
@@ -197,6 +192,11 @@ export class CCLoader extends Pipeline {
}
}
/**
* @en Initialize with director
* @zh 使用 {{director}} 初始化
* @param director The director instance of engine
*/
public init (director) {
if (DEBUG) {
const self = this;
@@ -207,46 +207,39 @@ export class CCLoader extends Pipeline {
}
/**
* @en
* Add custom supported types handler or modify existing type handler for download process.
* @zh
* 为下载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。
* @en Add custom supported types handler or modify existing type handler for download process.
* @zh 为下载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。
* @example
* ```typescript
* cc.loader.addDownloadHandlers({
* loader.addDownloadHandlers({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* ```
* @param extMap 具有相应处理程序的自定义支持类型
* @param extMap Handlers for corresponding type in a map
*/
public addDownloadHandlers (extMap: Object) {
public addDownloadHandlers (extMap: Map<string, Function>) {
this.downloader.addHandlers(extMap);
}
/**
* @en
* Add custom supported types handler or modify existing type handler for load process.
* @zh
* 为加载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。
* @en Add custom supported types handler or modify existing type handler for load process.
* @zh 为加载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。
* @example
* ```typescript
* cc.loader.addLoadHandlers({
* loader.addLoadHandlers({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* ```
* @method addLoadHandlers
* @param extMap 具有相应处理程序的自定义支持类型
* @param extMap Handlers for corresponding type in a map
*/
public addLoadHandlers (extMap: Object) {
public addLoadHandlers (extMap: Map<string, Function>) {
this.loader.addHandlers(extMap);
}
// tslint:disable: max-line-length
// load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void
// load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: Function|null): void
/**
* @en
* Load resources with a progression callback and a complete callback.<br>
@@ -260,19 +253,19 @@ export class CCLoader extends Pipeline {
     * 唯一的区别是当用户将单个 URL 作为资源传递时,完整的回调将其结果直接设置为第二个参数。
* @example
* ```TypeScript
* cc.loader.load('a.png', function (err, tex) {
* loader.load('a.png', function (err, tex) {
* cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D));
* });
*
* cc.loader.load('http://example.com/a.png', function (err, tex) {
* loader.load('http://example.com/a.png', function (err, tex) {
* cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D));
* });
*
* cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) {
* loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) {
* cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D));
* });
*
* cc.loader.load(['a.png', 'b.json'], function (errors, results) {
* loader.load(['a.png', 'b.json'], function (errors, results) {
* if (errors) {
* for (let i = 0; i < errors.length; i++) {
* cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i]));
@@ -282,17 +275,16 @@ export class CCLoader extends Pipeline {
* let bJsonObj = results.getContent('b.json');
* });
* ```
* @method load
* @param {String|String[]|Object} resources - Url 列表数组
* @param {Function} progressCallback - 当进度改变时调用的回调函数
* @param resources - Url list or load request list
* @param progressCallback - Progression callback
* @param {Number} progressCallback.completedCount - The number of the items that are already completed
* @param {Number} progressCallback.totalCount - The total number of the items
* @param {Object} progressCallback.item - The latest item which flow out the pipeline
* @param {Function} completeCallback - 当所有资源加载完毕后调用的回调函数
* @param completeCallback - Completion callback
*/
public load (resources, progressCallback, completeCallback?) {
public load (resources: string|string[]|Object, progressCallback?: Function|null, completeCallback?: Function|null) {
if (DEV && !resources) {
return legacyCC.error('[cc.loader.load] resources must be non-nil.');
return error('[loader.load] resources must be non-nil.');
}
if (completeCallback === undefined) {
@@ -302,23 +294,27 @@ export class CCLoader extends Pipeline {
const self = this;
let singleRes: Boolean = false;
let resList: Array<string|Object>;
let res;
if (!(resources instanceof Array)) {
if (resources instanceof Array) {
resList = resources;
}
else {
if (resources) {
singleRes = true;
resources = [resources];
resList = [resources];
} else {
resources = [];
resList = [];
}
}
_sharedResources.length = 0;
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < resources.length; ++i) {
const resource = resources[i];
for (let i = 0; i < resList.length; ++i) {
const resource: any = resList[i];
// Backward compatibility
if (resource && resource.id) {
legacyCC.warnID(4920, resource.id);
warnID(4920, resource.id);
if (!resource.uuid && !resource.url) {
resource.url = resource.id;
}
@@ -353,10 +349,8 @@ export class CCLoader extends Pipeline {
}
/**
* @en
* See: [[Pipeline.flowInDeps]]
* @zh
* 参考:[[Pipeline.flowInDeps]]
* @en See: {{Pipeline.flowInDeps}}
* @zh 参考:{{Pipeline.flowInDeps}}
*/
public flowInDeps (owner, urlList, callback) {
_sharedList.length = 0;
@@ -421,39 +415,29 @@ export class CCLoader extends Pipeline {
completeCallback: LoadCompleteCallback<T>,
);
// @typescript
// loadRes(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void
// loadRes(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any) => void): void
// loadRes(url: string, type: typeof cc.Asset): void
// loadRes(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void
// loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void
// loadRes(url: string): void
/**
* @en
* Load resources from the "resources" folder inside the "assets" folder of your project.<br>
* Load assets from the "resources" folder inside the "assets" folder of your project.<br>
* <br>
* Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work.
* @zh
* 从项目的 “assets” 文件夹下的 “resources” 文件夹中加载资源<br>
* <br>
* 注意:Creator 中的所有资源 URL 都使用正斜杠,使用反斜杠的 URL 将不起作用。
* @method loadRes
* @param {String} url - 目标资源的 URL<br>
* URl 相对于 “resources” 文件夹,必须省略文件扩展名。
* @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。
* @param {Function} progressCallback - 当进度改变时调用的回调函数
* @param url - The url of the asset to be loaded, this url should be related path without file extension to the `resources` folder.
* @param type - If type is provided, only asset for correspond type will be loaded
* @param progressCallback - Progression callback
* @param {Number} progressCallback.completedCount - The number of the items that are already completed.
* @param {Number} progressCallback.totalCount - The total number of the items.
* @param {Object} progressCallback.item - The latest item which flow out the pipeline.
* @param {Function} completeCallback - 当所有资源加载完毕后调用的回调函数
* @param completeCallback - Completion callback
* @param {Error} completeCallback.error - The error info or null if loaded successfully.
* @param {Object} completeCallback.resource - The loaded resource if it can be found otherwise returns null.
*
* @example
* ```typescript
* // load the prefab (project/assets/resources/misc/character/cocos) from resources folder
* cc.loader.loadRes('misc/character/cocos', function (err, prefab) {
* loader.loadRes('misc/character/cocos', function (err, prefab) {
* if (err) {
* cc.error(err.message || err);
* return;
@@ -462,7 +446,7 @@ export class CCLoader extends Pipeline {
* });
*
* // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder
* cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) {
* loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) {
* if (err) {
* cc.error(err.message || err);
* return;
@@ -471,7 +455,7 @@ export class CCLoader extends Pipeline {
* });
* ```
*/
public loadRes (url: String, type: Function, mount: string | Function, progressCallback?: Function, completeCallback?: Function) {
public loadRes (url: string, type: Function, mount: string | Function, progressCallback?: Function, completeCallback?: Function) {
if (arguments.length !== 5) {
completeCallback = progressCallback;
progressCallback = mount as Function;
@@ -505,14 +489,6 @@ export class CCLoader extends Pipeline {
}
}
// @typescript
// loadResDir(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void
// loadResDir(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void
// loadResDir(url: string, type: typeof cc.Asset): void
// loadResDir(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void
// loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void
// loadResDir(url: string): void
/**
* @en
* Load all assets in a folder inside the "assets/resources" folder of your project.<br>
@@ -522,25 +498,23 @@ export class CCLoader extends Pipeline {
* 将所有资产加载到项目 “assets / resources” 文件夹中
     * <br>
* 注意:Creator 中的所有资源 URL 都使用正斜杠,使用反斜杠的 URL 将不起作用。
* @method loadResDir
* @param {String} url - 目标文件夹的 URL<br>
* URl 相对于 “resources” 文件夹,必须省略文件扩展名。
* @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。
* @param {Function} progressCallback - 当进度改变时调用的回调函数
* @param url The url of the directory to be loaded, this url should be related path to the `resources` folder.
* @param type - If type is provided, only assets for correspond type will be loaded
* @param progressCallback - Progression callback
* @param {Number} progressCallback.completedCount - The number of the items that are already completed.
* @param {Number} progressCallback.totalCount - The total number of the items.
* @param {Object} progressCallback.item - The latest item which flow out the pipeline.
* @param {Function} completeCallback - 当所有资源加载完毕后或者发生错误时调用的回调函数
* @param completeCallback - Completion callback
* @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called
* with the error. If all assets are loaded successfully, error will be null.
* @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets.
* If nothing to load, assets will be an empty array.
* @param {String[]} completeCallback.urls - An array that lists all the URLs of loaded assets.
* @param {string[]} completeCallback.urls - An array that lists all the URLs of loaded assets.
*
* @example
* ```typescript
* // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame
* cc.loader.loadResDir('imgs/cocos', function (err, assets) {
* loader.loadResDir('imgs/cocos', function (err, assets) {
* if (err) {
* cc.error(err);
* return;
@@ -550,19 +524,19 @@ export class CCLoader extends Pipeline {
* });
*
* // load all textures in "resources/imgs/"
* cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) {
* loader.loadResDir('imgs', cc.Texture2D, function (err, textures) {
* let texture1 = textures[0];
* let texture2 = textures[1];
* });
*
* // load all JSONs in "resources/data/"
* cc.loader.loadResDir('data', function (err, objects, urls) {
* loader.loadResDir('data', function (err, objects, urls) {
* let data = objects[0];
* let url = urls[0];
* });
* ```
*/
public loadResDir (url: String, type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) {
public loadResDir (url: string, type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) {
if (arguments.length !== 5) {
completeCallback = progressCallback;
progressCallback = mount;
@@ -583,7 +557,7 @@ export class CCLoader extends Pipeline {
// To show users the exact structure in asset panel, we need to return the spriteFrame assets in spriteAtlas
const assetResLength = assetRes.length;
for (let i = 0; i < assetResLength; ++i) {
if (assetRes[i] instanceof legacyCC.SpriteAtlas) {
if (assetRes[i] instanceof SpriteAtlas) {
const spriteFrames = assetRes[i].getSpriteFrames();
// tslint:disable: forin
for (const k in spriteFrames) {
@@ -601,28 +575,17 @@ export class CCLoader extends Pipeline {
}, urls);
}
// * @typescript
// * loadResArray(url: string[], type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void
// * loadResArray(url: string[], type: typeof cc.Asset, completeCallback: (error: Error, resource: any[]) => void): void
// * loadResArray(url: string[], type: typeof cc.Asset): void
// * loadResArray(url: string[], progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void
// * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void
// * loadResArray(url: string[]): void
/**
* @en
* This method is like [[loadRes]] except that it accepts array of url.
* @zh
* 此方法除了接受 URL 数组参数外,与 [[loadRes]] 方法相同。
* @en This method is like [[loadRes]] except that it accepts array of url.
* @zh 此方法除了接受 URL 数组参数外,与 [[loadRes]] 方法相同。
*
* @method loadResArray
* @param {String[]} urls - 目标资源的 URL 数组。
* URl 为相对于 “resources” 文件夹的,且必须省略文件扩展名。
* @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。
* @param {Function} progressCallback - 当进度改变时调用的回调函数
* @param url The url array of assets to be loaded, this url should be related path without extension to the `resources` folder.
* @param type - If type is provided, only assets for correspond type will be loaded
* @param progressCallback - Progression callback
* @param {Number} progressCallback.completedCount - The number of the items that are already completed.
* @param {Number} progressCallback.totalCount - The total number of the items.
* @param {Object} progressCallback.item - The latest item which flow out the pipeline.
* @param {Function} completeCallback - 当所有资源加载完毕后或者发生错误时调用的回调函数
* @param completeCallback - Completion callback
* @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called
* with the error. If all assets are loaded successfully, error will be null.
* @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets.
@@ -632,7 +595,7 @@ export class CCLoader extends Pipeline {
* // load the SpriteFrames from resources folder
* let spriteFrames;
* let urls = ['misc/characters/character_01', 'misc/weapons/weapons_01'];
* cc.loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) {
* loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) {
* if (err) {
* cc.error(err);
* return;
@@ -642,7 +605,7 @@ export class CCLoader extends Pipeline {
* });
* ```
*/
public loadResArray (urls: String[], type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) {
public loadResArray (urls: string[], type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) {
if (arguments.length !== 5) {
completeCallback = progressCallback;
progressCallback = mount;
@@ -681,10 +644,8 @@ export class CCLoader extends Pipeline {
* 当使用 [[load]] 或 [[loadRes]] 来加载资源时,<br>
* URL 将是资源的唯一标识。<br>
* 在完成加载之后,你可以通过将 URL 传递给此 API 来获取它们。
* @method getRes
* @param {String} url
* @param {Function} type - 如果提供此参数,则将仅返回此类型的资源。
* @returns {*}
* @param url The asset url, it should be related path without extension to the `resources` folder.
* @param type If type is provided, the asset for correspond type will be returned
*/
public getRes<T = any> (url: string, type?: Function): T | null {
let item = this._cache[url];
@@ -705,10 +666,8 @@ export class CCLoader extends Pipeline {
}
/**
* @en
* Get total resources count in loader.
* @zh
* 获取加载的总资源数量
* @en Get total resources count in loader.
* @zh 获取加载的总资源数量
*/
public getResCount (): Number {
return Object.keys(this._cache).length;
@@ -731,23 +690,21 @@ export class CCLoader extends Pipeline {
* @example
* ```typescript
* // Release all dependencies of a loaded prefab
* let deps = cc.loader.getDependsRecursively(prefab);
* cc.loader.release(deps);
* let deps = loader.getDependsRecursively(prefab);
* loader.release(deps);
* // Retrieve all dependent textures
* let deps = cc.loader.getDependsRecursively('prefabs/sample');
* let deps = loader.getDependsRecursively('prefabs/sample');
* let textures = [];
* for (let i = 0; i < deps.length; ++i) {
* let item = cc.loader.getRes(deps[i]);
* let item = loader.getRes(deps[i]);
* if (item instanceof cc.Texture2D) {
* textures.push(item);
* }
* }
* ```
* @method getDependsRecursively
* @param {Asset|RawAsset|String} owner - 资源本身或者是资源的 url 或者是资源的 uuid
* @return {Array}
* @param owner - The asset itself or the asset url or the asset uuid
*/
public getDependsRecursively (owner: Asset|RawAsset|String) {
public getDependsRecursively (owner: Asset|RawAsset|string): Array<string> {
if (owner) {
const key = this._getReferenceKey(owner);
const assets = getDependsRecursively(key);
@@ -762,14 +719,14 @@ export class CCLoader extends Pipeline {
/**
* @en
* Release the content of an asset or an array of assets by uuid.<br>
* Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content.<br>
* This method will not only remove the cache of the asset in loader, but also clean up its content.<br>
* For example, if you release a texture, the texture asset and its gl texture data will be freed up.<br>
* In complexe project, you can use this function with [[getDependsRecursively]] to free up memory in critical circumstances.<br>
* Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors.<br>
* If you only want to remove the cache of an asset, please use [[Pipeline.removeItem]]
* @zh
* 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。<br>
* 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。<br>
* 这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。<br>
* 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。<br>
* 在复杂项目中,我们建议你结合 [[getDependsRecursively]] 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。<br>
* 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。<br>
@@ -778,25 +735,24 @@ export class CCLoader extends Pipeline {
* @example
* ```typescript
* // Release a texture which is no longer need
* cc.loader.release(texture);
* loader.release(texture);
* // Release all dependencies of a loaded prefab
* let deps = cc.loader.getDependsRecursively('prefabs/sample');
* cc.loader.release(deps);
* let deps = loader.getDependsRecursively('prefabs/sample');
* loader.release(deps);
* // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up.
* // If you have some other nodes share a texture in this prefab, you can skip it in two ways:
* // 1. Forbid auto release a texture before release
* cc.loader.setAutoRelease(texture2d, false);
* loader.setAutoRelease(texture2d, false);
* // 2. Remove it from the dependencies array
* let deps = cc.loader.getDependsRecursively('prefabs/sample');
* let deps = loader.getDependsRecursively('prefabs/sample');
* let index = deps.indexOf(texture2d._uuid);
* if (index !== -1)
* deps.splice(index, 1);
* cc.loader.release(deps);
* loader.release(deps);
* ```
* @method release
* @param {Asset|RawAsset|String|Array} asset
* @param asset Asset or assets to be released
*/
public release (asset) {
public release (asset: Asset|RawAsset|string|Array<Asset|RawAsset|string>) {
if (Array.isArray(asset)) {
for (let i = 0; i < asset.length; i++) {
const key = asset[i];
@@ -809,7 +765,7 @@ export class CCLoader extends Pipeline {
if (item) {
const removed = this.removeItem(id);
asset = item.content;
if (asset instanceof legacyCC.Asset) {
if (asset instanceof Asset) {
const nativeUrl = asset.nativeUrl;
if (nativeUrl) {
this.release(nativeUrl); // uncache loading item of native asset
@@ -824,11 +780,9 @@ export class CCLoader extends Pipeline {
}
/**
* @en Release the asset by its object. Refer to [[release]] for detailed informations.
* @zh 通过资源对象自身来释放资源。详细信息请参考 [[release]]
*
* @method releaseAsset
* @param {Asset} asset
* @en Release the asset by its object. Refer to {{release}} for detailed informations.
* @zh 通过资源对象自身来释放资源。详细信息请参考 {{release}}
* @param asset The asset to be released
*/
public releaseAsset (asset: Asset) {
const uuid = asset._uuid;
@@ -838,36 +792,28 @@ export class CCLoader extends Pipeline {
}
/**
* @en
* Release the asset loaded by [[loadRes]]. Refer to [[release]] for detailed informations.
* @zh
* 释放通过 [[loadRes]] 加载的资源。详细信息请参考 [[release]]
*
* @method releaseRes
* @param {String} url
* @param {Function} type - 如果提供此参数,则将仅释放此类型的资源。
* @en Release the asset loaded by {{loadRes}}. Refer to {{release}} for detailed informations.
* @zh 释放通过 {{loadRes}} 加载的资源。详细信息请参考 {{release}}
* @param url The asset url, it should be related path without extension to the `resources` folder.
* @param type If type is provided, the asset for correspond type will be returned
*/
public releaseRes (url: String, type?: Function, mount?) {
public releaseRes (url: string, type?: Function, mount?) {
const uuid = this._getResUuid(url, type, mount, true);
if (uuid) {
this.release(uuid);
}
else {
legacyCC.errorID(4914, url);
errorID(4914, url);
}
}
/**
* @en
* Release the all assets loaded by [[loadResDir]]. Refer to [[release]] for detailed informations.
* @zh
* 释放通过 [[loadResDir]] 加载的资源。详细信息请参考 [[release]]
*
* @method releaseResDir
* @param {String} url
* @param {Function} type - 如果提供此参数,则将仅释放此类型的资源。
* @en Release the all assets loaded by {{loadResDir}}. Refer to {{release}} for detailed informations.
* @zh 释放通过 {{loadResDir}} 加载的资源。详细信息请参考 {{release}}
* @param url The url of the directory to release, it should be related path to the `resources` folder.
* @param type If type is provided, the asset for correspond type will be returned
*/
public releaseResDir (url: String, type?: Function, mount?) {
public releaseResDir (url: string, type?: Function, mount?) {
mount = mount || 'assets';
if (!assetTables[mount]) { return; }
@@ -879,10 +825,8 @@ export class CCLoader extends Pipeline {
}
/**
* @en Resource all assets. Refer to [[release]] for detailed informations.
* @zh 释放所有资源。详细信息请参考 [[release]]
*
* @method releaseAll
* @en Resource all assets. Refer to {{release}} for detailed informations.
* @zh 释放所有资源。详细信息请参考 {{release}}
*/
public releaseAll () {
for (const id in this._cache) {
@@ -904,39 +848,38 @@ export class CCLoader extends Pipeline {
* Indicates whether to release the asset when loading a new scene.<br>
* By default, when loading a new scene, all assets in the previous scene will be released or preserved<br>
* according to whether the previous scene checked the "Auto Release Assets" option.<br>
* On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir`<br>
* On the other hand, assets dynamically loaded by using `loader.loadRes` or `loader.loadResDir`<br>
* will not be affected by that option, remain not released by default.<br>
* Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.<br>
* <br>
* See: [[setAutoReleaseRecursively]], [[isAutoRelease]]
* See: {{setAutoReleaseRecursively}}, {{isAutoRelease}}
* @zh
* 设置当场景切换时是否自动释放资源。<br>
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。<br>
* 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br>
* 而使用 `loader.loadRes` 或 `loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br>
* 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。<br>
* <br>
* 参考:[[setAutoReleaseRecursively]],[[isAutoRelease]]
* 参考:{{setAutoReleaseRecursively}},{{isAutoRelease}}
*
* @example
* ```typescript
* // auto release the texture event if "Auto Release Assets" disabled in current scene
* cc.loader.setAutoRelease(texture2d, true);
* loader.setAutoRelease(texture2d, true);
* // don't release the texture even if "Auto Release Assets" enabled in current scene
* cc.loader.setAutoRelease(texture2d, false);
* loader.setAutoRelease(texture2d, false);
* // first parameter can be url
* cc.loader.setAutoRelease(audioUrl, false);
* loader.setAutoRelease(audioUrl, false);
* ```
* @method setAutoRelease
* @param {Asset|String} assetOrUrlOrUuid - 资源对象或原始资源的 URL 或是 UUID
* @param {Boolean} autoRelease - 表示是否自动释放
* @param assetOrUrlOrUuid - The asset or its url or its uuid
* @param autoRelease - Whether to release automatically during scene switch
*/
public setAutoRelease (assetOrUrlOrUuid: Asset|String, autoRelease: Boolean) {
public setAutoRelease (assetOrUrlOrUuid: Asset|string, autoRelease: Boolean) {
const key = this._getReferenceKey(assetOrUrlOrUuid);
if (key) {
this._autoReleaseSetting[key] = !!autoRelease;
}
else if (DEV) {
legacyCC.warnID(4902);
warnID(4902);
}
}
@@ -945,33 +888,32 @@ export class CCLoader extends Pipeline {
* Indicates whether to release the asset and its referenced other assets when loading a new scene.<br>
* By default, when loading a new scene, all assets in the previous scene will be released or preserved<br>
* according to whether the previous scene checked the "Auto Release Assets" option.<br>
* On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir`<br>
* On the other hand, assets dynamically loaded by using `loader.loadRes` or `loader.loadResDir`<br>
* will not be affected by that option, remain not released by default.<br>
* Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.<br>
* <br>
* See: [[setAutoRelease]], [[isAutoRelease]]
* See: {{setAutoRelease}}, {{isAutoRelease}}
* @zh
* 设置当场景切换时是否自动释放资源及资源引用的其它资源。<br>
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。<br>
* 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br>
* 而使用 `loader.loadRes` 或 `loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br>
* 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。<br>
* <br>
* 参考:[[setAutoRelease]],[[isAutoRelease]]
* 参考:{{setAutoRelease}},{{isAutoRelease}}
*
* @example
* ```typescript
* // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene
* cc.loader.setAutoReleaseRecursively(spriteFrame, true);
* loader.setAutoReleaseRecursively(spriteFrame, true);
* // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene
* cc.loader.setAutoReleaseRecursively(spriteFrame, false);
* loader.setAutoReleaseRecursively(spriteFrame, false);
* // don't release the Prefab and all the referenced assets
* cc.loader.setAutoReleaseRecursively(prefab, false);
* loader.setAutoReleaseRecursively(prefab, false);
* ```
* @method setAutoReleaseRecursively
* @param {Asset|String} assetOrUrlOrUuid - 资源对象或原始资源的 URL 或是 UUID
* @param {Boolean} autoRelease - 表示是否自动释放
* @param assetOrUrlOrUuid - The asset or its url or its uuid
* @param autoRelease - Whether to release automatically during scene switch
*/
public setAutoReleaseRecursively (assetOrUrlOrUuid: Asset|String, autoRelease: Boolean) {
public setAutoReleaseRecursively (assetOrUrlOrUuid: Asset|string, autoRelease: Boolean) {
autoRelease = !!autoRelease;
const key = this._getReferenceKey(assetOrUrlOrUuid);
if (key) {
@@ -984,25 +926,21 @@ export class CCLoader extends Pipeline {
}
}
else if (DEV) {
legacyCC.warnID(4902);
warnID(4902);
}
}
/**
* @en
* Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.<br>
* @en Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.<br>
* <br>
* See: [[setAutoRelease]], [[setAutoReleaseRecursively]]
*
* @zh
* 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。<br>
* See: {{setAutoRelease}}, {{setAutoReleaseRecursively}}
* @zh 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。<br>
* <br>
* 参考:[[setAutoRelease]],[[setAutoReleaseRecursively]]
* @method isAutoRelease
* @param {Asset|String} assetOrUrl - asset object or the raw asset's url
* 参考:{{setAutoRelease}},{{setAutoReleaseRecursively}}
* @param {Asset|string} assetOrUrl - asset object or the raw asset's url
* @returns {Boolean}
*/
public isAutoRelease (assetOrUrl: Asset|String): Boolean{
public isAutoRelease (assetOrUrl: Asset|string): Boolean{
const key = this._getReferenceKey(assetOrUrl);
if (key) {
return !!this._autoReleaseSetting[key];
@@ -1011,10 +949,10 @@ export class CCLoader extends Pipeline {
}
/**
* @zh
* 获取资源的 uuid
* @en Retrieve asset's uuid
* @zh 获取资源的 uuid
*/
public _getResUuid (url, type, mount, quiet) {
public _getResUuid (url: string, type?: Function, mount?, quiet?) {
mount = mount || 'assets';
let uuid = '';
if (EDITOR) {
@@ -1031,13 +969,13 @@ export class CCLoader extends Pipeline {
}
uuid = assetTable.getUuid(url, type);
if (!uuid) {
const extname = legacyCC.path.extname(url);
const extname = path.extname(url);
if (extname) {
// strip extname
url = url.slice(0, - extname.length);
uuid = assetTable.getUuid(url, type);
if (uuid && !quiet) {
legacyCC.warnID(4901, url, extname);
warnID(4901, url, extname);
}
}
}
@@ -1045,17 +983,15 @@ export class CCLoader extends Pipeline {
}
if (!uuid && type) {
if (isChildClassOf(type, SpriteFrame) || isChildClassOf(type, Texture2D) || isChildClassOf(type, TextureCube)) {
legacyCC.warnID(4934);
warnID(4934);
}
}
return uuid;
}
/**
* @en
* Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url
* @zh
* 在 laoder 中找到资源的引用 id ,参数可以是资源对象、资源的 uuid 或者是资源的 url
* @en Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url
* @zh 在 laoder 中找到资源的引用 id ,参数可以是资源对象、资源的 uuid 或者是资源的 url
*/
public _getReferenceKey (assetOrUrlOrUuid) {
let key;
@@ -1063,20 +999,17 @@ export class CCLoader extends Pipeline {
key = assetOrUrlOrUuid._uuid || null;
}
else if (typeof assetOrUrlOrUuid === 'string') {
key = this._getResUuid(assetOrUrlOrUuid, null, null, true) || assetOrUrlOrUuid;
key = this._getResUuid(assetOrUrlOrUuid, undefined, undefined, true) || assetOrUrlOrUuid;
}
if (!key) {
legacyCC.warnID(4800, assetOrUrlOrUuid);
warnID(4800, assetOrUrlOrUuid);
return key;
}
legacyCC.AssetLibrary._getAssetInfoInRuntime(key, _info);
return this._cache[_info.url!] ? _info.url : key;
}
/**
* @zh
* 当 url 未找到时的操作
*/
// Operation when complete the request without found any asset
private _urlNotFound (url, type, completeCallback) {
callInNextTick(() => {
url = legacyCC.url.normalize(url);
@@ -1087,15 +1020,6 @@ export class CCLoader extends Pipeline {
});
}
/**
* @param {Function} [type]
* @param {Function} [onProgress]
* @param {Function} onComplete
* @returns {Object} arguments
* @returns {Function} arguments.type
* @returns {Function} arguments.onProgress
* @returns {Function} arguments.onComplete
*/
private _parseLoadResArgs (type, onProgress, onComplete) {
if (onComplete === undefined) {
const isValidType = isChildClassOf(type, legacyCC.RawAsset);
@@ -1122,10 +1046,7 @@ export class CCLoader extends Pipeline {
};
}
/**
* @zh
* 通过uuids 加载资源
*/
// Load assets with uuids
private _loadResUuids (uuids, progressCallback, completeCallback, urls ?) {
if (uuids.length > 0) {
const self = this;
@@ -1176,6 +1097,9 @@ export class CCLoader extends Pipeline {
}
}
/**
* Singleton object of CCLoader
*/
export const loader = legacyCC.loader = new CCLoader();
if (EDITOR) {
+6 -1
View File
@@ -23,6 +23,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @category loader
*/
@@ -37,6 +38,10 @@ import { legacyCC } from '../global-exports';
const ID = 'AssetLoader';
let reusedArray:Array<any> = [];
/**
* @en The load pipe in {{loader}} to load an asset with its uuid, it will recursively load its dependencies.
* @zh {{loader}} 加载管线中的资源加载管道,用来通过 uuid 加载 asset 资源及其依赖
*/
export default class AssetLoader implements IPipe {
static ID = ID;
public id:string = ID;
@@ -76,7 +81,7 @@ export default class AssetLoader implements IPipe {
if (EDITOR && this.pipeline) {
this.pipeline._cache[url] = reusedArray[0];
}
queue.append(reusedArray);
queue && queue.append(reusedArray);
// Dispatch to other raw type downloader
item.type = ext;
callback(null, item.content);
+19 -17
View File
@@ -24,7 +24,7 @@
THE SOFTWARE.
*/
/**
* @category loader
* @hidden
*/
import {pushToMap} from '../utils/misc';
@@ -37,7 +37,7 @@ import { SpriteAtlas } from '../assets/sprite-atlas';
import { DEBUG } from 'internal:constants';
class Entry {
public uuid:string;
public uuid: string;
public type;
constructor (uuid, type) {
this.uuid = uuid;
@@ -56,17 +56,17 @@ function isMatchByWord (path, test) {
/*
* @en AssetTable is used to find asset's uuid by url.
* @zh AssetTable 用于查找资源的 uuid 和 url。
* @class AssetTable
*
*/
export class AssetTable {
private _pathToUuid:Map<string, Entry> | Map<string, Array<Entry>>;
private _pathToUuid: Map<string, Entry> | Map<string, Array<Entry>>;
constructor () {
this._pathToUuid = createMap(true);
}
getUuid (path, type) {
/**
* Retrieve the asset uuid with the asset path and type
*/
getUuid (path: string, type: Function) {
path = url.normalize(path);
let item = this._pathToUuid[path];
if (item) {
@@ -105,13 +105,16 @@ export class AssetTable {
return '';
}
getUuidArray (path, type, out_urls) {
/**
* Retrieve an uuid array with the asset path and type
*/
getUuidArray (path: string, type: Function, out_urls: string[]) {
path = url.normalize(path);
if (path[path.length - 1] === '/') {
path = path.slice(0, -1);
}
let path2uuid = this._pathToUuid;
let uuids:Array<string> = [];
let uuids: Array<string> = [];
let _foundAtlasUrl;
for (let p in path2uuid) {
if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) {
@@ -161,16 +164,15 @@ export class AssetTable {
// }
/**
* @en TODO
* @zh 以路径为 key,uuid 为值添加到表中。
* @method add
* @param {String} path - the path to load, should NOT include filename extensions.
* @param {String} uuid
* @param {Function} type
* @param {Boolean} isMainAsset
* @en Add an asset entry with path as key and asset uuid & type as value to the table
* @zh 以路径为 key,uuid 和资源类型为值添加到表中。
* @param path - the path of the asset, should NOT include filename extensions.
* @param uuid - The uuid of the asset
* @param type - Constructor of the asset
* @param isMainAsset
* @private
*/
add (path, uuid, type, isMainAsset) {
add (path: string, uuid: string, type: Function, isMainAsset: boolean) {
// remove extname
// (can not use path.slice because length of extname maybe 0)
isMainAsset && (path = path.substring(0, path.length - extname(path).length));
@@ -24,7 +24,7 @@
THE SOFTWARE.
*/
/**
* @category loader
* @hidden
*/
import {createMap} from '../utils/js';
@@ -24,7 +24,7 @@
THE SOFTWARE.
*/
/**
* @category loader
* @hidden
*/
import { legacyCC } from '../global-exports';
@@ -42,14 +42,14 @@ export default function downloadBinary (item, callback) {
callback(null, arrayBuffer);
}
else {
callback({status:xhr.status, errorMessage:errInfo + '(no response)'});
callback({status: xhr.status, errorMessage: errInfo + '(no response)'});
}
};
xhr.onerror = function(){
callback({status:xhr.status, errorMessage:errInfo + '(error)'});
callback({status: xhr.status, errorMessage: errInfo + '(error)'});
};
xhr.ontimeout = function(){
callback({status:xhr.status, errorMessage:errInfo + '(time out)'});
callback({status: xhr.status, errorMessage: errInfo + '(time out)'});
};
xhr.send(null);
}
+2 -1
View File
@@ -1,6 +1,7 @@
/**
* @category loader
* @hidden
*/
export type LoadCompleteCallback<T> = (error: Error | null | undefined, asset?: T) => void;
export type LoadProgressCallback = (completedCount: number, totalCount: number, item: any) => void;
+27 -33
View File
@@ -186,45 +186,43 @@ interface IDownloadItem {
}
/**
* The downloader pipe, it can download several types of files:
* @en The downloader pipe in {{loader}}, it can download several types of files:
* 1. Text
* 2. Image
* 3. Script
* 4. Audio
* 5. Assets
* 5. Binary
* All unknown type will be downloaded as plain text.
* You can pass custom supported types in the constructor.
* @class Pipeline.Downloader
*/
/**
* Constructor of Downloader, you can pass custom supported types.
*
* @method constructor
* @param {Object} extMap Custom supported types with corresponded handler
* @example
* ```
* let downloader = new Downloader({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* ```
* You can pass custom supported types in the {{loader.addDownloadHandlers}}.
* @zh {{loader}} 中的下载管线,可以下载下列类型的文件:
* 1. Text
* 2. Image
* 3. Script
* 4. Audio
* 5. Binary
* 所有未知类型会被当做文本来下载,也可以通过 {{loader.addDownloadHandlers}} 来定制下载行为
*/
export default class Downloader implements IPipe {
static ID = ID;
static PackDownloader = PackDownloader;
public id:string = ID;
public async:boolean = true;
public pipeline:Pipeline | null = null;
private extMap:object;
public id: string = ID;
public async: boolean = true;
public pipeline: Pipeline | null = null;
private extMap: object;
private _curConcurrent = 0;
private _loadQueue:Array<IDownloadItem> = [];
private _loadQueue: Array<IDownloadItem> = [];
private _subPackages = {};
constructor (extMap?) {
this.extMap = mixin(extMap, defaultMap);
}
/**
* @en Set sub package configurations, only available in certain platforms
* @zh 设置子包配置,只在部分平台支持
* @param subPackages
*/
setSubPackages (subPackages) {
this._subPackages = subPackages;
}
@@ -232,10 +230,9 @@ export default class Downloader implements IPipe {
/**
* @en Add custom supported types handler or modify existing type handler.
* @zh 添加自定义支持的类型处理程序或修改现有的类型处理程序。
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
* @param extMap Custom supported types with corresponded handler
*/
addHandlers (extMap) {
addHandlers (extMap: Map<string, Function>) {
mixin(this.extMap, extMap);
}
@@ -289,16 +286,13 @@ export default class Downloader implements IPipe {
}
/**
* @en
* Load subpackage with name.
* @zh
* 通过子包名加载子包代码。
* @method loadSubpackage
* @param {String} name - Subpackage name
* @param {Function} [completeCallback] - Callback invoked when subpackage loaded
* @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
*/
loadSubpackage (name, completeCallback) {
loadSubpackage (name: string, completeCallback?: Function) {
let pac = this._subPackages[name];
if (pac) {
if (pac.loaded) {
+3 -3
View File
@@ -24,7 +24,7 @@
*/
/**
* @category loader
* @hidden
*/
import {safeMeasureText} from '../utils/text-utils';
@@ -43,7 +43,7 @@ const _testString = "BES bswy:->@123\u4E01\u3041\u1101";
let _fontFaces = {};
let _intervalId = -1;
let _loadingFonts:Array<IFontLoadHandle> = [];
let _loadingFonts: Array<IFontLoadHandle> = [];
// 3 seconds timeout
let _timeout = 3000;
@@ -201,7 +201,7 @@ export function loadFont (item, callback) {
}
else {
// Save loading font
let fontLoadHandle:IFontLoadHandle = {
let fontLoadHandle: IFontLoadHandle = {
fontFamilyName,
refWidth,
callback,
+1 -1
View File
@@ -25,7 +25,7 @@
*/
/**
* @category loader
* @hidden
*/
export {default as url} from './url';
+19 -20
View File
@@ -266,28 +266,25 @@ let defaultMap = {
let ID = 'Loader';
/**
* The loader pipe, it can load several types of files:
* @en The loader pipe in {{loader}}, it can load several types of files:
* 1. Images
* 2. JSON
* 3. Plist
* 4. Audio
* 5. Font
* 6. Cocos Creator scene
* 6. Binary
* 7. Cocos Assets
* It will not interfere with items of unknown type.
* You can pass custom supported types in the constructor.
* @class Pipeline.Loader
*/
/**
* Constructor of Loader, you can pass custom supported types.
*
* @param {Object} extMap Custom supported types with corresponded handler
* @example
* ```
* let loader = new Loader({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* ```
* You can pass custom supported types in the {{loader.addLoadHandlers}}.
* @zh {{loader}} 中的解析加载管线,可以解析加载下列类型的资源:
* 1. Images
* 2. JSON
* 3. Plist
* 4. Audio
* 5. Font
* 6. Binary
* 7. Cocos Assets
* 所有未知类型不会被处理,也可以通过 {{loader.addLoadHandlers}} 来定制加载行为
*/
export default class Loader implements IPipe {
static ID = ID;
@@ -295,16 +292,18 @@ export default class Loader implements IPipe {
public id = ID;
public async = true;
public pipeline: Pipeline | null = null;
private extMap:object;
private extMap: object;
constructor (extMap?) {
this.extMap = mixin(extMap, defaultMap);
}
/**
* Add custom supported types handler or modify existing type handler.
* @param {Object} extMap Custom supported types with corresponded handler
* @en Add custom supported types handler or modify existing type handler.
* @zh 添加自定义支持的类型处理程序或修改现有的类型处理程序。
* @param extMap Custom supported types with corresponded handler
* @param extMap Custom supported types with corresponded handler
*/
addHandlers (extMap?) {
addHandlers (extMap: Map<string, Function>) {
this.extMap = mixin(this.extMap, extMap);
}
+72 -118
View File
@@ -35,27 +35,36 @@ import { legacyCC } from '../global-exports';
let _qid = (0|(Math.random()*998));
let _queues = createMap(true);
let _pool:Array<LoadingItems> = [];
let _pool: Array<LoadingItems> = [];
const _POOL_MAX_LENGTH = 10;
export interface IItem {
queueId;
id:string;
id: string;
url; // real download url, maybe changed
rawUrl; // url used in scripts
urlParam;
type:string;
error:Error|null;
content:any;
complete:boolean;
states:object;
type: string;
error: Error|null;
content: any;
complete: boolean;
states: object;
deps;
isScene:boolean;
isScene: boolean;
}
enum ItemState {
/**
* @property {Number} WORKING
*/
WORKING,
/**
* @property {Number} COMPLETE
*/
COMPLETE,
/**
* @property {Number} ERROR
*/
ERROR
};
@@ -113,8 +122,8 @@ function createItem (id, queueId) {
return result;
}
let _checkedIds:Array<string> = [];
function checkCircleReference(owner, item:IItem, recursiveCall?) {
let _checkedIds: Array<string> = [];
function checkCircleReference(owner, item: IItem, recursiveCall?) {
if (!owner || !item) {
return false;
}
@@ -175,27 +184,11 @@ function checkCircleReference(owner, item:IItem, recursiveCall?) {
* <br/>
* 对象可容纳其他自定义属性。<br/>
* 每个 LoadingItems 对象都会在 onComplete 回调之后被销毁,所以请不要持有它的引用并在结束回调之后依赖它的内容执行任何逻辑,有这种需求的话你可以提前复制它的内容。
*
* @class LoadingItems
* @extends CallbacksInvoker
*/
export class LoadingItems extends CallbacksInvoker {
/**
* @en The item states of the LoadingItems, its value could be LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR
* @zh LoadingItems 队列中的加载项状态,状态的值可能是 LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR
* @enum LoadingItems.ItemState
*/
/**
* @property {Number} WORKING
*/
/**
* @property {Number} COMPLETET
*/
/**
* @property {Number} ERROR
* @en The item states of the LoadingItems, its value could be {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}}
* @zh LoadingItems 队列中的加载项状态,状态的值可能是 {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}}
*/
static ItemState = new legacyCC.Enum(ItemState);
@@ -203,10 +196,9 @@ export class LoadingItems extends CallbacksInvoker {
* @en This is a callback which will be invoked while an item flow out the pipeline.
* You can pass the callback function in LoadingItems.create or set it later.
* @zh 这个回调函数将在 item 加载结束后被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。
* @method onProgress
* @param {Number} completedCount The number of the items that are already completed.
* @param {Number} totalCount The total number of the items.
* @param {Object} item The latest item which flow out the pipeline.
* @param completedCount The number of the items that are already completed.
* @param totalCount The total number of the items.
* @param item The latest item which flow out the pipeline.
* @example
* ```
* loadingItems.onProgress (completedCount, totalCount, item) {
@@ -215,15 +207,14 @@ export class LoadingItems extends CallbacksInvoker {
* }
* ```
*/
public onProgress:Function|undefined;
public onProgress:((completedCount: number, totalCount: number, IItem) => void) | undefined;
/**
* @en This is a callback which will be invoked while all items is completed,
* You can pass the callback function in LoadingItems.create or set it later.
* @zh 该函数将在加载队列全部完成时被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。
* @method onComplete
* @param {Array} errors All errored urls will be stored in this array, if no error happened, then it will be null
* @param {LoadingItems} items All items.
* @param errors All errored urls will be stored in this array, if no error happened, then it will be null
* @param items All items.
* @example
* ```
* loadingItems.onComplete (errors, items) {
@@ -234,53 +225,43 @@ export class LoadingItems extends CallbacksInvoker {
* }
* ```
*/
public onComplete:Function|undefined;
public onComplete:((errors: string[]|null, items: LoadingItems) => void) | undefined;
/**
* @en The map of all items.
* @zh 存储所有加载项的对象。
* @property map
* @type {Object}
*/
public map = createMap(true);
public map: Map<string, IItem> = createMap(true);
/**
* @en The map of completed items.
* @zh 存储已经完成的加载项。
* @property completed
* @type {Object}
*/
public completed = {};
/**
* @en Total count of all items.
* @zh 所有加载项的总数。
* @property totalCount
* @type {Number}
*/
public totalCount = 0;
/**
* @en Total count of completed items.
* @zh 所有完成加载项的总数。
* @property completedCount
* @type {Number}
*/
public completedCount = 0;
/**
* @en Activated or not.
* @zh 是否启用。
* @property active
* @type {Boolean}
*/
public active:boolean;
public active: boolean;
private _id:number;
private _id: number;
private _pipeline;
private _errorUrls:Array<string> = [];
private _errorUrls: Array<string> = [];
private _appending = false;
public _ownerQueue = null;
public _ownerQueue: LoadingItems|null = null;
constructor (pipeline, urlList, onProgress, onComplete) {
super();
@@ -315,8 +296,6 @@ export class LoadingItems extends CallbacksInvoker {
* You can pass onProgress and onComplete callbacks to visualize the loading process.
* @zh LoadingItems 的构造函数,这种构造方式会重用内部对象缓冲池中的 LoadingItems 队列,以尽量避免对象创建。
* 你可以传递 onProgress 和 onComplete 回调函数来获知加载进度信息。
* @method create
* @static
* @param {Pipeline} pipeline The pipeline to process the queue.
* @param {Array} urlList The items array.
* @param {Function} [onProgress] The progression callback, refer to [[onProgress]]
@@ -382,22 +361,19 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Retrieve the LoadingItems queue object for an item.
* @zh 通过 item 对象获取它的 LoadingItems 队列。
* @method getQueue
* @static
* @param {Object} item The item to query
* @return {LoadingItems} The LoadingItems queue object
* @param item The item to query
* @return The LoadingItems queue object
*/
static getQueue (item) {
static getQueue (item: IItem): LoadingItems | null {
return item.queueId ? _queues[item.queueId] : null;
}
/**
* @en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening.
* @zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。
* @method itemComplete
* @param {Object} item The item which has completed
* @param item The item which has completed
*/
static itemComplete (item) {
static itemComplete (item: IItem) {
let queue = _queues[item.queueId];
if (queue) {
// console.log('----- Completed by pipeline ' + item.id + ', rest: ' + (queue.totalCount - queue.completedCount-1));
@@ -458,12 +434,11 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Add urls to the LoadingItems queue.
* @zh 向一个 LoadingItems 队列添加加载项。
* @method append
* @param {Array} urlList 要追加的url列表,url可以是对象或字符串
* @param {any} [owner]
* @return {Array} 在已接受的url列表中,可以拒绝某些无效项
* @param urlList 要追加的url列表,url可以是对象或字符串
* @param owner
* @return 在已接受的url列表中,可以拒绝某些无效项
*/
append (urlList, owner?) {
append (urlList: object[], owner?): IItem[] {
if (!this.active) {
return [];
}
@@ -472,7 +447,7 @@ export class LoadingItems extends CallbacksInvoker {
}
this._appending = true;
let accepted:Array<IItem> = [], i, url, item;
let accepted: Array<IItem> = [], i, url, item;
for (i = 0; i < urlList.length; ++i) {
url = urlList[i];
@@ -543,7 +518,6 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Complete a LoadingItems queue, please do not call this method unless you know what's happening.
* @zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。
* @method allComplete
*/
allComplete () {
let errors = this._errorUrls.length === 0 ? null : this._errorUrls;
@@ -555,43 +529,35 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Check whether all items are completed.
* @zh 检查是否所有加载项都已经完成。
* @method isCompleted
* @return {Boolean}
*/
isCompleted () {
isCompleted (): boolean {
return this.completedCount >= this.totalCount;
}
/**
* @en Check whether an item is completed.
* @zh 通过 id 检查指定加载项是否已经加载完成。
* @method isItemCompleted
* @param {String} id The item's id.
* @return {Boolean}
* @param id The item's id.
*/
isItemCompleted (id) {
isItemCompleted (id: string): boolean {
return !!this.completed[id];
}
/**
* @en Check whether an item exists.
* @zh 通过 id 检查加载项是否存在。
* @method exists
* @param {String} id The item's id.
* @return {Boolean}
* @param id The item's id.
*/
exists (id) {
exists (id: string): boolean {
return !!this.map[id];
}
/**
* @en Returns the content of an internal item.
* @zh 通过 id 获取指定对象的内容。
* @method getContent
* @param {String} id The item's id.
* @return {Object}
* @param id The item's id.
*/
getContent (id) {
getContent (id: string): any {
let item = this.map[id];
let ret = null;
if (item) {
@@ -609,11 +575,9 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Returns the error of an internal item.
* @zh 通过 id 获取指定对象的错误信息。
* @method getError
* @param {String} id The item's id.
* @return {Object}
* @param id The item's id.
*/
getError (id) {
getError (id: string): any {
let item = this.map[id];
let ret = null;
if (item) {
@@ -630,9 +594,9 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Remove an item, can only remove completed item, ongoing item can not be removed.
* @zh 移除加载项,这里只会移除已经完成的加载项,正在进行的加载项将不能被删除。
* @param {String} url
* @param url
*/
removeItem (url) {
removeItem (url: string) {
let item = this.map[url];
if (!item) return;
@@ -652,10 +616,9 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening.
* @zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。
* @method itemComplete
* @param {String} id The item url
* @param id The item url
*/
itemComplete (id) {
itemComplete (id: string) {
let item = this.map[id];
if (!item) {
return;
@@ -692,7 +655,6 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable.
* @zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。
* @method destroy
*/
destroy () {
this.active = false;
@@ -709,8 +671,7 @@ export class LoadingItems extends CallbacksInvoker {
this.totalCount = 0;
this.completedCount = 0;
// Reinitialize CallbacksInvoker, generate three new objects, could be improved
CallbacksInvoker.call(this);
this.clear();
_queues[this._id] = null;
if (_queueDeps[this._id]) {
@@ -725,13 +686,11 @@ export class LoadingItems extends CallbacksInvoker {
/**
* @en Add a listener for an item, the callback will be invoked when the item is completed.
* @zh 监听加载项(通过 key 指定)的完成事件。
* @method addListener
* @param {String} key
* @param {Function} callback - can be null
* @param {Object} target - can be null
* @return {Boolean} whether the key is new
* @param key - The item key
* @param callback - Callback function when item loaded
* @param target - Callback callee
*/
addListener (key, callback, target) {
addListener (key: string, callback: Function, target?: any) {
return super.on(key, callback, target);
}
@@ -742,13 +701,12 @@ export class LoadingItems extends CallbacksInvoker {
* @zh
* 检查指定的加载项是否有完成事件监听器。
* 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。
* @method hasListener
* @param {String} key
* @param {Function} [callback]
* @param {Object} [target]
* @return {Boolean}
* @param key - The item key
* @param callback - Callback function when item loaded
* @param target - Callback callee
* @return Whether the corresponding listener for the item is registered
*/
hasListener (key, callback?, target?) {
hasListener (key: string, callback?: Function, target?: any): boolean {
return super.hasEventListener(key, callback, target);
}
@@ -759,23 +717,19 @@ export class LoadingItems extends CallbacksInvoker {
* @zh
* 移除指定加载项已经注册的完成事件监听器。
* 只会删除 key, callback, target 均匹配的监听器。
* @method remove
* @param {String} key
* @param {Function} callback
* @param {Object} target
* @return {Boolean} removed
* @param key - The item key
* @param callback - Callback function when item loaded
* @param target - Callback callee
*/
removeListener (key, callback?, target?) {
removeListener (key: string, callback?: Function, target?: any) {
return super.off(key, callback, target);
}
/**
* @en
* Removes all callbacks registered in a certain event
* @en Removes all callbacks registered in a certain event
* type or all callbacks registered with a certain target.
* @zh 删除指定目标的所有完成事件监听器。
* @method removeAllListeners
* @param {String|Object} key - The event key to be removed or the target to be removed
* @param {String|Object} key - The item key to be removed or the target to be removed
*/
removeAllListeners (key) {
super.removeAll(key);
+11 -1
View File
@@ -43,6 +43,10 @@ function getUuidFromURL (url) {
return "";
}
/**
* @en The md5 pipe in {{loader}}, it can transform the url to the real url with md5 suffix
* @zh {{loader}} 中的 md5 管道,可以将资源 url 转换到包含 md5 后缀版本
*/
export default class MD5Pipe implements IPipe {
static ID = ID;
@@ -72,7 +76,13 @@ export default class MD5Pipe implements IPipe {
return item;
}
transformURL (url, hashPatchInFolder) {
/**
* @en Transform an url to the real url with md5 suffix
* @zh 将一个 url 转换到包含 md5 后缀版本
* @param url The url to be parsed
* @param hashPatchInFolder NA
*/
transformURL (url, hashPatchInFolder?: boolean) {
let uuid = getUuidFromURL(url);
if (uuid) {
let isNativeAsset = !url.match(this.libraryBase);
+1 -1
View File
@@ -25,7 +25,7 @@
*/
/**
* @category loader
* @hidden
*/
import {pushToMap} from '../utils/misc';
+55 -57
View File
@@ -35,10 +35,11 @@ import { legacyCC } from '../global-exports';
const ItemState = LoadingItems.ItemState;
export interface IPipe {
id:string;
async:boolean;
handle (item:IItem, callback);
next?:IPipe;
id: string;
async: boolean;
handle (item: IItem, callback);
next?: IPipe|null;
pipeline?: Pipeline|null;
}
function flow (pipe, item) {
@@ -117,20 +118,25 @@ function flow (pipe, item) {
* 一个 item 列表可以在 pipeline 中流动,它将输出加载项经过所有 pipe 之后的结果。<br/>
* 它们穿过 pipeline 就像水在管子里流动,将会按顺序流过每个 pipe。<br/>
* 最后当所有加载项都流出 pipeline 时,整个加载流程就结束了。
* @class Pipeline
*/
export class Pipeline {
/**
* @en The item states of the LoadingItems, its value could be {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}}
* @zh LoadingItems 队列中的加载项状态,状态的值可能是 {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}}
*/
static ItemState = ItemState;
protected _pipes:Array<IPipe>;
protected _pipes: Array<IPipe>;
public _cache = createMap(true);
/**
* 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。<br/>
* @en The constructor of the Pipeline, the order of pipes will remain as given.
* A pipe is an {{IPipe}} object which must have an `id` and a `handle` function, the `id` must be unique.
* It should also include an `async` property to identify whether the pipe's `handle` function is asynchronous.
* @zh 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。<br/>
* 一个 pipe 就是一个对象,它包含了字符串类型的 ‘id’ 和 ‘handle’ 函数,在 pipeline 中 id 必须是唯一的。<br/>
* 它还可以包括 ‘async’ 属性以确定它是否是一个异步过程。
*
* @param {Array} pipes
* @param pipes All pipes for constructing the pipeline
* @example
* ```
* let pipeline = new Pipeline([
@@ -143,7 +149,7 @@ export class Pipeline {
* ]);
* ```
*/
constructor (pipes) {
constructor (pipes: IPipe[]) {
this._pipes = pipes;
for (let i = 0; i < pipes.length; ++i) {
@@ -159,17 +165,14 @@ export class Pipeline {
}
/**
* @en
* Insert a new pipe at the given index of the pipeline. <br/>
* @en Insert a new pipe at the given index of the pipeline. <br/>
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* @zh
* 在给定的索引位置插入一个新的 pipe。<br/>
* @zh 在给定的索引位置插入一个新的 pipe。<br/>
* 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。
* @method insertPipe
* @param {Object} pipe The pipe to be inserted
* @param {Number} index The index to insert
* @param pipe The pipe to be inserted
* @param index The index to insert
*/
insertPipe (pipe, index) {
insertPipe (pipe: IPipe, index: number) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id || index > this._pipes.length) {
legacyCC.warnID(4921);
@@ -183,12 +186,12 @@ export class Pipeline {
pipe.pipeline = this;
let nextPipe:IPipe|null = null;
let nextPipe: IPipe|null = null;
if (index < this._pipes.length) {
nextPipe = this._pipes[index];
}
let previousPipe:IPipe|null = null;
let previousPipe: IPipe|null = null;
if (index > 0) {
previousPipe = this._pipes[index-1];
}
@@ -202,15 +205,12 @@ export class Pipeline {
}
/**
* @en
* Insert a pipe to the end of an existing pipe. The existing pipe must be a valid pipe in the pipeline.
* @zh
* 在当前 pipeline 的一个已知 pipe 后面插入一个新的 pipe。
* @method insertPipeAfter
* @param {Object} refPipe An existing pipe in the pipeline.
* @param {Object} newPipe The pipe to be inserted.
* @en Insert a pipe to the end of an existing pipe. The existing pipe must be a valid pipe in the pipeline.
* @zh 在当前 pipeline 的一个已知 pipe 后面插入一个新的 pipe。
* @param refPipe An existing pipe in the pipeline.
* @param newPipe The pipe to be inserted.
*/
insertPipeAfter (refPipe, newPipe) {
insertPipeAfter (refPipe: IPipe, newPipe: IPipe) {
let index = this._pipes.indexOf(refPipe);
if (index < 0) {
return;
@@ -219,16 +219,13 @@ export class Pipeline {
}
/**
* @en
* Add a new pipe at the end of the pipeline. <br/>
* @en Add a new pipe at the end of the pipeline. <br/>
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* @zh
* 添加一个新的 pipe 到 pipeline 尾部。 <br/>
* @zh 添加一个新的 pipe 到 pipeline 尾部。 <br/>
* 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。
* @method appendPipe
* @param {Object} pipe The pipe to be appended
* @param pipe The pipe to be appended
*/
appendPipe (pipe) {
appendPipe (pipe: IPipe) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
@@ -257,7 +254,7 @@ export class Pipeline {
* 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。<br/>
* 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。<br/>
* 该对象可以包含任何附加属性。
* @param {Array} items
* @param items The {{IItem}} to be appended to the current pipeline
* @example
* ```
* pipeline.flowIn([
@@ -271,7 +268,7 @@ export class Pipeline {
* ]);
* ```
*/
flowIn (items) {
flowIn (items: Array<IItem>) {
let i, pipe = this._pipes[0], item;
if (pipe) {
// Cache all items first, in case synchronous loading flow same item repeatly
@@ -303,12 +300,12 @@ export class Pipeline {
* 这个 API 的使用通常是为了加载依赖项。<br/>
* 例如:<br/>
* 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。
* @deprecated since v1.3
* @param {Array} urlList
* @param {Function} callback
* @return {Array} Items accepted by the pipeline
* @param owner The owner item
* @param urlList The list of urls to be appended as dependencies of the owner.
* @param callback The callback to be invoked when all dependencies are completed.
* @return Items accepted by the pipeline
*/
flowInDeps (owner, urlList, callback) {
flowInDeps (owner: IItem, urlList: object[], callback: Function): IItem[] {
let deps = LoadingItems.create(this, function (errors, items) {
callback(errors, items);
items.destroy();
@@ -316,7 +313,12 @@ export class Pipeline {
return deps.append(urlList, owner);
}
flowOut (item) {
/**
* @en This function is invoked when an item has completed all pipes, it will flow out of the pipeline.
* @zh 这个函数会在 `item` 完成了所有管道,它会被标记为 `complete` 并流出管线。
* @param item The item which is completed
*/
flowOut (item: IItem) {
if (item.error) {
delete this._cache[item.id];
}
@@ -342,11 +344,10 @@ export class Pipeline {
* 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,<br/>
* 但是你可能希望他们源 item 已经通过并跳过所有 pipes,<br/>
* 这个时候就可以使用这个 API。
* @method copyItemStates
* @param {Object} srcItem The source item
* @param {Array|Object} dstItems A single destination item or an array of destination items
* @param srcItem The source item
* @param dstItems A single destination item or an array of destination items
*/
copyItemStates (srcItem, dstItems) {
copyItemStates (srcItem: IItem, dstItems: IItem|Array<IItem>) {
if (!(dstItems instanceof Array)) {
dstItems.states = srcItem.states;
return;
@@ -359,11 +360,9 @@ export class Pipeline {
/**
* @en Returns an item in pipeline.
* @zh 根据 id 获取一个 item
* @method getItem
* @param {Object} id The id of the item
* @return {Object}
* @param id The id of the item
*/
getItem (id) {
getItem (id: string): IItem|null {
let item = this._cache[id];
if (!item)
@@ -380,15 +379,14 @@ export class Pipeline {
* @en Removes an completed item in pipeline.
* It will only remove the cache in the pipeline or loader, its dependencies won't be released.
* cc.loader provided another method to completely cleanup the resource and its dependencies,
* please refer to [[CCLoader.release]]
* please refer to {{Loader.release}}
* @zh 移除指定的已完成 item。
* 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。
* cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 [[CCLoader.release]]
* @method removeItem
* @param {Object} id The id of the item
* @return {Boolean} succeed or not
* cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{Loader.release}}
* @param id The id of the item
* @return succeed or not
*/
removeItem (id) {
removeItem (id: string): boolean {
let removed = this._cache[id];
if (removed && removed.complete) {
delete this._cache[id];
+6 -6
View File
@@ -26,11 +26,11 @@
*/
/**
* @category loader
* @hidden
*/
import { EDITOR } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { warnID } from '../platform/debug';
/**
* A SAX Parser
@@ -75,7 +75,7 @@ class SAXParser {
/**
*
* cc.plistParser is a singleton object for parsing plist files
* plistParser is a singleton object for parsing plist files
* @class plistParser
* @extends SAXParser
*/
@@ -90,7 +90,7 @@ class PlistParser extends SAXParser {
let xmlDoc = this._parseXML(xmlTxt);
let plist = xmlDoc.documentElement;
if (plist.tagName !== 'plist') {
legacyCC.warnID(5100);
warnID(5100);
return {};
}
@@ -107,7 +107,7 @@ class PlistParser extends SAXParser {
}
_parseNode (node) {
let data:any = null, tagName = node.tagName;
let data: any = null, tagName = node.tagName;
if(tagName === "dict"){
data = this._parseDict(node);
}else if(tagName === "array"){
@@ -134,7 +134,7 @@ class PlistParser extends SAXParser {
}
_parseArray (node) {
let data:Array<any> = [];
let data: Array<any> = [];
for (let i = 0, len = node.childNodes.length; i < len; i++) {
let child = node.childNodes[i];
if (child.nodeType !== 1)
@@ -25,13 +25,13 @@
*/
/**
* @category loader
* @hidden
*/
import {createMap, getClassName, clear} from '../utils/js';
import { legacyCC } from '../global-exports';
let _tmpInfo:any = null;
let _tmpInfo: any = null;
function getItemDesc (item) {
if (item.uuid) {
+5 -5
View File
@@ -24,7 +24,7 @@
*/
/**
* @category loader
* @hidden
*/
import {urlAppendTimestamp} from './utils';
@@ -44,18 +44,18 @@ export default function (item, callback) {
callback(null, xhr.responseText);
}
else {
callback({status:xhr.status, errorMessage:errInfo + '(wrong status)'});
callback({status: xhr.status, errorMessage: errInfo + '(wrong status)'});
}
}
else {
callback({status:xhr.status, errorMessage:errInfo + '(wrong readyState)'});
callback({status: xhr.status, errorMessage: errInfo + '(wrong readyState)'});
}
};
xhr.onerror = function(){
callback({status:xhr.status, errorMessage:errInfo + '(error)'});
callback({status: xhr.status, errorMessage: errInfo + '(error)'});
};
xhr.ontimeout = function(){
callback({status:xhr.status, errorMessage:errInfo + '(time out)'});
callback({status: xhr.status, errorMessage: errInfo + '(time out)'});
};
xhr.send(null);
}
+8 -6
View File
@@ -24,12 +24,14 @@
THE SOFTWARE.
*/
import { legacyCC } from '../global-exports';
/**
* @category loader
* @hidden
*/
import { errorID } from "../platform/debug";
import { js } from "../utils/js";
import { Texture2D } from "../assets/texture-2d";
export class JsonUnpacker {
public jsons = {};
@@ -39,7 +41,7 @@ export class JsonUnpacker {
*/
load (indices, packedJson) {
if (packedJson.length !== indices.length) {
legacyCC.errorID(4915);
errorID(4915);
}
for (let i = 0; i < indices.length; i++) {
let key = indices[i];
@@ -64,7 +66,7 @@ export class TextureUnpacker {
load (indices, packedJson) {
let datas = packedJson.data;
if (datas.length !== indices.length) {
legacyCC.errorID(4915);
errorID(4915);
}
for (let i = 0; i < indices.length; i++) {
this.contents[indices[i]] = {base: datas[i][0], mipmaps: datas[i][1]};
@@ -75,7 +77,7 @@ export class TextureUnpacker {
let content = this.contents[key];
if (content) {
return {
__type__: legacyCC.js._getClassId(legacyCC.Texture2D),
__type__: js._getClassId(Texture2D),
content: content
};
}
+6 -5
View File
@@ -25,12 +25,13 @@
*/
/**
* 加载相关模块
* @category loader
*/
import { EDITOR } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { errorID } from '../platform/debug';
import { extname, stripSep } from '../utils/path';
/**
* @class url
@@ -70,20 +71,20 @@ let url = {
*/
raw: function (url) {
if (EDITOR && !this._rawAssets) {
legacyCC.errorID(7000);
errorID(7000);
return '';
}
url = this.normalize(url);
if ( !url.startsWith('resources/') ) {
legacyCC.errorID(EDITOR ? 7001 : 7002, url);
errorID(EDITOR ? 7001 : 7002, url);
}
else {
// Compatible with versions lower than 1.10
var uuid = legacyCC.loader._getResUuid(url.slice(10), legacyCC.Asset, null, true);
if (uuid) {
return legacyCC.AssetLibrary.getLibUrlNoExt(uuid, true) + legacyCC.path.extname(url);
return legacyCC.AssetLibrary.getLibUrlNoExt(uuid, true) + extname(url);
}
}
@@ -91,7 +92,7 @@ let url = {
},
_init: function (assets) {
this._rawAssets = legacyCC.path.stripSep(assets) + '/';
this._rawAssets = stripSep(assets) + '/';
}
}
+1 -1
View File
@@ -26,7 +26,7 @@
import { legacyCC } from '../global-exports';
/**
* @category loader
* @hidden
*/
let _noCacheRex = /\?/;
+3 -8
View File
@@ -25,7 +25,7 @@
*/
/**
* @category loader
* @hidden
*/
import * as js from '../utils/js';
@@ -54,7 +54,7 @@ function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) {
let depends;
let i, dependUuid;
// cache dependencies for auto release
let dependKeys:Array<string> = item.dependKeys = [];
let dependKeys: Array<string> = item.dependKeys = [];
if (deferredLoadRawAssetsInRuntime) {
depends = [];
@@ -169,12 +169,7 @@ function loadDepends (pipeline, item, asset, depends, callback) {
else {
// item was removed from cache, but ready in pipeline actually
let queue = LoadingItems.getQueue(item);
// Hack to get a better behavior
let list = queue._callbackTable[dependSrc];
if (list) {
list.unshift(loadCallback, loadCallbackCtx);
}
else {
if (queue) {
queue.addListener(dependSrc, loadCallback, loadCallbackCtx);
}
}
+2 -2
View File
@@ -361,8 +361,8 @@ replaceProperty(Color, 'Color', [
{
name: 'fromHex',
newName: 'fromHEX',
customFunction: function (...args: any) {
let arg1 = args[1].toString(16);
customFunction (...args: any) {
const arg1 = args[1].toString(16);
return legacyCC.Color.fromHEX(args[0], arg1);
},
},
+65 -80
View File
@@ -45,14 +45,14 @@ export class Quat extends ValueType {
/**
* @zh 获得指定四元数的拷贝
*/
public static clone <Out extends IQuatLike> (a: Out) {
public static clone<Out extends IQuatLike> (a: Out) {
return new Quat(a.x, a.y, a.z, a.w);
}
/**
* @zh 复制目标四元数
*/
public static copy <Out extends IQuatLike, QuatLike extends IQuatLike> (out: Out, a: QuatLike) {
public static copy<Out extends IQuatLike, QuatLike extends IQuatLike> (out: Out, a: QuatLike) {
out.x = a.x;
out.y = a.y;
out.z = a.z;
@@ -63,7 +63,7 @@ export class Quat extends ValueType {
/**
* @zh 设置四元数值
*/
public static set <Out extends IQuatLike> (out: Out, x: number, y: number, z: number, w: number) {
public static set<Out extends IQuatLike> (out: Out, x: number, y: number, z: number, w: number) {
out.x = x;
out.y = y;
out.z = z;
@@ -74,7 +74,7 @@ export class Quat extends ValueType {
/**
* @zh 将目标赋值为单位四元数
*/
public static identity <Out extends IQuatLike> (out: Out) {
public static identity<Out extends IQuatLike> (out: Out) {
out.x = 0;
out.y = 0;
out.z = 0;
@@ -85,7 +85,7 @@ export class Quat extends ValueType {
/**
* @zh 设置四元数为两向量间的最短路径旋转,默认两向量都已归一化
*/
public static rotationTo <Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, a: VecLike, b: VecLike) {
public static rotationTo<Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, a: VecLike, b: VecLike) {
const dot = Vec3.dot(a, b);
if (dot < -0.999999) {
Vec3.cross(v3_1, Vec3.UNIT_X, a);
@@ -117,7 +117,7 @@ export class Quat extends ValueType {
* @param q 源四元数
* @return 旋转弧度
*/
public static getAxisAngle <Out extends IQuatLike, VecLike extends IVec3Like> (outAxis: VecLike, q: Out) {
public static getAxisAngle<Out extends IQuatLike, VecLike extends IVec3Like> (outAxis: VecLike, q: Out) {
const rad = Math.acos(q.w) * 2.0;
const s = Math.sin(rad / 2.0);
if (s !== 0.0) {
@@ -136,7 +136,7 @@ export class Quat extends ValueType {
/**
* @zh 四元数乘法
*/
public static multiply <Out extends IQuatLike, QuatLike_1 extends IQuatLike, QuatLike_2 extends IQuatLike> (out: Out, a: QuatLike_1, b: QuatLike_2) {
public static multiply<Out extends IQuatLike, QuatLike_1 extends IQuatLike, QuatLike_2 extends IQuatLike> (out: Out, a: QuatLike_1, b: QuatLike_2) {
const x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;
const y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;
const z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;
@@ -151,7 +151,7 @@ export class Quat extends ValueType {
/**
* @zh 四元数标量乘法
*/
public static multiplyScalar <Out extends IQuatLike> (out: Out, a: Out, b: number) {
public static multiplyScalar<Out extends IQuatLike> (out: Out, a: Out, b: number) {
out.x = a.x * b;
out.y = a.y * b;
out.z = a.z * b;
@@ -162,7 +162,7 @@ export class Quat extends ValueType {
/**
* @zh 四元数乘加:A + B * scale
*/
public static scaleAndAdd <Out extends IQuatLike> (out: Out, a: Out, b: Out, scale: number) {
public static scaleAndAdd<Out extends IQuatLike> (out: Out, a: Out, b: Out, scale: number) {
out.x = a.x + b.x * scale;
out.y = a.y + b.y * scale;
out.z = a.z + b.z * scale;
@@ -174,7 +174,7 @@ export class Quat extends ValueType {
* @zh 绕 X 轴旋转指定四元数
* @param rad 旋转弧度
*/
public static rotateX <Out extends IQuatLike> (out: Out, a: Out, rad: number) {
public static rotateX<Out extends IQuatLike> (out: Out, a: Out, rad: number) {
rad *= 0.5;
const bx = Math.sin(rad);
@@ -192,7 +192,7 @@ export class Quat extends ValueType {
* @zh 绕 Y 轴旋转指定四元数
* @param rad 旋转弧度
*/
public static rotateY <Out extends IQuatLike> (out: Out, a: Out, rad: number) {
public static rotateY<Out extends IQuatLike> (out: Out, a: Out, rad: number) {
rad *= 0.5;
const by = Math.sin(rad);
@@ -210,7 +210,7 @@ export class Quat extends ValueType {
* @zh 绕 Z 轴旋转指定四元数
* @param rad 旋转弧度
*/
public static rotateZ <Out extends IQuatLike> (out: Out, a: Out, rad: number) {
public static rotateZ<Out extends IQuatLike> (out: Out, a: Out, rad: number) {
rad *= 0.5;
const bz = Math.sin(rad);
@@ -229,7 +229,7 @@ export class Quat extends ValueType {
* @param axis 旋转轴,默认已归一化
* @param rad 旋转弧度
*/
public static rotateAround <Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, rot: Out, axis: VecLike, rad: number) {
public static rotateAround<Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, rot: Out, axis: VecLike, rad: number) {
// get inv-axis (local to rot)
Quat.invert(qt_1, rot);
Vec3.transformQuat(v3_1, axis, qt_1);
@@ -244,7 +244,7 @@ export class Quat extends ValueType {
* @param axis 旋转轴
* @param rad 旋转弧度
*/
public static rotateAroundLocal <Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, rot: Out, axis: VecLike, rad: number) {
public static rotateAroundLocal<Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, rot: Out, axis: VecLike, rad: number) {
Quat.fromAxisAngle(qt_1, axis, rad);
Quat.multiply(out, rot, qt_1);
return out;
@@ -253,7 +253,7 @@ export class Quat extends ValueType {
/**
* @zh 根据 xyz 分量计算 w 分量,默认已归一化
*/
public static calculateW <Out extends IQuatLike> (out: Out, a: Out) {
public static calculateW<Out extends IQuatLike> (out: Out, a: Out) {
out.x = a.x;
out.y = a.y;
@@ -265,14 +265,14 @@ export class Quat extends ValueType {
/**
* @zh 四元数点积(数量积)
*/
public static dot <Out extends IQuatLike> (a: Out, b: Out) {
public static dot<Out extends IQuatLike> (a: Out, b: Out) {
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
/**
* @zh 逐元素线性插值: A + t * (B - A)
*/
public static lerp <Out extends IQuatLike> (out: Out, a: Out, b: Out, t: number) {
public static lerp<Out extends IQuatLike> (out: Out, a: Out, b: Out, t: number) {
out.x = a.x + t * (b.x - a.x);
out.y = a.y + t * (b.y - a.y);
out.z = a.z + t * (b.z - a.z);
@@ -283,23 +283,27 @@ export class Quat extends ValueType {
/**
* @zh 四元数球面插值
*/
public static slerp <Out extends IQuatLike, QuatLike_1 extends IQuatLike, QuatLike_2 extends IQuatLike>
(out: Out, a: QuatLike_1, b: QuatLike_2, t: number) {
public static slerp<Out extends IQuatLike, QuatLike_1 extends IQuatLike, QuatLike_2 extends IQuatLike>
(out: Out, a: QuatLike_1, b: QuatLike_2, t: number) {
// benchmarks:
// http://jsperf.com/quaternion-slerp-implementations
let scale0 = 0;
let scale1 = 0;
let bx = b.x;
let by = b.y;
let bz = b.z;
let bw = b.w;
// calc cosine
let cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
// adjust signs (if necessary)
if (cosom < 0.0) {
cosom = -cosom;
b.x = -b.x;
b.y = -b.y;
b.z = -b.z;
b.w = -b.w;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
// calculate coefficients
if ((1.0 - cosom) > 0.000001) {
@@ -315,10 +319,10 @@ export class Quat extends ValueType {
scale1 = t;
}
// calculate final values
out.x = scale0 * a.x + scale1 * b.x;
out.y = scale0 * a.y + scale1 * b.y;
out.z = scale0 * a.z + scale1 * b.z;
out.w = scale0 * a.w + scale1 * b.w;
out.x = scale0 * a.x + scale1 * bx;
out.y = scale0 * a.y + scale1 * by;
out.z = scale0 * a.z + scale1 * bz;
out.w = scale0 * a.w + scale1 * bw;
return out;
}
@@ -326,7 +330,7 @@ export class Quat extends ValueType {
/**
* @zh 带两个控制点的四元数球面插值
*/
public static sqlerp <Out extends IQuatLike> (out: Out, a: Out, b: Out, c: Out, d: Out, t: number) {
public static sqlerp<Out extends IQuatLike> (out: Out, a: Out, b: Out, c: Out, d: Out, t: number) {
Quat.slerp(qt_1, a, d, t);
Quat.slerp(qt_2, b, c, t);
Quat.slerp(out, qt_1, qt_2, 2 * t * (1 - t));
@@ -336,7 +340,7 @@ export class Quat extends ValueType {
/**
* @zh 四元数求逆
*/
public static invert <Out extends IQuatLike, QuatLike extends IQuatLike> (out: Out, a: QuatLike) {
public static invert<Out extends IQuatLike, QuatLike extends IQuatLike> (out: Out, a: QuatLike) {
const dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
const invDot = dot ? 1.0 / dot : 0;
@@ -352,7 +356,7 @@ export class Quat extends ValueType {
/**
* @zh 求共轭四元数,对单位四元数与求逆等价,但更高效
*/
public static conjugate <Out extends IQuatLike> (out: Out, a: Out) {
public static conjugate<Out extends IQuatLike> (out: Out, a: Out) {
out.x = -a.x;
out.y = -a.y;
out.z = -a.z;
@@ -363,21 +367,21 @@ export class Quat extends ValueType {
/**
* @zh 求四元数长度
*/
public static len <Out extends IQuatLike> (a: Out) {
public static len<Out extends IQuatLike> (a: Out) {
return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
}
/**
* @zh 求四元数长度平方
*/
public static lengthSqr <Out extends IQuatLike> (a: Out) {
public static lengthSqr<Out extends IQuatLike> (a: Out) {
return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
}
/**
* @zh 归一化四元数
*/
public static normalize <Out extends IQuatLike> (out: Out, a: Out) {
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;
if (len > 0) {
len = 1 / Math.sqrt(len);
@@ -392,7 +396,7 @@ export class Quat extends ValueType {
/**
* @zh 根据本地坐标轴朝向计算四元数,默认三向量都已归一化且相互垂直
*/
public static fromAxes <Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, xAxis: VecLike, yAxis: VecLike, zAxis: VecLike) {
public static fromAxes<Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, xAxis: VecLike, yAxis: VecLike, zAxis: VecLike) {
Mat3.set(m3_1,
xAxis.x, xAxis.y, xAxis.z,
yAxis.x, yAxis.y, yAxis.z,
@@ -406,7 +410,7 @@ export class Quat extends ValueType {
* @param view 视口面向的前方向,必须归一化
* @param up 视口的上方向,必须归一化,默认为 (0, 1, 0)
*/
public static fromViewUp <Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, view: VecLike, up?: Vec3) {
public static fromViewUp<Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, view: VecLike, up?: Vec3) {
Mat3.fromViewUp(m3_1, view, up);
return Quat.normalize(out, Quat.fromMat3(out, m3_1));
}
@@ -414,7 +418,7 @@ export class Quat extends ValueType {
/**
* @zh 根据旋转轴和旋转弧度计算四元数
*/
public static fromAxisAngle <Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, axis: VecLike, rad: number) {
public static fromAxisAngle<Out extends IQuatLike, VecLike extends IVec3Like> (out: Out, axis: VecLike, rad: number) {
rad = rad * 0.5;
const s = Math.sin(rad);
out.x = s * axis.x;
@@ -427,7 +431,7 @@ export class Quat extends ValueType {
/**
* @zh 根据三维矩阵信息计算四元数,默认输入矩阵不含有缩放信息
*/
public static fromMat3 <Out extends IQuatLike> (out: Out, m: Mat3) {
public static fromMat3<Out extends IQuatLike> (out: Out, m: Mat3) {
const {
m00: m00, m03: m01, m06: m02,
m01: m10, m04: m11, m07: m12,
@@ -475,7 +479,7 @@ export class Quat extends ValueType {
/**
* @zh 根据欧拉角信息计算四元数,旋转顺序为 YZX
*/
public static fromEuler <Out extends IQuatLike> (out: Out, x: number, y: number, z: number) {
public static fromEuler<Out extends IQuatLike> (out: Out, x: number, y: number, z: number) {
x *= halfToRad;
y *= halfToRad;
z *= halfToRad;
@@ -498,7 +502,7 @@ export class Quat extends ValueType {
/**
* @zh 返回定义此四元数的坐标系 X 轴向量
*/
public static toAxisX <Out extends IQuatLike, VecLike extends IVec3Like> (out: VecLike, q: Out) {
public static toAxisX (out: IVec3Like, q: IQuatLike) {
const fy = 2.0 * q.y;
const fz = 2.0 * q.z;
out.x = 1.0 - fy * q.y - fz * q.z;
@@ -511,7 +515,7 @@ export class Quat extends ValueType {
/**
* @zh 返回定义此四元数的坐标系 Y 轴向量
*/
public static toAxisY <Out extends IQuatLike, VecLike extends IVec3Like> (out: VecLike, q: Out) {
public static toAxisY (out: IVec3Like, q: IQuatLike) {
const fx = 2.0 * q.x;
const fy = 2.0 * q.y;
const fz = 2.0 * q.z;
@@ -525,7 +529,7 @@ export class Quat extends ValueType {
/**
* @zh 返回定义此四元数的坐标系 Z 轴向量
*/
public static toAxisZ <Out extends IQuatLike, VecLike extends IVec3Like> (out: VecLike, q: Out) {
public static toAxisZ (out: IVec3Like, q: IQuatLike) {
const fx = 2.0 * q.x;
const fy = 2.0 * q.y;
const fz = 2.0 * q.z;
@@ -540,7 +544,7 @@ export class Quat extends ValueType {
* @zh 根据四元数计算欧拉角,返回角度 x, y 在 [-180, 180] 区间内, z 默认在 [-90, 90] 区间内,旋转顺序为 YZX
* @param outerZ z 取值范围区间改为 [-180, -90] U [90, 180]
*/
public static toEuler <Out extends IVec3Like> (out: Out, q: IQuatLike, outerZ?: boolean) {
public static toEuler (out: IVec3Like, q: IQuatLike, outerZ?: boolean) {
const { x, y, z, w } = q;
let bank = 0;
let heading = 0;
@@ -575,7 +579,7 @@ export class Quat extends ValueType {
* @zh 四元数转数组
* @param ofs 数组内的起始偏移量
*/
public static toArray <Out extends IWritableArrayLike<number>> (out: Out, q: IQuatLike, ofs = 0) {
public static toArray<Out extends IWritableArrayLike<number>> (out: Out, q: IQuatLike, ofs = 0) {
out[ofs + 0] = q.x;
out[ofs + 1] = q.y;
out[ofs + 2] = q.z;
@@ -587,7 +591,7 @@ export class Quat extends ValueType {
* @zh 数组转四元数
* @param ofs 数组起始偏移量
*/
public static fromArray <Out extends IQuatLike> (out: Out, arr: IWritableArrayLike<number>, ofs = 0) {
public static fromArray (out: IQuatLike, arr: IWritableArrayLike<number>, ofs = 0) {
out.x = arr[ofs + 0];
out.y = arr[ofs + 1];
out.z = arr[ofs + 2];
@@ -598,14 +602,14 @@ export class Quat extends ValueType {
/**
* @zh 四元数等价判断
*/
public static strictEquals <Out extends IQuatLike> (a: Out, b: Out) {
public static strictEquals (a: IQuatLike, b: IQuatLike) {
return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
}
/**
* @zh 排除浮点数误差的四元数近似等价判断
*/
public static equals <Out extends IQuatLike> (a: Out, b: Out, epsilon = EPSILON) {
public static equals (a: IQuatLike, b: IQuatLike, epsilon = EPSILON) {
return (Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) &&
Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) &&
Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) &&
@@ -636,7 +640,7 @@ export class Quat extends ValueType {
constructor (x?: number, y?: number, z?: number, w?: number);
constructor (x?: number | Quat, y?: number, z?: number, w?: number) {
constructor (x?: number | IQuatLike, y?: number, z?: number, w?: number) {
super();
if (x && typeof x === 'object') {
this.x = x.x;
@@ -721,46 +725,27 @@ export class Quat extends ValueType {
}
/**
* @zh 根据指定的插值比率,从当前四元数到目标四元数之间做插值。
* @zh 根据指定的插值比率,从当前四元数到目标四元数之间做线性插值。
* @param to 目标四元数。
* @param ratio 插值比率,范围为 [0,1]。
*/
public lerp (to: Quat, ratio: number) {
let scale0 = 0;
let scale1 = 0;
// calc cosine
let cosom = this.x * to.x + this.y * to.y + this.z * to.z + this.w * to.w;
// adjust signs (if necessary)
if (cosom < 0.0) {
cosom = -cosom;
to.x = -to.x;
to.y = -to.y;
to.z = -to.z;
to.w = -to.w;
}
// calculate coefficients
if ((1.0 - cosom) > 0.000001) {
// standard case (slerp)
const omega = Math.acos(cosom);
const sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - ratio) * omega) / sinom;
scale1 = Math.sin(ratio * omega) / sinom;
} else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0 - ratio;
scale1 = ratio;
}
// calculate final values
this.x = scale0 * this.x + scale1 * to.x;
this.y = scale0 * this.y + scale1 * to.y;
this.z = scale0 * this.z + scale1 * to.z;
this.w = scale0 * this.w + scale1 * to.w;
this.x = this.x + ratio * (to.x - this.x);
this.y = this.y + ratio * (to.y - this.y);
this.z = this.z + ratio * (to.z - this.z);
this.w = this.w + ratio * (to.w - this.w);
return this;
}
/**
* @zh 根据指定的插值比率,从当前四元数到目标四元数之间做球面插值。
* @param to 目标四元数。
* @param ratio 插值比率,范围为 [0,1]。
*/
public slerp (to: Quat, ratio: number) {
return Quat.slerp(this, this, to, ratio);
}
/**
* @zh 求四元数长度
*/
+5 -5
View File
@@ -358,7 +358,7 @@ export class Vec3 extends ValueType {
const y = a.y;
const z = a.z;
let rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
rhw = rhw ? 1 / rhw : 1;
rhw = rhw ? Math.abs(1 / rhw) : 1;
out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw;
out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw;
out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw;
@@ -373,7 +373,7 @@ export class Vec3 extends ValueType {
const y = a.y;
const z = a.z;
let rhw = m.m03 * x + m.m07 * y + m.m11 * z;
rhw = rhw ? 1 / rhw : 1;
rhw = rhw ? Math.abs(1 / rhw) : 1;
out.x = (m.m00 * x + m.m04 * y + m.m08 * z) * rhw;
out.y = (m.m01 * x + m.m05 * y + m.m09 * z) * rhw;
out.z = (m.m02 * x + m.m06 * y + m.m10 * z) * rhw;
@@ -400,9 +400,9 @@ export class Vec3 extends ValueType {
const x = v.x;
const y = v.y;
const z = v.z;
out.x = m.m00 * x + m.m01 * y + m.m02 * z + m.m03;
out.y = m.m04 * x + m.m05 * y + m.m06 * z + m.m07;
out.x = m.m08 * x + m.m09 * y + m.m10 * z + m.m11;
out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12;
out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13;
out.x = m.m02 * x + m.m06 * y + m.m10 * z + m.m14;
return out;
}
+1 -1
View File
@@ -196,7 +196,7 @@ export class ForwardStage extends RenderStage {
this._pipeline.lightBatchQueue.recordCommandBuffer(cmdBuff);
if (camera.visibility & Layers.BitMask.DEFAULT) {
cmdBuff.execute(planarShadow.cmdBuffs.array, planarShadow.cmdBuffCount);
planarShadow.recordCommandBuffer(cmdBuff);
}
this._renderQueues[1].recordCommandBuffer(this._device!, this._framebuffer.renderPass!, cmdBuff);
cmdBuff.endRenderPass();
+2 -1
View File
@@ -2,7 +2,8 @@
* @category pipeline
*/
export { RenderPassStage, JOINT_UNIFORM_CAPACITY as JointUniformCapacity } from './define';
import * as pipelineDefine from './define';
export const pipeline = pipelineDefine;
export { RenderPipeline } from './render-pipeline';
export { RenderFlow } from './render-flow';
+10 -4
View File
@@ -16,6 +16,7 @@ export interface IInstancedItem {
vb: GFXBuffer;
data: Uint8Array;
ia: GFXInputAssembler;
stride: number;
}
const INITIAL_CAPACITY = 32;
@@ -40,21 +41,26 @@ export class InstancedBuffer {
}
public merge (subModel: SubModel, attrs: IInstancedAttributeBlock, pso: GFXPipelineState) {
if (!this.pso) { this.pso = pso; }
const stride = attrs.buffer.length;
if (!stride) { return; } // we assume per-instance attributes are always present
if (!this.pso) { this.pso = pso; }
const sourceIA = subModel.inputAssembler!;
for (let i = 0; i < this.instances.length; ++i) {
const instance = this.instances[i];
if (instance.ia.indexBuffer !== sourceIA.indexBuffer || instance.count >= MAX_CAPACITY) { continue; }
if (instance.stride !== stride) {
// console.error(`instanced buffer stride mismatch! ${stride}/${instance.stride}`);
return;
}
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity <<= 1;
const newSize = stride * instance.capacity;
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.data.set(attrs.buffer, stride * instance.count++);
instance.data.set(attrs.buffer, instance.stride * instance.count++);
return;
}
@@ -86,7 +92,7 @@ export class InstancedBuffer {
vertexBuffers.push(vb);
const ia = device.createInputAssembler({ attributes, vertexBuffers, indexBuffer });
this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia });
this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia, stride });
}
public uploadBuffers () {
+10 -8
View File
@@ -45,14 +45,16 @@ export class RenderInstancedQueue {
const it = this.queue.values(); let res = it.next();
while (!res.done) {
const { instances, pso } = res.value;
res.value.uploadBuffers();
cmdBuff.bindPipelineState(pso!);
cmdBuff.bindBindingLayout(pso!.pipelineLayout.layouts[0]);
for (let b = 0; b < instances.length; ++b) {
const instance = instances[b];
if (!instance.count) { continue; }
cmdBuff.bindInputAssembler(instance.ia);
cmdBuff.draw(instance.ia);
if (pso) {
res.value.uploadBuffers();
cmdBuff.bindPipelineState(pso);
cmdBuff.bindBindingLayout(pso.pipelineLayout.layouts[0]);
for (let b = 0; b < instances.length; ++b) {
const instance = instances[b];
if (!instance.count) { continue; }
cmdBuff.bindInputAssembler(instance.ia);
cmdBuff.draw(instance.ia);
}
}
res = it.next();
}
@@ -187,8 +187,8 @@ export class EventListener {
* <p><br/>
* Sets paused state for the listener<br/>
* The paused state is only used for scene graph priority listeners.<br/>
* `EventDispatcher::resumeAllEventListenersForTarget(node)` will set the paused state to `true`,<br/>
* while `EventDispatcher::pauseAllEventListenersForTarget(node)` will set it to `false`.<br/>
* `EventDispatcher.resumeAllEventListenersForTarget(node)` will set the paused state to `true`,<br/>
* while `EventDispatcher.pauseAllEventListenersForTarget(node)` will set it to `false`.<br/>
* @note 1) Fixed priority listeners will never get paused. If a fixed priority doesn't want to receive events,<br/>
* call `setEnabled(false)` instead.<br/>
* 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners<br/>
+1 -1
View File
@@ -43,7 +43,7 @@ export class PassInstance extends Pass {
private _dontNotify = false;
constructor (parent: Pass, owner: MaterialInstance) {
super(parent.device);
super(parent.root);
this._parent = parent;
this._owner = owner;
this._doInit(this._parent, true); // defines may change now
+11 -8
View File
@@ -35,7 +35,7 @@ import { GFXBindingLayout, IGFXBinding, IGFXBindingLayoutInfo } from '../../gfx/
import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer';
import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState,
GFXGetTypeSize, GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define';
import { GFXFeature } from '../../gfx/device';
import { GFXFeature, GFXDevice } from '../../gfx/device';
import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState,
GFXRasterizerState } from '../../gfx/pipeline-state';
import { GFXSampler } from '../../gfx/sampler';
@@ -187,6 +187,7 @@ export class Pass {
protected _hash = 0;
// external references
protected _root: Root;
protected _device: GFXDevice;
protected _shader: GFXShader | null = null;
// for dynamic batching
protected _batchedBuffer: BatchedBuffer | null = null;
@@ -194,6 +195,7 @@ export class Pass {
public constructor (root: Root) {
this._root = root;
this._device = root.device;
}
/**
@@ -438,7 +440,7 @@ export class Pass {
const texture = builtinResMgr.get<TextureBase>(texName);
const textureView = texture && texture.getGFXTextureView()!;
const samplerHash = info && (info.samplerHash !== undefined) ? info.samplerHash : texture.getSamplerHash();
const sampler = samplerLib.getSampler(this._root.device, samplerHash);
const sampler = samplerLib.getSampler(this._device, samplerHash);
this._textureViews[binding] = textureView;
this._samplers[binding] = sampler;
for (let i = 0; i < this._resources.length; i++) {
@@ -491,7 +493,7 @@ export class Pass {
const pipeline = this._root.pipeline;
if (!pipeline) { return null; }
this._dynamicBatchingSync();
const res = programLib.getGFXShader(this._root.device, this._programName, this._defines, pipeline);
const res = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
if (!res.shader) { console.warn(`create shader ${this._programName} failed`); return false; }
this._shader = res.shader; this._bindings = res.bindings;
return true;
@@ -513,7 +515,7 @@ export class Pass {
const shader = res && res.shader || this._shader!;
_blInfo.bindings = res && res.bindings || this._bindings;
// bind resources
const bindingLayout = this._root.device.createBindingLayout(_blInfo);
const bindingLayout = this._device.createBindingLayout(_blInfo);
for (const b in this._buffers) {
bindingLayout.bindBuffer(parseInt(b), this._buffers[b]);
}
@@ -562,7 +564,7 @@ export class Pass {
this._shaderInfo = programLib.getTemplate(info.program);
this._properties = info.properties || this._properties;
// pipeline state
const device = this._root.device;
const device = this._device;
Pass.fillinPipelineInfo(this, info);
if (info.stateOverrides) { Pass.fillinPipelineInfo(this, info.stateOverrides); }
this._hash = Pass.getPassHash(this);
@@ -593,7 +595,7 @@ export class Pass {
protected _dynamicBatchingSync () {
if (this._defines.USE_INSTANCING) {
if (!this._root.device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) {
if (!this._device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) {
this._defines.USE_INSTANCING = false;
} else if (!this._instancedBuffer) {
this._instancedBuffer = new InstancedBuffer(this);
@@ -628,7 +630,7 @@ export class Pass {
const patch = patches[i];
this._defines[patch.name] = patch.value;
}
const res = programLib.getGFXShader(this._root.device, this._programName, this._defines, pipeline);
const res = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
for (let i = 0; i < patches.length; i++) {
const patch = patches[i];
delete this._defines[patch.name];
@@ -647,7 +649,8 @@ export class Pass {
get customizations () { return this._customizations; }
get phase () { return this._phase; }
// infos
get device () { return this._root.device; }
get root () { return this._root; }
get device () { return this._device; }
get shaderInfo () { return this._shaderInfo; }
get program () { return this._programName; }
get properties () { return this._properties; }
@@ -44,6 +44,7 @@ import { IAnimInfo, IJointTextureHandle, jointTextureSamplerHash } from './skele
import { MorphModel } from './morph-model';
import { IPSOCreateInfo } from '../scene/submodel';
import { legacyCC } from '../../global-exports';
import { IGFXAttribute } from '../../gfx';
interface IJointsInfo {
buffer: GFXBuffer | null;
@@ -131,9 +132,8 @@ export class BakedSkinningModel extends MorphModel {
const idx = this._instAnimInfoIdx;
if (idx >= 0) {
const view = this.instancedAttributes.list[idx].view;
view[0] = view[1] * info.data[0] + view[2];
}
if (info.dirty) {
view[0] = info.data[0];
} else if (info.dirty) {
info.buffer.update(info.data);
info.dirty = false;
}
@@ -167,20 +167,12 @@ export class BakedSkinningModel extends MorphModel {
if (oldTex && oldTex !== texture) { this._dataPoolManager.jointTexturePool.releaseHandle(oldTex); }
this._jointsMedium.texture = texture;
if (!texture) { return; }
const { buffer, jointTextureInfo: jointTextureInfo } = this._jointsMedium;
const { buffer, jointTextureInfo } = this._jointsMedium;
jointTextureInfo[0] = texture.handle.texture.width;
jointTextureInfo[1] = this._skeleton!.joints.length;
jointTextureInfo[2] = texture.pixelOffset + 0.1; // guard against floor() underflow
jointTextureInfo[3] = 1 / jointTextureInfo[0];
const idx = this._instAnimInfoIdx;
if (idx >= 0) { // update instancing data too
const info = this._jointsMedium.animInfo;
const view = this.instancedAttributes.list[idx].view;
const pixelsPerJoint = this._dataPoolManager.jointTexturePool.pixelsPerJoint;
view[1] = pixelsPerJoint * jointTextureInfo[1];
view[2] = jointTextureInfo[2];
view[0] = view[1] * info.data[0] + view[2];
}
this.updateInstancedJointTextureInfo();
if (buffer) { buffer.update(jointTextureInfo); }
const tv = texture.handle.texView;
@@ -220,8 +212,20 @@ export class BakedSkinningModel extends MorphModel {
}
}
protected updateInstancedAttributeList (psoCreateInfo: IPSOCreateInfo, pass: Pass) {
// super.updateInstancedAttributeList(psoCreateInfo, pass);
// this._instAnimInfoIdx = this.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO);
protected updateInstancedAttributeList (attributes: IGFXAttribute[], pass: Pass) {
super.updateInstancedAttributeList(attributes, pass);
this._instAnimInfoIdx = this.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO);
this.updateInstancedJointTextureInfo();
}
private updateInstancedJointTextureInfo () {
const { jointTextureInfo, animInfo } = this._jointsMedium;
const idx = this._instAnimInfoIdx;
if (idx >= 0) { // update instancing data too
const view = this.instancedAttributes.list[idx].view;
view[0] = animInfo.data[0];
view[1] = jointTextureInfo[1];
view[2] = jointTextureInfo[2];
}
}
}
+9 -9
View File
@@ -45,17 +45,17 @@ export class MorphModel extends Model {
private _launderMaterial (material: Material) {
return material;
if (this._usedMaterials.has(material)) {
return new MaterialInstance({
parent: material,
});
} else {
this._usedMaterials.add(material);
return material;
}
// if (this._usedMaterials.has(material)) {
// return new MaterialInstance({
// parent: material,
// });
// } else {
// this._usedMaterials.add(material);
// return material;
// }
}
public setMorphRendering (morphRendering: MorphRenderingInstance) {
this._morphRenderingInstance = morphRendering;
}
}
}
@@ -56,7 +56,7 @@ export function selectJointsMediumFormat (device: GFXDevice): GFXFormat {
}
// negative zeros cannot be decoded correctly at GLSL 100 minimum highp float precision, 1/1024
// and it has a significant effect on the final transformation
// and it has a significant impact on the final transformation
function makeStable (n: number) { return n ? n : 0; }
// Linear Blending Skinning
@@ -118,6 +118,13 @@ export const jointTextureSamplerHash = genSamplerHash([
GFXAddress.CLAMP,
]);
interface IInternalJointAnimInfo {
downstream?: Mat4; // downstream default pose, if present
curveData?: Mat4[]; // the nearest animation curve, if present
bindposeIdx: number; // index of the actual bindpose to use
bindposeCorrection?: Mat4; // correction factor from the original bindpose
}
export interface IJointTextureHandle {
pixelOffset: number;
refCount: number;
@@ -126,6 +133,7 @@ export interface IJointTextureHandle {
readyToBeDeleted: boolean;
handle: ITextureBufferHandle;
bounds: Map<number, aabb[]>;
animInfos?: IInternalJointAnimInfo[];
}
const v3_3 = new Vec3();
@@ -133,6 +141,7 @@ const v3_4 = new Vec3();
const v3_min = new Vec3();
const v3_max = new Vec3();
const m4_1 = new Mat4();
const m4_2 = new Mat4();
const ab_1 = new aabb();
export interface IChunkContent {
@@ -207,8 +216,9 @@ export class JointTexturePool {
if (texture && texture.bounds.has(mesh.hash)) { texture.refCount++; return texture; }
const { joints, bindposes } = skeleton;
let textureBuffer: Float32Array = null!; let buildTexture = false;
const jointCount = joints.length;
if (!texture) {
const bufSize = joints.length * 12;
const bufSize = jointCount * 12;
const customChunkIdx = this._chunkIdxMap.get(hash);
const handle = customChunkIdx !== undefined ?
this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) :
@@ -221,23 +231,19 @@ export class JointTexturePool {
Vec3.set(v3_min, Inf, Inf, Inf);
Vec3.set(v3_max, -Inf, -Inf, -Inf);
const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
for (let i = 0; i < joints.length; i++) {
const node = skinningRoot.getChildByPath(joints[i]);
const bound = boneSpaceBounds[i];
if (!node) { // don't skip null `bound` here, or it becomes mesh-specific
if (buildTexture) { uploadJointData(textureBuffer, 12 * i, Mat4.IDENTITY, i === 0); }
continue;
}
getWorldTransformUntilRoot(node, skinningRoot, m4_1);
for (let j = 0, offset = 0; j < jointCount; j++, offset += 12) {
const node = skinningRoot.getChildByPath(joints[j]);
const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : skeleton.inverseBindposes[j];
const bound = boneSpaceBounds[j];
if (bound) {
aabb.transform(ab_1, bound, m4_1);
aabb.transform(ab_1, bound, mat);
ab_1.getBoundary(v3_3, v3_4);
Vec3.min(v3_min, v3_min, v3_3);
Vec3.max(v3_max, v3_max, v3_4);
}
if (buildTexture) {
Mat4.multiply(m4_1, m4_1, bindposes[i]);
uploadJointData(textureBuffer, 12 * i, m4_1, i === 0);
if (node) { Mat4.multiply(mat, mat, bindposes[j]); }
uploadJointData(textureBuffer, offset, node ? mat : Mat4.IDENTITY, j === 0);
}
}
const bounds = [new aabb()]; texture.bounds.set(mesh.hash, bounds);
@@ -263,47 +269,50 @@ export class JointTexturePool {
const clipData = SkelAnimDataHub.getOrExtract(clip);
const frames = clipData.info.frames;
let textureBuffer: Float32Array = null!; let buildTexture = false;
const totalJoints = joints.length;
const jointCount = joints.length;
if (!texture) {
const bufSize = totalJoints * 12 * frames;
const bufSize = jointCount * 12 * frames;
const customChunkIdx = this._chunkIdxMap.get(hash);
const handle = customChunkIdx !== undefined ?
this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) :
this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
if (!handle) { return null; }
const animInfos = this._createAnimInfos(skeleton, clip, skinningRoot);
texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, bounds: new Map(),
skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle };
skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle, animInfos };
textureBuffer = new Float32Array(bufSize); buildTexture = true;
} else { texture.refCount++; }
const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
const bounds: aabb[] = []; texture.bounds.set(mesh.hash, bounds);
for (let fid = 0; fid < frames; fid++) {
for (let f = 0; f < frames; f++) {
bounds.push(new aabb(Inf, Inf, Inf, -Inf, -Inf, -Inf));
}
let offset = 0;
for (let frame = 0; frame < frames; frame++) {
const bound = bounds[frame];
for (let i = 0; i < totalJoints; i++, offset += 12) {
const nodeData = clipData.data[joints[i]];
if (!nodeData) { // don't skip null `boneSpaceBounds` here, or it becomes mesh-specific
const node = skinningRoot.getChildByPath(joints[i]); // fallback to default pose
const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : Mat4.IDENTITY;
if (buildTexture) { uploadJointData(textureBuffer, offset, mat, i === 0); }
continue;
for (let f = 0, offset = 0; f < frames; f++) {
const bound = bounds[f];
for (let j = 0; j < jointCount; j++, offset += 12) {
const { curveData, downstream, bindposeIdx, bindposeCorrection } = texture.animInfos![j];
let mat: Mat4; let transformValid = true;
if (curveData && downstream) { // curve & static two-way combination
mat = Mat4.multiply(m4_1, curveData[f], downstream);
} else if (curveData) { // there is a curve directly controlling the joint
mat = curveData[f];
} else if (downstream) { // fallback to default pose if no animation curve can be found upstream
mat = downstream;
} else { // bottom line: render the original mesh as-is
mat = skeleton.inverseBindposes[bindposeIdx];
transformValid = false;
}
const matrix = nodeData.worldMatrix.values as Mat4[];
const m = matrix[frame];
const boneSpaceBound = boneSpaceBounds[i];
const boneSpaceBound = boneSpaceBounds[j];
if (boneSpaceBound) {
aabb.transform(ab_1, boneSpaceBound, m);
const transform = bindposeCorrection ? Mat4.multiply(m4_2, mat, bindposeCorrection) : mat;
aabb.transform(ab_1, boneSpaceBound, transform);
ab_1.getBoundary(v3_3, v3_4);
Vec3.min(bound.center, bound.center, v3_3);
Vec3.max(bound.halfExtents, bound.halfExtents, v3_4);
}
if (buildTexture) {
const bindpose = bindposes[i];
Mat4.multiply(m4_1, m, bindpose);
uploadJointData(textureBuffer, offset, m4_1, i === 0);
if (transformValid) { Mat4.multiply(m4_1, mat, bindposes[bindposeIdx]); }
uploadJointData(textureBuffer, offset, transformValid ? m4_1 : Mat4.IDENTITY, j === 0);
}
}
aabb.fromPoints(bound, bound.center, bound.halfExtents);
@@ -318,9 +327,12 @@ export class JointTexturePool {
public releaseHandle (handle: IJointTextureHandle) {
if (handle.refCount > 0) { handle.refCount--; }
if (!handle.refCount && handle.readyToBeDeleted) {
const customChunkIdx = this._chunkIdxMap.get(handle.skeletonHash ^ handle.clipHash);
const hash = handle.skeletonHash ^ handle.clipHash;
const customChunkIdx = this._chunkIdxMap.get(hash);
(customChunkIdx !== undefined ? this._customPool : this._pool).free(handle.handle);
this._textureBuffers.delete(handle.skeletonHash ^ handle.clipHash);
if (this._textureBuffers.get(hash) === handle) {
this._textureBuffers.delete(hash);
}
}
}
@@ -359,6 +371,69 @@ export class JointTexturePool {
res = it.next();
}
}
private _createAnimInfos (skeleton: Skeleton, clip: AnimationClip, skinningRoot: Node) {
const animInfos: IInternalJointAnimInfo[] = [];
const { joints, bindposes } = skeleton;
const jointCount = joints.length;
const clipData = SkelAnimDataHub.getOrExtract(clip);
for (let j = 0; j < jointCount; j++) {
let animPath = joints[j];
let source = clipData.data[animPath];
let animNode = skinningRoot.getChildByPath(animPath);
let downstream: Mat4 | undefined;
let correctionPath: string | undefined;
while (!source) {
const idx = animPath.lastIndexOf('/');
animPath = animPath.substring(0, idx);
source = clipData.data[animPath];
if (animNode) {
if (!downstream) { downstream = new Mat4(); }
Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale);
Mat4.multiply(downstream, m4_1, downstream);
animNode = animNode.parent;
} else { // record the nearest curve path if no downstream pose is present
correctionPath = animPath;
}
if (idx < 0) { break; }
}
// the default behavior, just use the bindpose for current joint directly
let bindposeIdx = j;
let bindposeCorrection: Mat4 | undefined;
/**
* It is regularly observed that developers may choose to delete the whole
* skeleton node tree for skinning models that only use baked animations,
* to reduce prefab file size.
*
* This becomes troublesome in some cases during baking though, e.g. when a
* skeleton joint node is not directly controlled by any animation curve,
* but its parent nodes are. Due to lack of proper downstream default pose,
* the joint transform can not be calculated accurately.
*
* We address this issue by employing some pragmatic approximation.
* Specifically, by multiplying the bindpose of the joint corresponding to
* the nearest curve, instead of the actual target joint. This effectively
* merges the skinning influence of the 'incomplete' joint into its nearest
* parent with accurate transform data.
* It gives more visually-plausible results compared to the naive approach
* for most cases we've covered.
*/
if (correctionPath !== undefined && source) {
// just use the previous joint if the exact path is not found
bindposeIdx = j - 1;
for (let t = 0; t < jointCount; t++) {
if (joints[t] === correctionPath) {
bindposeIdx = t;
bindposeCorrection = new Mat4();
Mat4.multiply(bindposeCorrection, bindposes[t], skeleton.inverseBindposes[j]);
break;
}
}
}
animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, bindposeIdx, bindposeCorrection });
}
return animInfos;
}
}
export interface IAnimInfo {
+8 -7
View File
@@ -63,6 +63,7 @@ export function getWorldMatrix (transform: IJointTransform | null, stamp: number
while (transform) {
if (transform.stamp === stamp || transform.stamp + 1 === stamp && !transform.node.hasChangedFlags) {
res = transform.world;
transform.stamp = stamp;
break;
}
transform.stamp = stamp;
@@ -111,7 +112,7 @@ export function deleteTransform (node: Node) {
}
}
function getRevelantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number) {
function getRelevantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number) {
for (let i = 0; i < jointMaps.length; i++) {
const idxMap = jointMaps[i];
let index = -1;
@@ -152,7 +153,7 @@ export class SkinningModel extends MorphModel {
public uploadAnimation = null;
private _buffers: GFXBuffer[] = [];
private _datas: Float32Array[] = [];
private _dataArray: Float32Array[] = [];
private _joints: IJointInfo[] = [];
private _bufferIndices: number[] | null = null;
@@ -192,7 +193,7 @@ export class SkinningModel extends MorphModel {
const indices: number[] = [];
const buffers: number[] = [];
if (!jointMaps) { indices.push(index); buffers.push(0); }
else { getRevelantBuffers(indices, buffers, jointMaps, index); }
else { getRelevantBuffers(indices, buffers, jointMaps, index); }
this._joints.push({ indices, buffers, bound, target, bindpose, transform });
}
}
@@ -228,11 +229,11 @@ export class SkinningModel extends MorphModel {
const { indices, buffers, transform, bindpose } = this._joints[i];
Mat4.multiply(m4_1, transform.world, bindpose);
for (let b = 0; b < buffers.length; b++) {
uploadJointData(this._datas[buffers[b]], indices[b] * 12, m4_1, i === 0);
uploadJointData(this._dataArray[buffers[b]], indices[b] * 12, m4_1, i === 0);
}
}
for (let b = 0; b < this._buffers.length; b++) {
this._buffers[b].update(this._datas[b]);
this._buffers[b].update(this._dataArray[b]);
}
return true;
}
@@ -269,8 +270,8 @@ export class SkinningModel extends MorphModel {
stride: UBOSkinning.SIZE,
});
}
if (!this._datas[i]) {
this._datas[i] = new Float32Array(UBOSkinning.COUNT);
if (!this._dataArray[i]) {
this._dataArray[i] = new Float32Array(UBOSkinning.COUNT);
}
}
}
+1
View File
@@ -605,6 +605,7 @@ export class Camera {
const ch = this.viewport.height * this._height;
Vec3.transformMat4(out, worldPos, this.matViewProj);
out.x = cx + (out.x + 1) * 0.5 * cw;
out.y = cy + (out.y + 1) * 0.5 * ch;
out.z = out.z * 0.5 + 0.5;
+42 -38
View File
@@ -4,21 +4,22 @@ import { Material } from '../../assets/material';
import { RenderingSubMesh } from '../../assets/mesh';
import { aabb } from '../../geometry';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXFilter, GFXAddress } from '../../gfx/define';
import { GFXDevice } from '../../gfx/device';
import { getTypedArrayConstructor, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXFilter, GFXAddress } from '../../gfx/define';
import { GFXDevice, GFXFeature } from '../../gfx/device';
import { GFXPipelineState } from '../../gfx/pipeline-state';
import { Mat4, Vec3, Vec4} from '../../math';
import { Mat4, Vec3, Vec4 } from '../../math';
import { Pool } from '../../memop';
import { UBOForwardLight, UBOLocal, UniformLightingMapSampler } from '../../pipeline/define';
import { UBOForwardLight, UBOLocal, UniformLightingMapSampler, INST_MAT_WORLD } from '../../pipeline/define';
import { Node } from '../../scene-graph';
import { Layers } from '../../scene-graph/layers';
import { RenderScene } from './render-scene';
import { Texture2D } from '../..';
import { genSamplerHash, samplerLib} from '../../renderer/core/sampler-lib';
import { GFXSampler } from '../../gfx';
import { genSamplerHash, samplerLib } from '../../renderer/core/sampler-lib';
import { GFXSampler, IGFXAttribute } from '../../gfx';
import { SubModel, IPSOCreateInfo } from './submodel';
import { Pass } from '../core/pass';
import { legacyCC } from '../../global-exports';
import { programLib } from '../core/program-lib';
const m4_1 = new Mat4();
@@ -85,6 +86,10 @@ export class Model {
return this._updateStamp;
}
get isInstancingEnabled () {
return this._instMatWorldIdx >= 0;
}
public type = ModelType.DEFAULT;
public scene: RenderScene | null = null;
public node: Node = null!;
@@ -217,11 +222,12 @@ export class Model {
if (idx >= 0) {
const attrs = this.instancedAttributes!.list;
uploadMat4AsVec4x3(worldMatrix, attrs[idx].view, attrs[idx + 1].view, attrs[idx + 2].view);
} else {
Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
Mat4.inverseTranspose(m4_1, worldMatrix);
Mat4.toArray(this._localData, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET);
this._localBuffer!.update(this._localData);
}
Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
Mat4.inverseTranspose(m4_1, worldMatrix);
Mat4.toArray(this._localData, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET);
this._localBuffer!.update(this._localData);
}
/**
@@ -294,7 +300,7 @@ export class Model {
if (this._localBuffer) { bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localBuffer); }
}
this.updateInstancedAttributeList(psoCreateInfos[0], subModel.passes[0]);
this.updateInstancedAttributeList(subModel.subMeshData.attributes, subModel.passes[0]);
}
protected getMacroPatches (subModelIndex: number) : any {
@@ -302,32 +308,29 @@ export class Model {
}
// for now no submodel level instancing attributes
protected updateInstancedAttributeList (psoCreateInfo: IPSOCreateInfo, pass: Pass) {
// if (!pass || !psoCreateInfo) {
// return;
// }
// const attributes = pso.inputState.attributes;
// let size = 0;
// for (let j = 0; j < attributes.length; j++) {
// const attribute = attributes[j];
// if (!attribute.isInstanced) { continue; }
// size += GFXFormatInfos[attribute.format].size;
// }
// const attrs = this.instancedAttributes;
// attrs.buffer = new Uint8Array(size); attrs.list.length = 0;
// let offset = 0; const buffer = attrs.buffer.buffer;
// for (let j = 0; j < attributes.length; j++) {
// const attribute = attributes[j];
// if (!attribute.isInstanced) { continue; }
// const format = attribute.format;
// const info = GFXFormatInfos[format];
// const view = new (getTypedArrayConstructor(info))(buffer, offset, info.count);
// const isNormalized = attribute.isNormalized;
// offset += info.size; attrs.list.push({ name: attribute.name, format, isNormalized, view });
// }
// if (pass.instancedBuffer) { pass.instancedBuffer.destroy(); } // instancing IA changed
// this._instMatWorldIdx = this.getInstancedAttributeIndex(INST_MAT_WORLD);
// this._transformUpdated = true;
protected updateInstancedAttributeList (attributes: IGFXAttribute[], pass: Pass) {
if (!pass.device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) { return; }
let size = 0;
for (let j = 0; j < attributes.length; j++) {
const attribute = attributes[j];
if (!attribute.isInstanced) { continue; }
size += GFXFormatInfos[attribute.format].size;
}
const attrs = this.instancedAttributes;
attrs.buffer = new Uint8Array(size); attrs.list.length = 0;
let offset = 0; const buffer = attrs.buffer.buffer;
for (let j = 0; j < attributes.length; j++) {
const attribute = attributes[j];
if (!attribute.isInstanced) { continue; }
const format = attribute.format;
const info = GFXFormatInfos[format];
const view = new (getTypedArrayConstructor(info))(buffer, offset, info.count);
const isNormalized = attribute.isNormalized;
offset += info.size; attrs.list.push({ name: attribute.name, format, isNormalized, view });
}
if (pass.instancedBuffer) { pass.instancedBuffer.destroy(); } // instancing IA changed
this._instMatWorldIdx = this.getInstancedAttributeIndex(INST_MAT_WORLD);
this._transformUpdated = true;
}
protected getInstancedAttributeIndex (name: string) {
@@ -350,7 +353,8 @@ export class Model {
if (!mat) { return; }
let hasForwardLight = false;
for (const p of mat.passes) {
if (p.bindings.find((b) => b.name === UBOForwardLight.BLOCK.name)) {
const blocks = programLib.getTemplate(p.program).builtins.locals.blocks;
if (blocks.find((b) => b.name === UBOForwardLight.BLOCK.name)) {
hasForwardLight = true;
break;
}
+59 -47
View File
@@ -1,29 +1,25 @@
import { Material } from '../../assets/material';
import { aabb, frustum, intersect } from '../../geometry';
import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../../gfx/command-buffer';
import { GFXCommandBufferType } from '../../gfx/define';
import { GFXPipelineState } from '../../gfx/pipeline-state';
import { Color, Mat4, Quat, Vec3 } from '../../math';
import { CachedArray } from '../../memop/cached-array';
import { IInternalBindingInst, UBOShadow } from '../../pipeline/define';
import { DirectionalLight } from './directional-light';
import { Model } from './model';
import { RenderScene } from './render-scene';
import { SphereLight } from './sphere-light';
import { GFXCommandBuffer } from '../../gfx';
import { InstancedBuffer } from '../../pipeline/instanced-buffer';
const _forward = new Vec3(0, 0, -1);
const _v3 = new Vec3();
const _ab = new aabb();
const _qt = new Quat();
const _info: IGFXCommandBufferInfo = {
allocator: null!,
type: GFXCommandBufferType.SECONDARY,
};
interface IShadowRenderData {
model: Model;
psos: GFXPipelineState[];
cmdBuffer: GFXCommandBuffer;
instancedBuffer: InstancedBuffer | null;
}
export class PlanarShadows {
@@ -31,7 +27,6 @@ export class PlanarShadows {
set enabled (enable: boolean) {
this._enabled = enable;
if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); }
this._cmdBuffs.clear();
}
get enabled (): boolean {
@@ -67,14 +62,6 @@ export class PlanarShadows {
return this._data;
}
get cmdBuffs () {
return this._cmdBuffs;
}
get cmdBuffCount () {
return this._cmdBuffs.length;
}
protected _scene: RenderScene;
protected _enabled: boolean = false;
protected _normal = new Vec3(0, 1, 0);
@@ -85,17 +72,18 @@ export class PlanarShadows {
0.0, 0.0, 0.0, 0.3, // shadowColor
]);
protected _globalBindings: IInternalBindingInst;
protected _cmdBuffs: CachedArray<GFXCommandBuffer>;
protected _cmdBuffCount = 0;
protected _record = new Map<Model, IShadowRenderData>();
protected _pendingModels: IShadowRenderData[] = [];
protected _material: Material;
protected _instancingMaterial: Material;
constructor (scene: RenderScene) {
this._scene = scene;
this._globalBindings = scene.root.pipeline.globalBindings.get(UBOShadow.BLOCK.name)!;
this._cmdBuffs = new CachedArray<GFXCommandBuffer>(64);
this._material = new Material();
this._material.initialize({ effectName: 'pipeline/planar-shadow' });
this._instancingMaterial = new Material();
this._instancingMaterial.initialize({ effectName: 'pipeline/planar-shadow', defines: { USE_INSTANCING: true } });
}
public updateSphereLight (light: SphereLight) {
@@ -154,7 +142,7 @@ export class PlanarShadows {
}
public updateCommandBuffers (frstm: frustum, stamp: number) {
this._cmdBuffs.clear();
this._pendingModels.length = 0;
if (!this._scene.mainLight) { return; }
const models = this._scene.models;
for (let i = 0; i < models.length; i++) {
@@ -165,44 +153,68 @@ export class PlanarShadows {
if (!intersect.aabb_frustum(_ab, frstm)) { continue; }
}
let data = this._record.get(model);
if (data && (!!data.instancedBuffer !== model.isInstancingEnabled)) { this.destroyShadowData(model); data = undefined; }
if (!data) { data = this.createShadowData(model); this._record.set(model, data); }
if (model.updateStamp !== stamp) { model.updateUBOs(stamp); } // for those outside the frustum
this.cmdBuffs.push(data.cmdBuffer);
this._pendingModels.push(data);
}
}
public recordCommandBuffer (cmdBuff: GFXCommandBuffer) {
const models = this._pendingModels;
const modelLen = models.length;
const buffer = this._instancingMaterial.passes[0].instancedBuffer;
if (buffer) { buffer.clear(); }
for (let i = 0; i < modelLen; i++) {
const { model, psos, instancedBuffer } = models[i];
for (let j = 0; j < psos.length; j++) {
const submodel = model.getSubModel(j);
const pso = psos[j];
if (instancedBuffer) {
instancedBuffer.merge(submodel, model.instancedAttributes, pso);
} else {
const ia = submodel.inputAssembler!;
cmdBuff.bindPipelineState(pso);
cmdBuff.bindBindingLayout(pso.pipelineLayout.layouts[0]);
cmdBuff.bindInputAssembler(ia);
cmdBuff.draw(ia);
}
}
}
if (buffer && buffer.pso) {
buffer.uploadBuffers();
cmdBuff.bindPipelineState(buffer.pso!);
cmdBuff.bindBindingLayout(buffer.pso!.pipelineLayout.layouts[0]);
for (let b = 0; b < buffer.instances.length; ++b) {
const instance = buffer.instances[b];
if (!instance.count) { continue; }
cmdBuff.bindInputAssembler(instance.ia);
cmdBuff.draw(instance.ia);
}
}
}
public createShadowData (model: Model): IShadowRenderData {
const device = this._scene.root.device;
_info.allocator = device.commandAllocator;
const cmdBuffer = device.createCommandBuffer(_info);
const psos: GFXPipelineState[] = [];
cmdBuffer.begin();
const material = model.isInstancingEnabled ? this._instancingMaterial : this._material;
for (let i = 0; i < model.subModelNum; i++) {
const ia = model.getSubModel(i).inputAssembler!;
// @ts-ignore TS2445
const pso = model.createPipelineState(this._material.passes[0], i);
model.insertImplantPSO(pso); // add back to model to sync binding layouts
pso.pipelineLayout.layouts[0].update(); psos.push(pso);
cmdBuffer.bindPipelineState(pso);
cmdBuffer.bindBindingLayout(pso.pipelineLayout.layouts[0]);
cmdBuffer.bindInputAssembler(ia);
cmdBuffer.draw(ia);
// const pso = model.createPipelineState(material.passes[0], i);
// model.insertImplantPSO(pso); // add back to model to sync binding layouts
// pso.pipelineLayout.layouts[0].update(); psos.push(pso);
}
cmdBuffer.end();
return { psos, cmdBuffer };
return { model, psos, instancedBuffer: material.passes[0].instancedBuffer };
}
public destroyShadowData (model: Model) {
//todo: minggo
// const data = this._record.get(model);
// if (!data) { return; }
// data.cmdBuffer.destroy();
// for (let i = 0; i < data.psos.length; i++) {
// const pso = data.psos[i];
// model.removeImplantPSO(pso);
// this._material.passes[0].destroyPipelineState(pso);
// }
// this._record.delete(model);
const data = this._record.get(model);
if (!data) { return; }
const material = data.instancedBuffer ? this._instancingMaterial : this._material;
for (let i = 0; i < data.psos.length; i++) {
const pso = data.psos[i];
model.removeImplantPSO(pso);
// material.passes[0].destroyPipelineState(pso);
}
this._record.delete(model);
}
public onGlobalPipelineStateChanged () {
+4 -4
View File
@@ -427,9 +427,9 @@ export class RenderScene {
if (PREVIEW) {
if (ui2dNode == null) { console.error('make sure UINode is not null'); }
}
const uiTransfrom = ui2dNode._uiProps.uiTransformComp;
if (uiTransfrom == null || ui2dNode.layer & Layers.Enum.IGNORE_RAYCAST || !(ui2dNode.layer & mask)) { return; }
uiTransfrom.getComputeAABB(aabbUI);
const uiTransform = ui2dNode._uiProps.uiTransformComp;
if (uiTransform == null || ui2dNode.layer & Layers.Enum.IGNORE_RAYCAST || !(ui2dNode.layer & mask)) { return; }
uiTransform.getComputeAABB(aabbUI);
const d = intersect.ray_aabb(worldRay, aabbUI);
if (d <= 0) {
@@ -464,7 +464,7 @@ const pool = new RecyclePool<IRaycastResult>(() => {
return { node: null!, distance: Infinity };
}, 8);
const resultModels: IRaycastResult[] = [];
/** Canavas raycast result pool */
/** Canvas raycast result pool */
const aabbUI = new aabb();
const poolUI = new RecyclePool<IRaycastResult>(() => {
return { node: null!, distance: Infinity };
+5 -2
View File
@@ -18,7 +18,6 @@ export class Skybox extends Model {
set useIBL (val) {
this._useIBL = val;
this._updatePipeline();
this._updateGlobalBinding();
}
get useIBL () {
return this._useIBL;
@@ -29,7 +28,6 @@ export class Skybox extends Model {
skybox_material!.recompileShaders({ USE_RGBE_CUBEMAP: this._isRGBE });
this.setSubModelMaterial(0, skybox_material);
this._updatePipeline();
this._updateGlobalBinding();
}
get isRGBE () {
return this._isRGBE;
@@ -65,6 +63,11 @@ export class Skybox extends Model {
this.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material);
}
public onGlobalPipelineStateChanged () {
super.onGlobalPipelineStateChanged();
this._updateGlobalBinding();
}
protected _updatePipeline () {
const value = this._useIBL ? this._isRGBE ? 2 : 1 : 0;
const pipeline = this.scene!.root.pipeline;
+1 -1
View File
@@ -64,7 +64,7 @@ export class UIMaterial {
this._material.copy(info.material);
this._pass = this._material.passes[0];
this._pass = info.material.passes[0];
this._pass.update();
this._psoCreateInfo = new Pool(() => {
+1 -1
View File
@@ -487,7 +487,7 @@ export class Root {
this._views = [];
}
public createModel<T extends Model> (mClass: new () => T): T {
public createModel<T extends Model> (mClass: typeof Model): T {
let p = this._modelPools.get(mClass);
if (!p) {
this._modelPools.set(mClass, new Pool(() => new mClass(), 10));
+1 -1
View File
@@ -24,7 +24,7 @@
*/
/**
* @category scene-graph
* @hidden
*/
import { CCObject } from '../data/object';
+233 -228
View File
@@ -40,10 +40,9 @@ import { baseNodePolyfill } from './base-node-dev';
import { NodeEventProcessor } from './node-event-processor';
import { DEV, DEBUG, EDITOR } from 'internal:constants';
import { legacyCC } from '../global-exports';
import { Node } from './node';
import { Scene } from './scene';
/**
*
*/
type Constructor<T = {}> = new (...args: any[]) => T;
// @ts-ignore
@@ -78,21 +77,18 @@ function getConstructor (typeOrClassName: string | Function): Function | null {
}
/**
* A base node for CCNode, it will:
* - maintain scene hierarchy and active logic
* - notifications if some properties changed
* - define some interfaces shares between CCNode
* - define machanisms for Enity Component Systems
* - define prefab and serialize functions
*
* @class _BaseNode
* @extends Object
* @uses EventTarget
* @method constructor
* @param {String} [name]
* @protected
* @en The base class for [[Node]], it:
* - maintains scene hierarchy and life cycle logic
* - provides EventTarget ability
* - emits events if some properties changed, ref: [[SystemEventType]]
* - manages components
* @zh [[Node]] 的基类,他会负责:
* - 维护场景树以及节点生命周期管理
* - 提供 EventTarget 的事件管理和注册能力
* - 派发节点状态相关的事件,参考:[[SystemEventType]]
* - 管理组件
*/
@ccclass('cc._BaseNode')
@ccclass('cc.BaseNode')
export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Gets all components attached to this node.
@@ -103,17 +99,15 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en If true, the node is an persist node which won't be destroyed during scene transition.<br/>
* @en If true, the node is an persist node which won't be destroyed during scene transition.
* If false, the node will be destroyed automatically when loading a new scene. Default is false.
* @zh 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。<br/>
* 如果为false,节点将在加载新场景时自动销毁。默认为false。
* @property _persistNode
* @type {Boolean}
* @zh 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。
* 如果为false,节点将在加载新场景时自动销毁。默认为 false。
* @default false
* @protected
*/
@property
get _persistNode () {
get _persistNode (): boolean {
return (this._objFlags & DontDestroy) > 0;
}
set _persistNode (value) {
@@ -129,16 +123,9 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Name of node.
* @zh 该节点名称。
* @property name
* @type {String}
* @example
* ```
* node.name = "New Node";
* cc.log("Node Name: " + node.name);
* ```
*/
@property
get name () {
get name (): string {
return this._name;
}
set name (value) {
@@ -150,15 +137,9 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en The uuid for editor, will be stripped before building project.
* @en The uuid for editor, will be stripped after building project.
* @zh 主要用于编辑器的 uuid,在编辑器下可用于持久化存储,在项目构建之后将变成自增的 id。
* @property uuid
* @type {String}
* @readOnly
* @example
* ```
* cc.log("Node Uuid: " + node.uuid);
* ```
*/
@property
get uuid () {
@@ -168,16 +149,7 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en All children nodes.
* @zh 节点的所有子节点。
* @property children
* @type {Node[]}
* @readOnly
* @example
* ```
* var children = node.children;
* for (var i = 0; i < children.length; ++i) {
* cc.log("Node: " + children[i]);
* }
* ```
*/
@property
get children () {
@@ -186,21 +158,15 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en
* The local active state of this node.<br/>
* Note that a Node may be inactive because a parent is not active, even if this returns true.<br/>
* The local active state of this node.
* Note that a Node may be inactive because a parent is not active, even if this returns true.
* Use [[activeInHierarchy]]
* if you want to check if the Node is actually treated as active in the scene.
* @zh
* 当前节点的自身激活状态。<br/>
* 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。<br/>
* 当前节点的自身激活状态。
* 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。
* 如果你想检查节点在场景中实际的激活状态可以使用 [[activeInHierarchy]]
* @property active
* @type {Boolean}
* @default true
* @example
* ```
* node.active = false;
* ```
*/
@property
get active () {
@@ -222,18 +188,16 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Indicates whether this node is active in the scene.
* @zh 表示此节点是否在场景中激活。
* @property activeInHierarchy
* @type {Boolean}
* @example
* ```
* cc.log("activeInHierarchy: " + node.activeInHierarchy);
* ```
*/
@property
get activeInHierarchy () {
return this._activeInHierarchy;
}
/**
* @en The parent node
* @zh 父节点
*/
@property
get parent () {
return this._parent;
@@ -243,14 +207,19 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en which scene this node belongs to.
* @en Which scene this node belongs to.
* @zh 此节点属于哪个场景。
* @type {cc.Scene}}
* @readonly
*/
get scene () {
return this._scene;
}
/**
* @en The event processor of the current node, it provides EventTarget ability.
* @zh 当前节点的事件处理器,提供 EventTarget 能力。
* @readonly
*/
get eventProcessor () {
return this._eventProcessor;
}
@@ -349,42 +318,27 @@ export class BaseNode extends CCObject implements ISchedulable {
@property
protected _active = true;
/**
* @default []
* @readOnly
*/
@property
protected _components: Component[] = [];
/**
* The PrefabInfo object
* @type {PrefabInfo}
*/
// The PrefabInfo object
@property
protected _prefab: any = null;
/**
* @en which scene this node belongs to.
* @zh 此节点属于哪个场景。
* @type {cc.Scene}}
*/
protected _scene: any = NullScene;
protected _activeInHierarchy = false;
// TO DO
// @ts-ignore
protected _id: string = idGenerator.getNewId();
protected _name: string;
protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this);
protected _eventMask = 0;
/**
* Register all related EventTargets,
* all event callbacks will be removed in _onPreDestroy
* protected __eventTargets: EventTarget[] = [];
*/
// Register all related EventTargets,
// all event callbacks will be removed in _onPreDestroy
// protected __eventTargets: EventTarget[] = [];
protected __eventTargets: any[] = [];
protected _siblingIndex: number = 0;
@@ -416,10 +370,6 @@ export class BaseNode extends CCObject implements ISchedulable {
}
};
/**
* @method constructor
* @param {String} [name]
*/
constructor (name?: string) {
super(name);
this._name = name !== undefined ? name : 'New Node';
@@ -427,15 +377,15 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en
* Properties configuration function <br/>
* All properties in attrs will be set to the node, <br/>
* when the setter of the node is available, <br/>
* the property will be set via setter function.<br/>
* Properties configuration function.
* All properties in attrs will be set to the node,
* when the setter of the node is available,
* the property will be set via setter function.
* @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。
* @param attrs - Properties to be set to node
* @example
* ```
* var attrs = { key: 0, num: 100 };
* var attrs = { name: 'New Name', active: false };
* node.attr(attrs);
* ```
*/
@@ -448,10 +398,6 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Get parent of the node.
* @zh 获取该节点的父节点。
* @example
* ```
* var parent = this.node.getParent();
* ```
*/
public getParent () {
return this._parent;
@@ -460,23 +406,20 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Set parent of the node.
* @zh 设置该节点的父节点。
* @example
* ```
* node.setParent(newNode);
* ```
*/
public setParent (value: this | null, keepWorldTransform: boolean = false) {
public setParent (value: this | Scene | null, keepWorldTransform: boolean = false) {
if (this._parent === value) {
return;
}
const oldParent = this._parent;
const newParent = value as this;
if (DEBUG && oldParent &&
// Change parent when old parent desactivating or activating
(oldParent._objFlags & ChangingState)) {
errorID(3821);
}
this._parent = value;
this._parent = newParent;
// Reset sibling index
this._siblingIndex = 0;
@@ -486,14 +429,14 @@ export class BaseNode extends CCObject implements ISchedulable {
this.emit(SystemEventType.PARENT_CHANGED, oldParent);
}
if (value) {
if (DEBUG && (value._objFlags & Deactivating)) {
if (newParent) {
if (DEBUG && (newParent._objFlags & Deactivating)) {
errorID(3821);
}
value._children.push(this);
this._siblingIndex = value._children.length - 1;
if (value.emit) {
value.emit(SystemEventType.CHILD_ADDED, this);
newParent._children.push(this);
this._siblingIndex = newParent._children.length - 1;
if (newParent.emit) {
newParent.emit(SystemEventType.CHILD_ADDED, this);
}
}
if (oldParent) {
@@ -514,14 +457,10 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en Returns a child from the container given its uuid.
* @en Returns a child with the same uuid.
* @zh 通过 uuid 获取节点的子节点。
* @param uuid - The uuid to find the child node.
* @return a Node whose uuid equals to the input parameter
* @example
* ```
* var child = node.getChildByUuid(uuid);
* ```
*/
public getChildByUuid (uuid: string) {
if (!uuid) {
@@ -539,7 +478,7 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en Returns a child from the container given its name.
* @en Returns a child with the same name.
* @zh 通过名称获取节点的子节点。
* @param name - A name to find the child node.
* @return a CCNode object whose name equals to the input parameter
@@ -564,13 +503,13 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en Returns a child from the container given its path.
* @en Returns a child with the given path.
* @zh 通过路径获取节点的子节点。
* @param path - A path to find the child node.
* @return a CCNode object whose name equals to the input parameter
* @return a Node object whose path equals to the input parameter
* @example
* ```
* var child = node.getChildByPath("Test Node");
* var child = node.getChildByPath("subNode/Test Node");
* ```
*/
public getChildByPath (path: string) {
@@ -589,58 +528,48 @@ export class BaseNode extends CCObject implements ISchedulable {
}
return lastNode;
}
public addChild (child: this): void {
/**
* @en Add a child to the current node, it will be pushed to the end of [[children]] array.
* @zh 添加一个子节点,它会被添加到 [[children]] 数组的末尾。
* @param child - the child node to be added
*/
public addChild (child: this | Node): void {
if (DEV && !(child instanceof legacyCC._BaseNode)) {
return errorID(1634, legacyCC.js.getClassName(child));
}
legacyCC.assertID(child, 1606);
legacyCC.assertID(child._parent === null, 1605);
legacyCC.assertID((child as this)._parent === null, 1605);
// invokes the parent setter
child.setParent(this);
(child as this).setParent(this);
}
/**
* @en
* Inserts a child to the node at a specified index.
* @zh
* 插入子节点到指定位置
* @en Inserts a child to the node at a specified index.
* @zh 插入子节点到指定位置
* @param child - the child node to be inserted
* 要插入的子节点
* @param siblingIndex - the sibling index to place the child in
* 用于放置子节点的同级索引
* @example
* ```
* node.insertChild(child, 2);
* ```
*/
public insertChild (child: this, siblingIndex: number) {
public insertChild (child: this | Node, siblingIndex: number) {
child.parent = this;
child.setSiblingIndex(siblingIndex);
}
/**
* @en Get the sibling index.
* @zh 获取同级索引。
* @example
* ```
* var index = node.getSiblingIndex();
* ```
* @en Get the sibling index of the current node in its parent's children array.
* @zh 获取当前节点在父节点的 children 数组中的位置。
*/
public getSiblingIndex () {
return this._siblingIndex;
}
/**
* @en Set the sibling index of this node.
* @zh 设置节点同级索引。
* @example
* ```
* node.setSiblingIndex(1);
* ```
* @en Set the sibling index of the current node in its parent's children array.
* @zh 设置当前节点在父节点的 children 数组中的位置。
*/
public setSiblingIndex (index: number) {
if (!this._parent) {
@@ -674,11 +603,11 @@ export class BaseNode extends CCObject implements ISchedulable {
* This function call is not recursive, it's based on stack.
* Please don't walk any other node inside the walk process.
* @zh 遍历该节点的子树里的所有节点并按规则执行回调函数。
* 对子树中的所有节点,包含当前节点,会执行两次回调,prefunc 会在访问它的子节点之前调用,postfunc 会在访问所有子节点之后调用。
* 对子树中的所有节点,包含当前节点,会执行两次回调,preFunc 会在访问它的子节点之前调用,postFunc 会在访问所有子节点之后调用。
* 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。
* 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。
* @param prefunc The callback to process node when reach the node for the first time
* @param postfunc The callback to process node when re-visit the node after walked all children in its sub tree
* @param preFunc The callback to process node when reach the node for the first time
* @param postFunc The callback to process node when re-visit the node after walked all children in its sub tree
* @example
* ```
* node.walk(function (target) {
@@ -688,7 +617,7 @@ export class BaseNode extends CCObject implements ISchedulable {
* });
* ```
*/
public walk (prefunc: (target: this) => void, postfunc?: (target: this) => void) {
public walk (preFunc: (target: this) => void, postFunc?: (target: this) => void) {
// const BaseNode = cc._BaseNode;
let index = 1;
let children: this[] | null = null;
@@ -711,12 +640,12 @@ export class BaseNode extends CCObject implements ISchedulable {
if (!curr) {
continue;
}
if (!afterChildren && prefunc) {
if (!afterChildren && preFunc) {
// pre call
prefunc(curr);
} else if (afterChildren && postfunc) {
preFunc(curr);
} else if (afterChildren && postFunc) {
// post call
postfunc(curr);
postFunc(curr);
}
// Avoid memory leak
@@ -774,16 +703,11 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en
* Remove itself from its parent node. <br/>
* If the node orphan, then nothing happens.
* Remove itself from its parent node.
* If the node have no parent, then nothing happens.
* @zh
* 从父节点中删除该节点。<br/>
* 如果这个节点是一个孤节点,那么什么都不会发生。
* @see cc.Node#removeFromParentAndCleanup
* @example
* ```
* node.removeFromParent();
* ```
* 从父节点中删除该节点。
* 如果这个节点是一个孤立节点,那么什么都不会发生。
*/
public removeFromParent () {
if (this._parent) {
@@ -792,33 +716,20 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en
* Removes a child from the container.
* @zh
* 移除节点中指定的子节点。
* @en Removes a child from the container.
* @zh 移除节点中指定的子节点。
* @param child - The child node which will be removed.
* 将被移除的子节点
* @example
* ```
* node.removeChild(newNode);
* ```
*/
public removeChild (child: this) {
if (this._children.indexOf(child) > -1) {
public removeChild (child: this | Node) {
if (this._children.indexOf(child as this) > -1) {
// invoke the parent setter
child.parent = null;
}
}
/**
* @en
* Removes all children from the container.
* @zh
* 移除节点所有的子节点。
* @example
* ```
* node.removeAllChildren();
* ```
* @en Removes all children from the container.
* @zh 移除节点所有的子节点。
*/
public removeAllChildren () {
// not using detachChild improves speed here
@@ -836,13 +747,8 @@ export class BaseNode extends CCObject implements ISchedulable {
* @en Is this node a child of the given node?
* @zh 是否是指定节点的子节点?
* @return True if this node is a child, deep child or identical to the given node.
* @return 如果此节点是子节点、深度子节点或与给定节点相同,则为True。
* @example
* ```
* node.isChildOf(newNode);
* ```
*/
public isChildOf (parent: this | null): boolean {
public isChildOf (parent: this | Scene | null): boolean {
let child: BaseNode | null = this;
do {
if (child === parent) {
@@ -858,29 +764,31 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en
* Returns the component of supplied type if the node has one attached, null if it doesn't.<br/>
* Returns the component of supplied type if the node has one attached, null if it doesn't.
* You can also get component in the node by passing in the name of the script.
* @zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。<br/>
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
* 传入参数也可以是脚本的名称。
* @param classConstructor The class of the target component
* @example
* ```
* // get sprite component.
* var sprite = node.getComponent(cc.SpriteComponent);
* var sprite = node.getComponent(SpriteComponent);
* ```
*/
public getComponent<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* @en
* Returns the component of supplied type if the node has one attached, null if it doesn't.<br/>
* Returns the component of supplied type if the node has one attached, null if it doesn't.
* You can also get component in the node by passing in the name of the script.
* @zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。<br/>
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
* 传入参数也可以是脚本的名称。
* @param className The class name of the target component
* @example
* ```
* // get custom test calss.
* // get custom test class.
* var test = node.getComponent("Test");
* ```
*/
@@ -895,22 +803,16 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en Returns all components of supplied type in the node.
* @en Returns all components of given type in the node.
* @zh 返回节点上指定类型的所有组件。
* @example
* ```
* var sprites = node.getComponents(cc.SpriteComponent);
* ```
* @param classConstructor The class of the target component
*/
public getComponents<T extends Component> (classConstructor: Constructor<T>): T[];
/**
* @en Returns all components of supplied type in the node.
* @en Returns all components of given type in the node.
* @zh 返回节点上指定类型的所有组件。
* @example
* ```
* var tests = node.getComponents("Test");
* ```
* @param className The class name of the target component
*/
public getComponents (className: string): Component[];
@@ -924,18 +826,20 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en Returns the component of supplied type in any of its children using depth first search.
* @en Returns the component of given type in any of its children using depth first search.
* @zh 递归查找所有子节点中第一个匹配指定类型的组件。
* @param classConstructor The class of the target component
* @example
* ```
* var sprite = node.getComponentInChildren(cc.SpriteComponent);
* var sprite = node.getComponentInChildren(SpriteComponent);
* ```
*/
public getComponentInChildren<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* @en Returns the component of supplied type in any of its children using depth first search.
* @en Returns the component of given type in any of its children using depth first search.
* @zh 递归查找所有子节点中第一个匹配指定类型的组件。
* @param className The class name of the target component
* @example
* ```
* var Test = node.getComponentInChildren("Test");
@@ -952,18 +856,20 @@ export class BaseNode extends CCObject implements ISchedulable {
}
/**
* @en Returns all components of supplied type in self or any of its children.
* @en Returns all components of given type in self or any of its children.
* @zh 递归查找自身或所有子节点中指定类型的组件
* @param classConstructor The class of the target component
* @example
* ```
* var sprites = node.getComponentsInChildren(cc.SpriteComponent);
* var sprites = node.getComponentsInChildren(SpriteComponent);
* ```
*/
public getComponentsInChildren<T extends Component> (classConstructor: Constructor<T>): T[];
/**
* @en Returns all components of supplied type in self or any of its children.
* @en Returns all components of given type in self or any of its children.
* @zh 递归查找自身或所有子节点中指定类型的组件
* @param className The class name of the target component
* @example
* ```
* var tests = node.getComponentsInChildren("Test");
@@ -984,9 +890,10 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
* @param classConstructor The class of the component to add
* @example
* ```
* var sprite = node.addComponent(cc.SpriteComponent);
* var sprite = node.addComponent(SpriteComponent);
* ```
*/
public addComponent<T extends Component> (classConstructor: Constructor<T>): T | null;
@@ -994,6 +901,7 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
* @param className The class name of the component to add
* @example
* ```
* var test = node.addComponent("Test");
@@ -1086,11 +994,11 @@ export class BaseNode extends CCObject implements ISchedulable {
* @zh
* 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。
* 如果你已经获得组件引用,你也可以直接调用 component.destroy()
* @param classConstructor The class of the component to remove
* @deprecated please destroy the component to remove it.
* 请销毁组件以移除它。
* @example
* ```
* node.removeComponent(cc.SpriteComponent);
* node.removeComponent(SpriteComponent);
* ```
*/
public removeComponent<T extends Component> (classConstructor: Constructor<T>): void;
@@ -1102,6 +1010,7 @@ export class BaseNode extends CCObject implements ISchedulable {
* @zh
* 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。
* 如果你已经获得组件引用,你也可以直接调用 component.destroy()
* @param classNameOrInstance The class name of the component to remove or the component instance to be removed
* @deprecated please destroy the component to remove it.
* @example
* ```
@@ -1132,7 +1041,44 @@ export class BaseNode extends CCObject implements ISchedulable {
// EVENT PROCESSING
public on (type: string | SystemEventType, callback: Function, target?: Object, useCapture?: any) {
/**
* @en
* Register a callback of a specific event type on Node.
* Use this method to register touch or mouse event permit propagation based on scene graph,
* These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
* 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
* 2. At target phase: dispatch to the listeners of the real target
* 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
* In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
* It's the recommended way to register touch/mouse event for Node,
* please do not use cc.eventManager directly for Node.
* You can also register custom event and use `emit` to trigger custom event on Node.
* For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
* You can also pass event callback parameters with `emit` by passing parameters after `type`.
* @zh
* 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
* 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
* 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
* 2. 目标阶段:派发给目标节点的监听器。
* 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发直到根节点。
* 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
* 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
* 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
* 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
* @param type - A string representing the event type to listen for.<br>See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
* @param callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
* @param useCapture - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @return - Just returns the incoming callback so you can save the anonymous function easier.
* @example
* ```typescript
* this.node.on(SystemEventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
* node.on(SystemEventType.TOUCH_START, callback, this);
* node.on(SystemEventType.TOUCH_MOVE, callback, this);
* node.on(SystemEventType.TOUCH_END, callback, this);
* ```
*/
public on (type: string | SystemEventType, callback: Function, target?: Object, useCapture: any = false) {
switch (type) {
case SystemEventType.TRANSFORM_CHANGED:
this._eventMask |= TRANSFORM_ON;
@@ -1141,7 +1087,22 @@ export class BaseNode extends CCObject implements ISchedulable {
this._eventProcessor.on(type, callback, target, useCapture);
}
public off (type: string, callback?: Function, target?: Object, useCapture?: any) {
/**
* @en
* Removes the callback previously registered with the same type, callback, target and or useCapture.
* This method is merely an alias to removeEventListener.
* @zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。
* @param type - A string representing the event type being removed.
* @param callback - The callback to remove.
* @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
* @param useCapture - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @example
* ```typescript
* this.node.off(SystemEventType.TOUCH_START, this.memberFunction, this);
* node.off(SystemEventType.TOUCH_START, callback, this.node);
* ```
*/
public off (type: string, callback?: Function, target?: Object, useCapture: any = false) {
this._eventProcessor.off(type, callback, target, useCapture);
const hasListeners = this._eventProcessor.hasEventListener(type);
@@ -1155,22 +1116,69 @@ export class BaseNode extends CCObject implements ISchedulable {
}
}
/**
* @en
* Register an callback of a specific event type on the Node,
* the callback will remove itself after the first time it is triggered.
* @zh
* 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
*/
public once (type: string, callback: Function, target?: Object, useCapture?: any) {
this._eventProcessor.once(type, callback, target, useCapture);
}
/**
* @en
* Trigger an event directly with the event name and necessary arguments.
* @zh
* 通过事件名发送自定义事件
* @param type - event type
* @param arg1 - First argument in callback
* @param arg2 - Second argument in callback
* @param arg3 - Third argument in callback
* @param arg4 - Fourth argument in callback
* @param arg5 - Fifth argument in callback
* @example
* ```typescript
* eventTarget.emit('fire', event);
* eventTarget.emit('fire', message, emitter);
* ```
*/
public emit (type: string, ...args: any[]) {
this._eventProcessor.emit(type, ...args);
}
/**
* @en
* Dispatches an event into the event flow.
* The event target is the EventTarget object upon which the dispatchEvent() method is called.
* @zh 分发事件到事件流中。
* @param event - The Event object that is dispatched into the event flow
*/
public dispatchEvent (event: Event) {
this._eventProcessor.dispatchEvent(event);
}
/**
* @en Checks whether the EventTarget object has any callback registered for a specific type of event.
* @zh 检查事件目标对象是否有为特定类型的事件注册的回调。
* @param type - The type of event.
* @return True if a callback of the specified type is registered; false otherwise.
*/
public hasEventListener (type: string) {
return this._eventProcessor.hasEventListener(type);
}
/**
* @en Removes all callbacks previously registered with the same target.
* @zh 移除目标上的所有注册事件。
* @param target - The target to be searched for all related callbacks
*/
public targetOff (target: string | Object) {
this._eventProcessor.targetOff(target);
// Check for event mask reset
@@ -1194,15 +1202,11 @@ export class BaseNode extends CCObject implements ISchedulable {
/**
* @en
* Destroy all children from the node, and release all their own references to other objects.<br/>
* Destroy all children from the node, and release all their own references to other objects.
* Actual destruct operation will delayed until before rendering.
* @zh
* 销毁所有子节点,并释放所有它们对其它对象的引用。<br/>
* 销毁所有子节点,并释放所有它们对其它对象的引用。
* 实际销毁操作会延迟到当前帧渲染前执行。
* @example
* ```
* node.destroyAllChildren();
* ```
*/
public destroyAllChildren () {
const children = this._children;
@@ -1341,6 +1345,16 @@ export class BaseNode extends CCObject implements ISchedulable {
this._registerIfAttached!(false);
}
// Clear event targets
const eventTargets = this.__eventTargets;
for (let i = 0; i < eventTargets.length; ++i) {
const et = eventTargets[i];
if (et) {
et.targetOff(this);
}
}
eventTargets.length = 0;
// destroy children
const children = this._children;
for (let i = 0; i < children.length; ++i) {
@@ -1356,15 +1370,6 @@ export class BaseNode extends CCObject implements ISchedulable {
comps[i]._destroyImmediate();
}
const eventTargets = this.__eventTargets;
for (let i = 0; i < eventTargets.length; ++i) {
const et = eventTargets[i];
if (et) {
et.targetOff(this);
}
}
eventTargets.length = 0;
// remove from persist
if (this._persistNode) {
legacyCC.game.removePersistRootNode(this);
+48 -4
View File
@@ -216,7 +216,7 @@ function enableInEditor (comp) {
}
// return function to simply call each component with try catch protection
export function createInvokeImplJit (code:string, useDt?, ensureFlag?) {
export function createInvokeImplJit (code: string, useDt?, ensureFlag?) {
// function (it) {
// let a = it.array;
// for (it.i = 0; it.i < a.length; ++it.i) {
@@ -333,11 +333,26 @@ export const invokeOnEnable = EDITOR ? (iterator) => {
};
/**
* The Manager for Component's life-cycle methods.
* @en The Manager for Component's life-cycle methods.
* It collaborates with [[NodeActivator]] to schedule and invoke life cycle methods for components
* @zh 组件生命周期函数的调度器。
* 它和 [[NodeActivator]] 一起调度并执行组件的生命周期函数。
*/
export class ComponentScheduler {
/**
* @en The invoker of `start` callback
* @zh `start` 回调的调度器
*/
public startInvoker!: OneOffInvoker;
/**
* @en The invoker of `update` callback
* @zh `update` 回调的调度器
*/
public updateInvoker!: ReusableInvoker;
/**
* @en The invoker of `lateUpdate` callback
* @zh `lateUpdate` 回调的调度器
*/
public lateUpdateInvoker!: ReusableInvoker;
// components deferred to schedule
private _deferredComps: any[] = [];
@@ -347,6 +362,10 @@ export class ComponentScheduler {
this.unscheduleAll();
}
/**
* @en Cancel all future callbacks, including `start`, `update` and `lateUpdate`
* @zh 取消所有未来的函数调度,包括 `start`,`update` 和 `lateUpdate`
*/
public unscheduleAll () {
// invokers
this.startInvoker = new OneOffInvoker(invokeStart);
@@ -393,6 +412,12 @@ export class ComponentScheduler {
}
}
/**
* @en Enable a component
* @zh 启用一个组件
* @param comp The component to be enabled
* @param invoker The invoker which is responsible to schedule the `onEnable` call
*/
public enableComp (comp, invoker?) {
if (!(comp._objFlags & IsOnEnableCalled)) {
if (comp.onEnable) {
@@ -413,6 +438,11 @@ export class ComponentScheduler {
}
}
/**
* @en Disable a component
* @zh 禁用一个组件
* @param comp The component to be disabled
*/
public disableComp (comp) {
if (comp._objFlags & IsOnEnableCalled) {
if (comp.onDisable) {
@@ -422,6 +452,10 @@ export class ComponentScheduler {
}
}
/**
* @en Process start phase for registered components
* @zh 为当前注册的组件执行 start 阶段任务
*/
public startPhase () {
// Start of this frame
this._updating = true;
@@ -447,11 +481,21 @@ export class ComponentScheduler {
// }
}
public updatePhase (dt) {
/**
* @en Process update phase for registered components
* @zh 为当前注册的组件执行 update 阶段任务
* @param dt 距离上一帧的时间
*/
public updatePhase (dt:number) {
this.updateInvoker.invoke(dt);
}
public lateUpdatePhase (dt) {
/**
* @en Process late update phase for registered components
* @zh 为当前注册的组件执行 late update 阶段任务
* @param dt 距离上一帧的时间
*/
public lateUpdatePhase (dt:number) {
this.lateUpdateInvoker.invoke(dt);
// End of this frame
+5 -1
View File
@@ -33,10 +33,14 @@ import { DEV } from 'internal:constants';
import { legacyCC } from '../global-exports';
/**
* Finds a node by hierarchy path, the path is case-sensitive.
* @en Finds a node by hierarchy path, the path is case-sensitive.
* It will traverse the hierarchy by splitting the path using '/' character.
* This function will still returns the node even if it is inactive.
* It is recommended to not use this function every frame instead cache the result at startup.
* @zh 通过路径从节点树中查找节点的方法,路径是大小写敏感的,并且通过 `/` 来分隔节点层级。
* 即使节点的状态是未启用的也可以找到,建议将结果缓存,而不是每次需要都去查找。
* @param path The path of the target node
* @param referenceNode If given, the search will be limited in the sub node tree of the reference node
*/
export function find (path: string, referenceNode?: Node): Node | null {
if (!referenceNode) {
+23 -11
View File
@@ -46,12 +46,23 @@ const layerList = {
};
/**
* 场景节点层管理器,用于射线检测、物理碰撞和用户自定义脚本逻辑。
* @zh 节点层管理器,层数据是以掩码数据方式存储在 [[Node.layer]] 中,用于射线检测、物理碰撞和用户自定义脚本逻辑。
* 每个节点可属于一个或多个层,可通过 “包含式” 或 “排除式” 两种检测器进行层检测。
* @en Node's layer manager, it's stored as bit mask data in [[Node.layer]].
* Layer information is widely used in raycast, physics and user logic.
* Every node can be assigned to multiple layers with different bit masks, you can setup layer with inclusive or exclusive operation.
*/
export class Layers {
/**
* @en All layers in an Enum
* @zh 以 Enum 形式存在的所有层列表
*/
public static Enum = Enum(layerList);
/**
* @en All layers in [[BitMask]] type
* @zh 包含所有层的 [[BitMask]]
*/
public static BitMask = BitMask(Object.assign({}, layerList));
/**
@@ -59,8 +70,8 @@ export class Layers {
* Make a layer mask accepting nothing but the listed layers
* @zh
* 创建一个包含式层检测器,只接受列表中的层
* @param includes 可接受的层数组
* @return 指定功能的层检测器
* @param includes All accepted layers
* @return A filter which can detect all accepted layers
*/
public static makeMaskInclude (includes: number[]): number {
let mask = 0;
@@ -75,8 +86,8 @@ export class Layers {
* Make a layer mask accepting everything but the listed layers
* @zh
* 创建一个排除式层检测器,只拒绝列表中的层
* @param excludes 将拒绝的层数组
* @return 指定功能的层检测器
* @param excludes All excluded layers
* @return A filter which can detect for excluded layers
*/
public static makeMaskExclude (excludes: number[]): number {
return ~Layers.makeMaskInclude(excludes);
@@ -84,10 +95,11 @@ export class Layers {
/**
* @zh 添加一个新层,用户可编辑 0 - 19 位为用户自定义层
* @param name 层名字
* @param bitNum 层序号
* @en Add a new layer, user can use layers from bit position 0 to 19, other bits are reserved.
* @param name Layer's name
* @param bitNum Layer's bit position
*/
public static addLayer ( name: string, bitNum: number) {
public static addLayer (name: string, bitNum: number) {
if ( bitNum === undefined ) {
console.warn('bitNum can\'t be undefined');
return;
@@ -103,9 +115,9 @@ export class Layers {
}
/**
* @zh
* 移除一个层,用户可编辑 0 - 19 位为用户自定义层
* @param bitNum 层序号
* @en Remove a layer, user can remove layers from bit position 0 to 19, other bits are reserved.
* @zh 移除一个层,用户可编辑 0 - 19 位为用户自定义层
* @param bitNum Layer's bit position
*/
public static deleteLayer (bitNum: number) {
if ( bitNum > 19 || bitNum < 0) {
+24 -1
View File
@@ -163,7 +163,7 @@ function _onLoadInEditor (comp) {
/**
* @en The class used to perform activating and deactivating operations of node and component.
* @zh 用于执行节点和组件的激活和停用操作的类。
* @zh 用于执行节点和组件的激活和停用操作的管理器。
*/
export default class NodeActivator {
public resetComp: any;
@@ -173,11 +173,21 @@ export default class NodeActivator {
this.reset();
}
/**
* @en Reset all activation or des-activation tasks
* @zh 重置所有激活或非激活任务
*/
public reset () {
// a stack of node's activating tasks
this._activatingStack = [];
}
/**
* @en Activate or des-activate a node
* @zh 激活或者停用某个节点
* @param node Target node
* @param active Which state to set the node to
*/
public activateNode (node, active) {
if (active) {
const task: any = activateTasksPool.get();
@@ -206,6 +216,14 @@ export default class NodeActivator {
node.emit('active-in-hierarchy-changed', node);
}
/**
* @en Activate or des-activate a component
* @zh 激活或者停用某个组件
* @param comp Target component
* @param preloadInvoker The invoker for `_preload` method, normally from [[ComponentScheduler]]
* @param onLoadInvoker The invoker for `onLoad` method, normally from [[ComponentScheduler]]
* @param onEnableInvoker The invoker for `onEnable` method, normally from [[ComponentScheduler]]
*/
public activateComp (comp, preloadInvoker?, onLoadInvoker?, onEnableInvoker?) {
if (!(comp._objFlags & IsPreloadStarted)) {
comp._objFlags |= IsPreloadStarted;
@@ -242,6 +260,11 @@ export default class NodeActivator {
}
}
/**
* @en Destroy a component
* @zh 销毁一个组件
* @param comp Target component
*/
public destroyComp (comp) {
// ensure onDisable called
legacyCC.director._compScheduler.disableComp(comp);
+12 -2
View File
@@ -23,17 +23,25 @@
THE SOFTWARE.
*/
import { legacyCC } from '../global-exports';
/**
* @category scene-graph
*/
import { ccenum } from '../value-types/enum';
/**
* @en Node's coordinate space
* @zh 节点的坐标空间
*/
export enum NodeSpace {
LOCAL,
WORLD,
}
/**
* @en Bit masks for node's transformation
* @zh 节点的空间变换位标记
*/
export enum TransformBit {
/**
* @zh
@@ -67,3 +75,5 @@ export enum TransformBit {
TRS = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE,
TRS_MASK = ~TransformBit.TRS,
}
legacyCC.internal.TransformBit = TransformBit;

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