Merge remote-tracking branch 'origin/3d-v1.1.1' into 3d

# Conflicts:
#	cocos/core/3d/builtin/effects.ts
#	cocos/core/3d/framework/light-component.ts
#	cocos/core/3d/framework/model-component.ts
#	cocos/core/animation/animation-state.ts
#	cocos/core/assets/image-asset.ts
#	cocos/core/data/object.ts
#	cocos/core/event/callbacks-invoker.ts
#	cocos/core/game.ts
#	cocos/core/gfx/webgl/webgl-commands.ts
#	cocos/core/gfx/webgl2/webgl2-commands.ts
#	cocos/core/pipeline/define.ts
#	cocos/core/platform/event-manager/events.ts
#	cocos/core/primitive/primitive.ts
#	cocos/core/renderer/scene/model.ts
#	cocos/core/renderer/scene/render-scene.ts
#	cocos/core/root.ts
#	cocos/core/scene-graph/node-event-processor.ts
#	cocos/core/splash-screen-webgl.ts
#	cocos/particle/index.ts
#	cocos/terrain/terrain.ts
#	exports/base.ts
This commit is contained in:
pandamicro
2020-06-17 14:47:36 +08:00
48 changed files with 1245 additions and 1009 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -499,7 +499,7 @@ export class CameraComponent extends Component {
}
public onEnable () {
this.node.hasChangedFlags = TransformBit.POSITION; // trigger camera matrix update
this.node.hasChangedFlags |= TransformBit.POSITION; // trigger camera matrix update
if (this._camera) {
this._attachToScene();
return;
+1 -1
View File
@@ -11,7 +11,7 @@ removeProperty(ModelComponent.prototype, 'ModelComponent.prototype', [
name: 'enableDynamicBatching',
},
{
name: 'receiveShadows',
name: 'recieveShadows',
},
]);
+12 -7
View File
@@ -96,6 +96,13 @@ class StaticLightSettings {
}
}
// tslint:disable: no-shadowed-variable
export namespace LightComponent {
export type Type = EnumAlias<typeof LightType>;
export type PhotometricTerm = EnumAlias<typeof PhotometricTerm>;
}
// tslint:enable: no-shadowed-variable
@ccclass('cc.LightComponent')
export class LightComponent extends Component {
public static Type = LightType;
@@ -175,7 +182,7 @@ export class LightComponent extends Component {
/**
* @en
* static light setttings.
* static light settings.
* @zh
* 静态灯光设置。
*/
@@ -243,6 +250,7 @@ export class LightComponent extends Component {
if (this._light && !this._light.scene && this.node.scene) {
switch (this._type) {
case LightType.DIRECTIONAL:
this._getRenderScene().addDirectionalLight(this._light as DirectionalLight);
this._getRenderScene().setMainLight(this._light as DirectionalLight);
break;
case LightType.SPHERE:
@@ -259,7 +267,9 @@ export class LightComponent extends Component {
if (this._light && this._light.scene) {
switch (this._type) {
case LightType.DIRECTIONAL:
this._light.scene.unsetMainLight(this._light as DirectionalLight);
const scene = this._light.scene;
scene.removeDirectionalLight(this._light as DirectionalLight);
scene.unsetMainLight(this._light as DirectionalLight);
break;
case LightType.SPHERE:
this._light.scene.removeSphereLight(this._light as SphereLight);
@@ -271,8 +281,3 @@ export class LightComponent extends Component {
}
}
}
export namespace LightComponent {
export type Type = EnumAlias<typeof LightType>;
export type PhotometricTerm = EnumAlias<typeof PhotometricTerm>;
}
+3 -1
View File
@@ -243,6 +243,7 @@ export class ModelComponent extends RenderableComponent {
this._updateCastShadow();
}
// Redo, Undo, Prefab restore, etc.
public onRestore () {
this._updateModels();
}
@@ -358,7 +359,8 @@ export class ModelComponent extends RenderableComponent {
protected _updateModelParams () {
if (!this._mesh || !this._model) { return; }
this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformBit.POSITION;
this.node.hasChangedFlags |= TransformBit.POSITION;
this._model.transform.hasChangedFlags |= TransformBit.POSITION;
this._model.isDynamicBatching = this._isBatchingEnabled();
const meshCount = this._mesh ? this._mesh.subMeshCount : 0;
const renderingMesh = this._mesh.renderingSubMeshes;
+2 -2
View File
@@ -370,8 +370,8 @@ export class AnimationComponent extends Eventify(Component) {
* animation.on('play', this.onPlay, this);
* ```
*/
public on<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any) {
const ret = super.on(type, callback, thisArg);
public on<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any, once?: boolean) {
const ret = super.on(type, callback, thisArg, once);
if (type === EventType.LASTFRAME) {
this._syncAllowLastFrameEvent();
}
+60 -27
View File
@@ -34,10 +34,11 @@ import { createBoundTarget, createBufferedTarget, IBufferedTarget, IBoundTarget
import { Playable } from './playable';
import { WrapMode, WrapModeMask, WrappedInfo } from './types';
import { EDITOR } from 'internal:constants';
import { HierarchyPath, evaluatePath } from './target-path';
import { HierarchyPath, evaluatePath, TargetPath } from './target-path';
import { BlendStateBuffer, createBlendStateWriter, IBlendStateWriter } from './skeletal-animation-blending';
import { legacyCC } from '../global-exports';
import { ccenum } from '../value-types/enum';
import { IValueProxyFactory } from './value-proxy';
/**
* @en The event type supported by Animation
@@ -357,8 +358,44 @@ export class AnimationState extends Playable {
this.repeatCount = 1;
}
/**
* Create the bound target. Especially optimized for skeletal case.
*/
const createBoundTargetOptimized = <BoundTargetT extends IBoundTarget>(
createFn: (...args: Parameters<typeof createBoundTarget>) => BoundTargetT | null,
rootTarget: any,
path: TargetPath[],
valueAdapter: IValueProxyFactory | undefined,
isConstant: boolean,
): BoundTargetT | null => {
if (!isTargetingTRS(path) || !this._blendStateBuffer) {
return createFn(rootTarget, path, valueAdapter);
} else {
const targetNode = evaluatePath(rootTarget, ...path.slice(0, path.length - 1));
if (targetNode !== null && targetNode instanceof Node) {
const propertyName = path[path.length - 1] as 'position' | 'rotation' | 'scale' | 'eulerAngles';
const blendStateWriter = createBlendStateWriter(
this._blendStateBuffer,
targetNode,
propertyName,
this,
isConstant,
);
this._blendStateWriters.push(blendStateWriter);
return createFn(rootTarget, [], blendStateWriter);
}
}
return null;
};
this._commonTargetStatuses = clip.commonTargets.map((commonTarget, index) => {
const target = createBufferedTarget(root, commonTarget.modifiers, commonTarget.valueAdapter);
const target = createBoundTargetOptimized(
createBufferedTarget,
root,
commonTarget.modifiers,
commonTarget.valueAdapter,
false,
);
if (target === null) {
return null;
} else {
@@ -391,24 +428,13 @@ export class AnimationState extends Playable {
rootTarget = commonTargetStatus.target.peek();
}
let boundTarget: IBoundTarget | null = null;
if (!isSkeletonCurve(propertyCurve) || !this._blendStateBuffer) {
boundTarget = createBoundTarget(rootTarget, propertyCurve.modifiers, propertyCurve.valueAdapter);
} else {
const targetNode = evaluatePath(rootTarget, ...propertyCurve.modifiers.slice(0, propertyCurve.modifiers.length - 1));
if (targetNode !== null && targetNode instanceof Node) {
const propertyName = propertyCurve.modifiers[propertyCurve.modifiers.length - 1] as 'position' | 'rotation' | 'scale';
const blendStateWriter = createBlendStateWriter(
this._blendStateBuffer,
targetNode,
propertyName,
this,
propertyCurve.curve.constant(),
);
this._blendStateWriters.push(blendStateWriter);
boundTarget = createBoundTarget(rootTarget, [], blendStateWriter);
}
}
const boundTarget = createBoundTargetOptimized(
createBoundTarget,
rootTarget,
propertyCurve.modifiers,
propertyCurve.valueAdapter,
propertyCurve.curve.constant(),
);
if (boundTarget === null) {
// warn(`Failed to bind "${root.name}" to curve in clip ${clip.name}: ${err}`);
@@ -681,6 +707,9 @@ export class AnimationState extends Playable {
if (!this.isPaused) {
this._onPauseOrStop();
}
for (let iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
this._blendStateWriters[iBlendStateWriter].enable(false);
}
this.emit(EventType.STOP, this);
}
@@ -868,6 +897,9 @@ export class AnimationState extends Playable {
}
this._isBlendStateWriterInitialized = true;
}
for (let iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
this._blendStateWriters[iBlendStateWriter].enable(true);
}
legacyCC.director.getAnimationManager().addAnimation(this);
}
@@ -884,22 +916,23 @@ export class AnimationState extends Playable {
}
}
function isSkeletonCurve (curve: IRuntimeCurve) {
function isTargetingTRS (path: TargetPath[]) {
let prs: string | undefined;
if (curve.modifiers.length === 1 && typeof curve.modifiers[0] === 'string') {
prs = curve.modifiers[0];
} else if (curve.modifiers.length > 1) {
for (let i = 0; i < curve.modifiers.length - 1; ++i) {
if (!(curve.modifiers[i] instanceof HierarchyPath)) {
if (path.length === 1 && typeof path[0] === 'string') {
prs = path[0];
} else if (path.length > 1) {
for (let i = 0; i < path.length - 1; ++i) {
if (!(path[i] instanceof HierarchyPath)) {
return false;
}
}
prs = curve.modifiers[curve.modifiers.length - 1] as string;
prs = path[path.length - 1] as string;
}
switch (prs) {
case 'position':
case 'scale':
case 'rotation':
case 'eulerAngles':
return true;
default:
return false;
@@ -20,7 +20,7 @@ export class BlendStateBuffer {
propertyBlendState = nodeBlendState.properties[property] = {
refCount: 0,
weight: 0,
value: ((property === 'position' || property === 'scale') ? new Vec3() : new Quat()) as any,
value: (isVec3Property(property) ? new Vec3() : new Quat()) as any,
};
}
++propertyBlendState.refCount;
@@ -48,10 +48,10 @@ export class BlendStateBuffer {
public apply () {
this._nodeBlendStates.forEach((nodeBlendState, node) => {
const { position, scale, rotation } = nodeBlendState.properties;
const { position, scale, rotation, eulerAngles } = nodeBlendState.properties;
let t: Vec3 | undefined;
let s: Vec3 | undefined;
let r: Quat | undefined;
let r: Quat | Vec3 | undefined;
let anyChanged = false;
if (position && position.weight !== 0) {
position.weight = 0;
@@ -63,11 +63,19 @@ export class BlendStateBuffer {
s = scale.value;
anyChanged = true;
}
// Note: rotation and eulerAngles can not co-exist.
if (rotation && rotation.weight !== 0) {
rotation.weight = 0;
r = rotation.value;
anyChanged = true;
}
if (eulerAngles && eulerAngles.weight !== 0) {
eulerAngles.weight = 0;
r = eulerAngles.value;
anyChanged = true;
}
if (anyChanged) {
node.setRTS(r, t, s);
}
@@ -78,6 +86,7 @@ export class BlendStateBuffer {
export type IBlendStateWriter = IValueProxyFactory & {
initialize: () => void;
destroy: () => void;
enable: (enabled: boolean) => void;
};
export function createBlendStateWriter<P extends BlendingProperty> (
@@ -91,12 +100,11 @@ export function createBlendStateWriter<P extends BlendingProperty> (
constants: boolean,
): IBlendStateWriter {
const blendFunction: BlendFunction<BlendingPropertyValue<P>> =
(property === 'position' || property === 'scale') ?
additive3D as any:
additiveQuat as any;
isVec3Property(property) ? additive3D as any: additiveQuat as any;
let propertyBlendState: PropertyBlendState<BlendingPropertyValue<P>> | null = null;
let isConstCacheValid = false;
let lastWeight = -1;
let isEnabled = true;
return {
initialize () {
if (!propertyBlendState) {
@@ -109,9 +117,21 @@ export function createBlendStateWriter<P extends BlendingProperty> (
propertyBlendState = null;
}
},
enable (enabled: boolean) {
isEnabled = enabled;
},
forTarget: () => {
return {
/**
* Gets the node's actual property for now.
*/
get: () => {
return node[property];
},
set: (value: BlendingPropertyValue<P>) => {
if (!isEnabled) {
return;
}
if (!propertyBlendState) {
return;
}
@@ -139,6 +159,14 @@ export function createBlendStateWriter<P extends BlendingProperty> (
};
}
function isQuatProperty (property: BlendingProperty) {
return property === 'rotation';
}
function isVec3Property (property: BlendingProperty) {
return !isQuatProperty(property);
}
type BlendingProperty = keyof NodeBlendState['properties'];
type BlendingPropertyValue<P extends BlendingProperty> = NonNullable<NodeBlendState['properties'][P]>['value'];
@@ -157,6 +185,7 @@ interface NodeBlendState {
properties: {
position?: PropertyBlendState<Vec3>;
rotation?: PropertyBlendState<Quat>;
eulerAngles?: PropertyBlendState<Vec3>;
scale?: PropertyBlendState<Vec3>;
};
}
@@ -165,6 +194,7 @@ function isEmptyNodeBlendState (nodeBlendState: NodeBlendState) {
// Which is equal to `Object.keys(nodeBlendState.properties).length === 0`.
return !nodeBlendState.properties.position &&
!nodeBlendState.properties.rotation &&
!nodeBlendState.properties.eulerAngles &&
!nodeBlendState.properties.scale;
}
+1
View File
@@ -204,6 +204,7 @@ export class ImageAsset extends Asset {
public destroy () {
if (this.data && this.data instanceof HTMLImageElement) {
this.data.src = "";
this._setRawAsset("");
legacyCC.loader.removeItem(this.data.id);
}
return super.destroy();
+1 -1
View File
@@ -146,7 +146,7 @@ export class SimpleTexture extends TextureBase {
this._checkTextureLoaded();
if (macro.CLEANUP_IMAGE_CACHE) {
image.destroy();
cc.loader.release(image);
}
};
if (image.loaded) {
+5 -5
View File
@@ -119,6 +119,10 @@ export class Texture2D extends SimpleTexture {
super(true);
}
public initialize () {
this.mipmaps = this._mipmaps;
}
public onLoaded () {
this.initialize();
}
@@ -242,10 +246,6 @@ export class Texture2D extends SimpleTexture {
}
}
public initialize () {
this.mipmaps = this._mipmaps;
}
protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo) {
return Object.assign({
type: GFXTextureType.TEX2D,
@@ -264,7 +264,7 @@ export class Texture2D extends SimpleTexture {
}
}
if (ready){
if (ready) {
super._textureReady();
}
}
-14
View File
@@ -208,12 +208,6 @@ class Component extends CCObject {
*/
public _id: string = idGenerator.getNewId();
/**
* Register all related EventTargets,
* all event callbacks will be removed in _onPreDestroy
*/
private _eventTargets: any[] = [];
// private __scriptUuid = '';
public _getRenderScene (): RenderScene {
@@ -381,14 +375,6 @@ class Component extends CCObject {
// Schedules
this.unscheduleAllCallbacks();
// Remove all listeners
const eventTargets = this._eventTargets;
for (let i = 0, l = eventTargets.length; i < l; ++i) {
const target = eventTargets[i];
target && target.targetOff(this);
}
eventTargets.length = 0;
//
if (EDITOR && !TEST) {
// @ts-ignore
+1 -1
View File
@@ -328,7 +328,7 @@ class CCObject {
this._onPreDestroy();
}
if ((TEST ? (/* make EDITOR mockable*/ Function('return !EDITOR'))() : !EDITOR) || legacyCC.engine._isPlaying) {
if (!EDITOR || legacyCC.engine._isPlaying) {
this._destruct();
}
+62 -25
View File
@@ -31,6 +31,7 @@
import { Pool } from '../memop';
import { array, createMap } from '../utils/js';
import { TEST } from 'internal:constants';
import { CCObject, isValid } from '../data/object';
import { legacyCC } from '../global-exports';
const fastRemoveAt = array.fastRemoveAt;
@@ -42,16 +43,31 @@ class CallbackInfo {
public once = false;
public set (callback: Function, target?: Object, once?: boolean) {
this.callback = callback;
this.callback = callback || empty;
this.target = target;
this.once = !!once;
}
public reset () {
this.target = undefined;
this.callback = empty;
this.once = false;
}
public check () {
// Validation
if (this.target instanceof CCObject && !isValid(this.target, true)) {
return false;
}
else {
return true;
}
}
}
const callbackInfoPool = new Pool(() => {
return new CallbackInfo();
}, 32);
/**
* @zh 事件监听器列表的简单封装。
* @en A simple list of event callbacks
@@ -71,6 +87,7 @@ export class CallbackList {
for (let i = 0; i < this.callbackInfos.length; ++i) {
const info = this.callbackInfos[i];
if (info && info.callback === cb) {
info.reset();
callbackInfoPool.free(info);
fastRemoveAt(this.callbackInfos, i);
--i;
@@ -86,6 +103,7 @@ export class CallbackList {
for (let i = 0; i < this.callbackInfos.length; ++i) {
const info = this.callbackInfos[i];
if (info && info.target === target) {
info.reset();
callbackInfoPool.free(info);
fastRemoveAt(this.callbackInfos, i);
--i;
@@ -101,8 +119,14 @@ export class CallbackList {
public cancel (index: number) {
const info = this.callbackInfos[index];
if (info) {
info.reset();
if (this.isInvoking) {
this.callbackInfos[index] = null;
}
else {
fastRemoveAt(this.callbackInfos, index);
}
callbackInfoPool.free(info);
this.callbackInfos[index] = null;
}
this.containCanceled = true;
}
@@ -115,6 +139,7 @@ export class CallbackList {
for (let i = 0; i < this.callbackInfos.length; i++) {
const info = this.callbackInfos[i];
if (info) {
info.reset();
callbackInfoPool.free(info);
this.callbackInfos[i] = null;
}
@@ -175,13 +200,16 @@ export class CallbacksInvoker {
* @param once - Whether invoke the callback only once (and remove it)
*/
public on (key: string, callback: Function, target?: Object, once?: boolean) {
let list = this._callbackTable[key];
if (!list) {
list = this._callbackTable[key] = callbackListPool.alloc();
if (!this.hasEventListener(key, callback, target)) {
let list = this._callbackTable[key];
if (!list) {
list = this._callbackTable[key] = callbackListPool.alloc();
}
const info = callbackInfoPool.alloc();
info.set(callback, target, once);
list.callbackInfos.push(info);
}
const info = callbackInfoPool.alloc();
info.set(callback, target, once);
list.callbackInfos.push(info);
return callback;
}
/**
@@ -191,7 +219,7 @@ export class CallbacksInvoker {
* @param callback - Callback function when event triggered
* @param target - Callback callee
*/
public hasEventListener (key: string, callback?: Function, target: Object | null = null) {
public hasEventListener (key: string, callback?: Function, target?: Object) {
const list = this._callbackTable[key];
if (!list) {
return false;
@@ -202,8 +230,8 @@ export class CallbacksInvoker {
if (!callback) {
// Make sure no cancelled callbacks
if (list.isInvoking) {
for (const info of infos) {
if (info) {
for (let i = 0; i < infos.length; ++i) {
if (infos[i]) {
return true;
}
}
@@ -214,8 +242,9 @@ export class CallbacksInvoker {
}
}
for (const info of infos) {
if (info && info.callback === callback && info.target === target) {
for (let i = 0; i < infos.length; ++i) {
let info = infos[i];
if (info && info.check() && info.callback === callback && info.target === target) {
return true;
}
}
@@ -277,13 +306,7 @@ export class CallbacksInvoker {
for (let i = 0; i < infos.length; ++i) {
const info = infos[i];
if (info && info.callback === callback && info.target === target) {
if (list.isInvoking) {
list.cancel(i);
}
else {
fastRemoveAt(infos, i);
callbackInfoPool.free(info);
}
list.cancel(i);
break;
}
}
@@ -320,11 +343,18 @@ export class CallbacksInvoker {
if (info.once) {
this.off(key, callback, target);
}
if (target) {
callback.call(target, arg0, arg1, arg2, arg3, arg4);
// Lazy check validity of callback target,
// if target is CCObject and is no longer valid, then remove the callback info directly
if (!info.check()) {
this.off(key, callback, target);
}
else {
callback(arg0, arg1, arg2, arg3, arg4);
if (target) {
callback.call(target, arg0, arg1, arg2, arg3, arg4);
}
else {
callback(arg0, arg1, arg2, arg3, arg4);
}
}
}
}
@@ -342,7 +372,14 @@ export class CallbacksInvoker {
* 移除所有回调。
*/
public clear () {
this._callbackTable = createMap(true);
for (let key in this._callbackTable) {
let list = this._callbackTable[key];
if (list) {
list.clear();
callbackListPool.free(list);
delete this._callbackTable[key];
}
}
}
}
+3 -59
View File
@@ -2,7 +2,6 @@
* @category event
*/
import { fastRemove } from '../utils/array';
import { CallbacksInvoker } from './callbacks-invoker';
import { createMap } from '../utils/js';
@@ -10,13 +9,6 @@ type Constructor<T = {}> = new (...args: any[]) => T;
type EventType = string;
const {
prototype: {
on: callbacksInvokerOn,
off: callbacksInvokerOff,
},
} = CallbacksInvoker;
/**
* @zh
* 实现该接口的对象具有处理事件的能力。
@@ -50,7 +42,7 @@ export interface IEventified {
* cc.log("fire in the hole");
* }, node);
*/
on<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any): typeof callback;
on<TFunction extends Function> (type: EventType, callback: TFunction, thisArg?: any, once?: boolean): typeof callback;
/**
* @en
@@ -137,57 +129,14 @@ export interface 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);
}
}
return this.on(type, callback, target, true);
}
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
@@ -199,9 +148,4 @@ export function Eventify<TBase> (base: Constructor<TBase>): Constructor<TBase &
}
return Eventified as unknown as any;
}
interface ITargetImpl extends Object {
__eventTargets?: any[];
node?: ITargetImpl;
}
}
+5 -3
View File
@@ -526,13 +526,13 @@ export class Game extends EventTarget {
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
*/
public on (type: string, callback: Function, target?: object): any {
public on (type: string, callback: Function, target?: object, once?: boolean): any {
// Make sure EVENT_ENGINE_INITED callbacks to be invoked
if (this._inited && type === Game.EVENT_ENGINE_INITED) {
callback.call(target);
}
else {
this.eventTargetOn(type, callback, target);
this.eventTargetOn(type, callback, target, once);
}
}
@@ -586,7 +586,6 @@ export class Game extends EventTarget {
legacyCC.internal.SplashScreen.instance.main(legacyCC.director.root);
}
legacyCC.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts);
return this._inited;
}
@@ -597,6 +596,9 @@ export class Game extends EventTarget {
* @param {Function} onStart - function to be executed after game initialized
*/
public run (onStart: Function | null, legacyOnStart?: Function | null) {
if (!EDITOR) {
this._initEvents();
}
if (typeof onStart !== 'function' && legacyOnStart) {
const config: IGameConfig = this.onStart as IGameConfig;
this.init(config);
+3
View File
@@ -867,6 +867,9 @@ export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: W
gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
}
else {
gl.deleteTexture(glTexture);
}
}
break;
+5 -2
View File
@@ -136,7 +136,7 @@ export function GFXFormatToWebGLType (format: GFXFormat, gl: WebGL2RenderingCont
case GFXFormat.RGB9E5: return gl.FLOAT;
case GFXFormat.D16: return gl.UNSIGNED_SHORT;
case GFXFormat.D16S8: return gl.UNSIGNED_INT_24_8; // not supported, fallback
case GFXFormat.D16S8: return gl.UNSIGNED_INT_24_8; // no D16S8 support
case GFXFormat.D24: return gl.UNSIGNED_INT;
case GFXFormat.D24S8: return gl.UNSIGNED_INT_24_8;
case GFXFormat.D32F: return gl.FLOAT;
@@ -235,7 +235,7 @@ export function GFXFormatToWebGLInternalFormat (format: GFXFormat, gl: WebGL2Ren
case GFXFormat.RGB10A2UI: return gl.RGB10_A2UI;
case GFXFormat.R11G11B10F: return gl.R11F_G11F_B10F;
case GFXFormat.D16: return gl.DEPTH_COMPONENT16;
case GFXFormat.D16S8: return gl.DEPTH_STENCIL;
case GFXFormat.D16S8: return gl.DEPTH24_STENCIL8; // no D16S8 support
case GFXFormat.D24: return gl.DEPTH_COMPONENT24;
case GFXFormat.D24S8: return gl.DEPTH24_STENCIL8;
case GFXFormat.D32F: return gl.DEPTH_COMPONENT32F;
@@ -1052,6 +1052,9 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2GFXDevice, gpuTexture:
gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
*/
}
else {
gl.deleteTexture(glTexture);
}
} else {
const glRenderbuffer = gl.createRenderbuffer();
if (glRenderbuffer && gpuTexture.size > 0) {
+6 -3
View File
@@ -307,8 +307,10 @@ export class Color extends ValueType {
super();
if (typeof r === 'string') {
this.fromHEX(r);
} else if (g !== undefined) {
this.set(r as number, g, b, a);
} else {
this.set(r as Color, g, b, a);
this.set(r as Color);
}
}
@@ -573,8 +575,9 @@ export class Color extends ValueType {
* @param [a=255] 指定的 Alpha 通道。
* @returns 当前颜色。
*/
public set (other: Color, g?: number, b?: number, a?: number): Color;
public set (r?: number | Color, g?: number, b?: number, a?: number) {
public set(other: Color): Color;
public set(r?: number, g?: number, b?: number, a?: number): Color;
public set(r?: number | Color, g?: number, b?: number, a?: number): Color {
if (typeof r === 'object') {
if (r._val != null) {
this._val = r._val;
+3 -2
View File
@@ -31,6 +31,7 @@
import Event from '../../event/event';
import { Vec2 } from '../../math/vec2';
import { Touch } from './touch';
import { Acceleration } from './input-manager';
import { legacyCC } from '../../global-exports';
let _vec2 = new Vec2();
@@ -606,13 +607,13 @@ export class EventAcceleration extends Event {
* @en The acceleration object
* @zh 加速度对象
*/
public acc: Object;
public acc: Acceleration;
/**
* @param acc - The acceleration
* @param bubbles - Indicate whether the event bubbles up through the hierarchy or not.
*/
constructor (acc: Object, bubbles?: boolean) {
constructor (acc: Acceleration, bubbles?: boolean) {
super(Event.ACCELERATION, bubbles);
this.acc = acc;
}
@@ -71,7 +71,7 @@ interface IView {
* @en the device accelerometer reports values for each axis in units of g-force.
* @zh 设备重力传感器传递的各个轴的数据。
*/
class Acceleration {
export class Acceleration {
public x: number;
public y: number;
public z: number;
@@ -116,11 +116,11 @@ export class SystemEvent extends EventTarget {
* @param callback - The event listener's callback
* @param target - The event listener's target and callee
*/
public on (type: string, callback: Function, target?: Object) {
public on (type: string, callback: Function, target?: Object, once?: boolean) {
if (EDITOR) {
return;
}
super.on(type, callback, target);
super.on(type, callback, target, once);
// Keyboard
if (type === SystemEventType.KEY_DOWN || type === SystemEventType.KEY_UP) {
+7
View File
@@ -29,6 +29,9 @@ ccenum(PrimitiveType);
*/
@ccclass('cc.Primitive')
export class Primitive extends Mesh {
public static PrimitiveType = PrimitiveType;
/**
* @en
* The type of the primitive mesh, set it before you call onLoaded.
@@ -63,4 +66,8 @@ export class Primitive extends Mesh {
}
}
export namespace Primitive {
export type PrimitiveType = EnumAlias<typeof PrimitiveType>;
}
legacyCC.Primitive = Primitive;
+1 -1
View File
@@ -73,7 +73,7 @@ export class Light {
set node (n) {
this._node = n;
if (this._node) {
this._node.hasChangedFlags = TransformBit.ROTATION;
this._node.hasChangedFlags |= TransformBit.ROTATION;
}
}
+2 -2
View File
@@ -8,11 +8,11 @@ import { getTypedArrayConstructor, GFXBufferUsageBit, GFXFormat, GFXFormatInfos,
import { GFXDevice, GFXFeature } from '../../gfx/device';
import { Mat4, Vec3, Vec4 } from '../../math';
import { Pool } from '../../memop';
import { UBOLocal, UniformLightingMapSampler, INST_MAT_WORLD } from '../../pipeline/define';
import { INST_MAT_WORLD, UBOLocal, UniformLightingMapSampler } from '../../pipeline/define';
import { Node } from '../../scene-graph';
import { Layers } from '../../scene-graph/layers';
import { RenderScene } from './render-scene';
import { Texture2D } from '../..';
import { Texture2D } from '../../assets/texture-2d';
import { genSamplerHash, samplerLib } from '../../renderer/core/sampler-lib';
import { IGFXAttribute } from '../../gfx';
import { SubModel, IPSOCreateInfo } from './submodel';
+28 -3
View File
@@ -15,6 +15,7 @@ import { Skybox } from './skybox';
import { SphereLight } from './sphere-light';
import { SpotLight } from './spot-light';
import { PREVIEW } from 'internal:constants';
import { TransformBit } from '../../scene-graph/node-enum';
import { Fog } from './fog';
import { legacyCC } from '../../global-exports';
@@ -122,6 +123,7 @@ export class RenderScene {
private _skybox: Skybox;
private _planarShadows: PlanarShadows;
private _models: Model[] = [];
private _directionalLights: DirectionalLight[] = [];
private _sphereLights: SphereLight[] = [];
private _spotLights: SpotLight[] = [];
private _mainLight: DirectionalLight | null = null;
@@ -173,13 +175,36 @@ export class RenderScene {
}
public setMainLight (dl: DirectionalLight) {
dl.attachToScene(this);
this._mainLight = dl;
}
public unsetMainLight (dl: DirectionalLight) {
dl.detachFromScene();
this._mainLight = null;
if (this._mainLight === dl) {
const dlList = this._directionalLights;
if (dlList.length) {
this._mainLight = dlList[dlList.length - 1];
if (this._mainLight.node) { // trigger update
this._mainLight.node.hasChangedFlags |= TransformBit.ROTATION;
}
} else {
this._mainLight = null;
}
}
}
public addDirectionalLight (dl: DirectionalLight) {
dl.attachToScene(this);
this._directionalLights.push(dl);
}
public removeDirectionalLight (dl: DirectionalLight) {
for (let i = 0; i < this._directionalLights.length; ++i) {
if (this._directionalLights[i] === dl) {
dl.detachFromScene();
this._directionalLights.splice(i, 1);
return;
}
}
}
public addSphereLight (pl: SphereLight) {
+6 -6
View File
@@ -187,9 +187,9 @@ export class Root {
private _dataPoolMgr: DataPoolManager;
private _scenes: RenderScene[] = [];
private _views: RenderView[] = [];
private _modelPools: Map<Function, Pool<any>> = new Map<Function, Pool<any>>();
private _modelPools = new Map<Constructor<Model>, Pool<Model>>();
private _cameraPool: Pool<Camera> | null = null;
private _lightPools: Map<Function, Pool<any>> = new Map<Function, Pool<any>>();
private _lightPools = new Map<Constructor<Light>, Pool<Light>>();
private _time: number = 0;
private _frameTime: number = 0;
private _fpsTime: number = 0;
@@ -488,11 +488,11 @@ export class Root {
this._modelPools.set(mClass, new Pool(() => new mClass(), 10));
p = this._modelPools.get(mClass)!;
}
return p.alloc();
return p.alloc() as T;
}
public destroyModel (m: Model) {
const p = this._modelPools.get(m.constructor);
const p = this._modelPools.get(m.constructor as Constructor<Model>);
if (p) {
p.free(m);
m.destroy();
@@ -523,11 +523,11 @@ export class Root {
this._lightPools.set(lClass, new Pool(() => new lClass(), 4));
l = this._lightPools.get(lClass)!;
}
return l.alloc();
return l.alloc() as T;
}
public destroyLight (l: Light) {
const p = this._lightPools.get(l.constructor);
const p = this._lightPools.get(l.constructor as Constructor<Light>);
l.destroy();
if (p) {
p.free(l);
+26 -34
View File
@@ -336,11 +336,6 @@ export class BaseNode extends CCObject implements ISchedulable {
protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this);
protected _eventMask = 0;
// Register all related EventTargets,
// all event callbacks will be removed in _onPreDestroy
// protected __eventTargets: EventTarget[] = [];
protected __eventTargets: any[] = [];
protected _siblingIndex: number = 0;
protected _registerIfAttached = !EDITOR ? undefined : function (this: BaseNode, register) {
@@ -1149,8 +1144,8 @@ export class BaseNode extends CCObject implements ISchedulable {
* eventTarget.emit('fire', message, emitter);
* ```
*/
public emit (type: string, ...args: any[]) {
this._eventProcessor.emit(type, ...args);
public emit (type: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) {
this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
}
/**
@@ -1168,10 +1163,12 @@ export class BaseNode extends CCObject implements ISchedulable {
* @en Checks whether the EventTarget object has any callback registered for a specific type of event.
* @zh 检查事件目标对象是否有为特定类型的事件注册的回调。
* @param type - The type of event.
* @param callback - The callback function of the event listener, if absent all event listeners for the given type will be removed
* @param target - The callback callee of the event listener
* @return True if a callback of the specified type is registered; false otherwise.
*/
public hasEventListener (type: string) {
return this._eventProcessor.hasEventListener(type);
public hasEventListener (type: string, callback?: Function, target?: Object) {
return this._eventProcessor.hasEventListener(type, callback, target);
}
/**
@@ -1345,31 +1342,6 @@ 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) {
// destroy immediate so its _onPreDestroy can be called
children[i]._destroyImmediate();
}
// destroy self components
const comps = this._components;
for (let i = 0; i < comps.length; ++i) {
// destroy immediate so its _onPreDestroy can be called
// TO DO
comps[i]._destroyImmediate();
}
// remove from persist
if (this._persistNode) {
legacyCC.game.removePersistRootNode(this);
@@ -1389,7 +1361,27 @@ export class BaseNode extends CCObject implements ISchedulable {
}
}
// emit node destroy event (this should before event processor destroy)
this.emit(SystemEventType.NODE_DESTROYED, this);
// Destroy node event processor
this._eventProcessor.destroy();
// destroy children
const children = this._children;
for (let i = 0; i < children.length; ++i) {
// destroy immediate so its _onPreDestroy can be called
children[i]._destroyImmediate();
}
// destroy self components
const comps = this._components;
for (let i = 0; i < comps.length; ++i) {
// destroy immediate so its _onPreDestroy can be called
// TO DO
comps[i]._destroyImmediate();
}
return destroyByParent;
}
+34 -28
View File
@@ -28,7 +28,6 @@
*/
import Event from '../event/event';
import { EventTarget } from '../event/event-target';
import { Vec2 } from '../math/vec2';
import { SystemEventType } from '../platform/event-manager/event-enum';
import { EventListener } from '../platform/event-manager/event-listener';
@@ -37,8 +36,9 @@ import { EventMouse, EventTouch } from '../platform/event-manager/events';
import { Touch } from '../platform/event-manager/touch';
import { BaseNode } from './base-node';
import { Node } from './node';
import { legacyCC } from '../global-exports';
import { CallbacksInvoker } from '../event/callbacks-invoker';
import { errorID } from '../platform/debug';
import { legacyCC } from '../global-exports';
const _cachedArray = new Array<BaseNode>(16);
let _currentHovered: BaseNode | null = null;
@@ -289,16 +289,15 @@ function _searchMaskInParent (node: Node | null) {
function _checkListeners (node: BaseNode, events: string[]) {
if (!node._persistNode) {
let i = 0;
if (node.eventProcessor.bubblingTargets) {
for (; i < events.length; ++i) {
for (let i = 0; i < events.length; ++i) {
if (node.eventProcessor.bubblingTargets.hasEventListener(events[i])) {
return true;
}
}
}
if (node.eventProcessor.capturingTargets) {
for (; i < events.length; ++i) {
for (let i = 0; i < events.length; ++i) {
if (node.eventProcessor.capturingTargets.hasEventListener(events[i])) {
return true;
}
@@ -322,13 +321,13 @@ export class NodeEventProcessor {
* @zh
* 节点冒泡事件监听器
*/
public bubblingTargets: EventTarget | null = null;
public bubblingTargets: CallbacksInvoker | null = null;
/**
* @zh
* 节点捕获事件监听器
*/
public capturingTargets: EventTarget | null = null;
public capturingTargets: CallbacksInvoker | null = null;
/**
* @zh
* 触摸监听器
@@ -377,6 +376,9 @@ export class NodeEventProcessor {
this.mouseListener = null;
}
}
this.capturingTargets && this.capturingTargets.clear();
this.bubblingTargets && this.bubblingTargets.clear();
}
/**
@@ -432,7 +434,7 @@ export class NodeEventProcessor {
// break;
// }
if (!this.bubblingTargets) {
this.bubblingTargets = new EventTarget();
this.bubblingTargets = new CallbacksInvoker();
}
return this.bubblingTargets.on(type, callback, target);
}
@@ -460,15 +462,18 @@ export class NodeEventProcessor {
public once (type: string, callback: Function, target?: Object, useCapture?: Object) {
const forDispatch = this._checknSetupSysEvent(type);
let listeners: EventTarget;
let listeners: CallbacksInvoker;
if (forDispatch && useCapture) {
listeners = this.capturingTargets = this.capturingTargets || new EventTarget();
listeners = this.capturingTargets = this.capturingTargets || new CallbacksInvoker();
}
else {
listeners = this.bubblingTargets = this.bubblingTargets || new EventTarget();
listeners = this.bubblingTargets = this.bubblingTargets || new CallbacksInvoker();
}
listeners.once(type, callback, target);
listeners.on(type, callback, target, true);
listeners.on(type, () => {
this.off(type, callback, target);
}, undefined, true);
}
/**
@@ -536,20 +541,20 @@ export class NodeEventProcessor {
* 通过事件名发送自定义事件
*
* @param type - 一个监听事件类型的字符串。
* @param arg1 - 回调第一个参数。
* @param arg2 - 回调第二个参数。
* @param arg3 - 回调第三个参数。
* @param arg4 - 回调第四个参数。
* @param arg5 - 回调第五个参数。
* @param arg0 - 回调第一个参数。
* @param arg1 - 回调第二个参数。
* @param arg2 - 回调第三个参数。
* @param arg3 - 回调第四个参数。
* @param arg4 - 回调第五个参数。
* @example
* ```typescript
* eventTarget.emit('fire', event);
* eventTarget.emit('fire', message, emitter);
* ```
*/
public emit (type: string, ...args: any[]) {
public emit (type: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) {
if (this.bubblingTargets) {
this.bubblingTargets.emit(type, ...args);
this.bubblingTargets.emit(type, arg0, arg1, arg2, arg3, arg4);
}
}
@@ -569,15 +574,17 @@ export class NodeEventProcessor {
* 是否监听过某事件。
*
* @param type - 一个监听事件类型的字符串。
* @param callback - The callback function of the event listener, if absent all event listeners for the given type will be removed
* @param target - The callback callee of the event listener
* @return - 返回是否当前节点已监听该事件类型。
*/
public hasEventListener (type: string) {
public hasEventListener (type: string, callback?: Function, target?: Object) {
let has = false;
if (this.bubblingTargets) {
has = this.bubblingTargets.hasEventListener(type);
has = this.bubblingTargets.hasEventListener(type, callback, target);
}
if (!has && this.capturingTargets) {
has = this.capturingTargets.hasEventListener(type);
has = this.capturingTargets.hasEventListener(type, callback, target);
}
return has;
}
@@ -590,10 +597,10 @@ export class NodeEventProcessor {
*/
public targetOff (target: string | Object) {
if (this.capturingTargets) {
this.capturingTargets.targetOff(target);
this.capturingTargets.removeAll(target);
}
if (this.bubblingTargets) {
this.bubblingTargets.targetOff(target);
this.bubblingTargets.removeAll(target);
}
if (this.touchListener && !_checkListeners(this.node, _touchEvents)) {
@@ -704,11 +711,11 @@ export class NodeEventProcessor {
return;
}
let listeners: EventTarget | null = null;
let listeners: CallbacksInvoker | null = null;
if (useCapture) {
listeners = this.capturingTargets = this.capturingTargets || new EventTarget();
listeners = this.capturingTargets = this.capturingTargets || new CallbacksInvoker();
} else {
listeners = this.bubblingTargets = this.bubblingTargets || new EventTarget();
listeners = this.bubblingTargets = this.bubblingTargets || new CallbacksInvoker();
}
if (!listeners.hasEventListener(type, callback, target)) {
@@ -737,7 +744,6 @@ export class NodeEventProcessor {
if (listeners) {
listeners.off(type, callback, target);
}
}
}
}
+32 -18
View File
@@ -463,7 +463,7 @@ export class Node extends BaseNode {
const len = this._children.length;
for (let i = 0; i < len; ++i) {
const child = this._children[i];
child.isValid && child.invalidateChildren(dirtyBit);
if (child.isValid) { child.invalidateChildren(dirtyBit); }
}
}
@@ -854,16 +854,16 @@ export class Node extends BaseNode {
}
const parent = this._parent;
if (parent) {
parent.updateWorldTransform();
Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, parent._rot));
this.updateWorldTransform();
Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, this._rot));
Mat3.multiplyMat4(m3_1, m3_1, parent._mat);
m3_scaling.m00 = this._scale.x;
m3_scaling.m04 = this._scale.y;
m3_scaling.m08 = this._scale.z;
Mat3.multiply(m3_1, m3_scaling, Mat3.invert(m3_1, m3_1));
this._lscale.x = m3_1.m00;
this._lscale.y = m3_1.m04;
this._lscale.z = m3_1.m08;
this._lscale.x = Vec3.set(v3_a, m3_1.m00, m3_1.m01, m3_1.m02).length();
this._lscale.y = Vec3.set(v3_a, m3_1.m03, m3_1.m04, m3_1.m05).length();
this._lscale.z = Vec3.set(v3_a, m3_1.m06, m3_1.m07, m3_1.m08).length();
} else {
Vec3.copy(this._lscale, this._scale);
}
@@ -934,14 +934,32 @@ export class Node extends BaseNode {
* @param pos The position
* @param scale The scale
*/
public setRTS (rot?: Quat, pos?: Vec3, scale?: Vec3) {
if (rot) { Quat.copy(this._lrot, rot); }
if (pos) { Vec3.copy(this._lpos, pos); }
if (scale) { Vec3.copy(this._lscale, scale); }
this.invalidateChildren(TransformBit.TRS);
this._eulerDirty = true;
if (this._eventMask & TRANSFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.TRS);
public setRTS (rot?: Quat | Vec3, pos?: Vec3, scale?: Vec3) {
let dirtyBit: TransformBit = 0;
if (rot) {
dirtyBit |= TransformBit.ROTATION;
if ((rot as Quat).w !== undefined) {
Quat.copy(this._lrot, rot as Quat);
this._eulerDirty = true;
} else {
Vec3.copy(this._euler, rot);
Quat.fromEuler(this._lrot, rot.x, rot.y, rot.z);
this._eulerDirty = false;
}
}
if (pos) {
Vec3.copy(this._lpos, pos);
dirtyBit |= TransformBit.POSITION;
}
if (scale) {
Vec3.copy(this._lscale, scale);
dirtyBit |= TransformBit.SCALE;
}
if (dirtyBit) {
this.invalidateChildren(dirtyBit);
if (this._eventMask & TRANSFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, dirtyBit);
}
}
}
@@ -1004,10 +1022,6 @@ export class Node extends BaseNode {
}
}
public _onPreDestroy () {
this._eventProcessor.destroy();
super._onPreDestroy();
}
}
legacyCC.Node = Node;
+4 -2
View File
@@ -7,17 +7,19 @@ import { LineComponent } from './line-component';
import { ParticleSystemComponent } from './particle-system-component';
import { ParticleUtils } from './particle-utils';
import './deprecated';
import CurveRange from './animator/curve-range';
import { legacyCC } from '../core/global-exports';
export {
BillboardComponent,
LineComponent,
ParticleSystemComponent,
ParticleUtils
ParticleUtils,
CurveRange
};
legacyCC.ParticleSystemComponent = ParticleSystemComponent;
legacyCC.BillboardComponent = BillboardComponent;
legacyCC.LineComponent = LineComponent;
legacyCC.ParticleUtils = ParticleUtils;
legacyCC.ParticleUtils = ParticleUtils;
@@ -377,6 +377,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
const shareMaterial = ps.sharedMaterial;
if (shareMaterial != null) {
const effectName = shareMaterial._effectAsset._name;
this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0);
// reset material
if (effectName.indexOf('particle') === -1 || effectName.indexOf('particle-gpu') !== -1) {
ps.setMaterial(null, 0);
@@ -388,6 +389,9 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
_matInsInfo.owner = this._particleSystem;
_matInsInfo.subModelIdx = 0;
this._defaultMat = new MaterialInstance(_matInsInfo);
if (this._renderInfo!.mainTexture !== null) {
this._defaultMat.setProperty('mainTexture', this._renderInfo!.mainTexture);
}
}
const mat: Material = ps.getMaterialInstance(0) || this._defaultMat;
if (ps._simulationSpace === Space.World) {
@@ -1,11 +1,23 @@
import { Material, Mesh } from '../../core/assets';
import { Material, Mesh, Texture2D } from '../../core/assets';
import { ccclass, property } from '../../core/data/class-decorator';
import { RenderMode} from '../enum';
import ParticleSystemRendererCPU from './particle-system-renderer-cpu';
import ParticleSystemRendererGPU from './particle-system-renderer-gpu';
import { director } from '../../core/director';
import { GFXDevice, GFXFeature } from '../../core/gfx/device';
function isSupportGPUParticle () {
const device: GFXDevice = director.root!.device;
if (device.maxVertexTextureUnits >= 8 && device.hasFeature(GFXFeature.TEXTURE_FLOAT)) {
return true;
}
cc.warn("Maybe the device has restrictions on vertex textures or does not support float textures.");
return false;
}
@ccclass('cc.ParticleSystemRenderer')
export default class ParticleSystemRenderer {
/**
* @zh 设定粒子生成模式。
*/
@@ -136,6 +148,17 @@ export default class ParticleSystemRenderer {
this._particleSystem.setMaterial(val, 1);
}
@property
private _mainTexture: Texture2D | null = null;
public get mainTexture () {
return this._mainTexture;
}
public set mainTexture (val) {
this._mainTexture = val;
}
@property
private _useGPU: boolean = false;
@@ -152,7 +175,12 @@ export default class ParticleSystemRenderer {
return;
}
this._useGPU = val;
if (!isSupportGPUParticle()) {
this._useGPU = false;
} else {
this._useGPU = val;
}
this._switchProcessor();
}
@@ -160,7 +188,8 @@ export default class ParticleSystemRenderer {
onInit (ps: any) {
this._particleSystem = ps;
this._particleSystem.processor = this._useGPU ? new ParticleSystemRendererGPU(this) : new ParticleSystemRendererCPU(this);
const useGPU = this._useGPU && isSupportGPUParticle();
this._particleSystem.processor = useGPU ? new ParticleSystemRendererGPU(this) : new ParticleSystemRendererCPU(this);
this._particleSystem.processor.onInit(ps);
}
@@ -357,29 +357,40 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
if (!this._particleSystem) {
return;
}
if (this._particleSystem.sharedMaterial != null && this._particleSystem.sharedMaterial._effectAsset._name.indexOf('particle-gpu') === -1) {
// reset material
this._particleSystem.setMaterial(null, 0);
const ps = this._particleSystem;
const shareMaterial = ps.sharedMaterial;
if (shareMaterial !== null) {
const effectName = shareMaterial._effectAsset._name;
this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0);
if (effectName.indexOf('particle-gpu') === -1) {
this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0);
// reset material
this._particleSystem.setMaterial(null, 0);
}
}
if (this._particleSystem.sharedMaterial == null && this._defaultMat == null) {
if (shareMaterial == null && this._defaultMat == null) {
_matInsInfo.parent = builtinResMgr.get<Material>('default-particle-gpu-material');
_matInsInfo.owner = this._particleSystem;
_matInsInfo.owner = ps;
_matInsInfo.subModelIdx = 0;
this._defaultMat = new MaterialInstance(_matInsInfo);
if (this._renderInfo!.mainTexture !== null) {
this._defaultMat.setProperty('mainTexture', this._renderInfo!.mainTexture);
}
}
const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat;
const mat: Material | null = ps.getMaterialInstance(0) || this._defaultMat;
this._particleSystem.node.getWorldMatrix(_tempWorldTrans);
switch (this._particleSystem.scaleSpace) {
ps.node.getWorldMatrix(_tempWorldTrans);
switch (ps.scaleSpace) {
case Space.Local:
this._particleSystem.node.getScale(this._node_scale);
ps.node.getScale(this._node_scale);
break;
case Space.World:
this._particleSystem.node.getWorldScale(this._node_scale);
ps.node.getWorldScale(this._node_scale);
break;
}
if (this._particleSystem._simulationSpace === Space.World) {
if (ps._simulationSpace === Space.World) {
this._defines[CC_USE_WORLD_SPACE] = true;
} else {
this._defines[CC_USE_WORLD_SPACE] = false;
@@ -400,7 +411,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
} else {
console.warn(`particle system renderMode ${renderMode} not support.`);
}
const textureModule = this._particleSystem._textureAnimationModule;
const textureModule = ps._textureAnimationModule;
if (textureModule && textureModule.enable) {
Vec2.set(this._frameTile_velLenScale, textureModule.numTilesX, textureModule.numTilesY);
}
+2 -2
View File
@@ -119,7 +119,7 @@ export class AmmoShape implements IBaseShape {
this._btCompound = null;
(this._collider as any) = null;
const shape = Ammo.castObject(this._btShape, Ammo.btCollisionShape);
shape.wrapped = null;
shape['wrapped'] = null;
Ammo.destroy(this.transform);
Ammo.destroy(this.pos);
Ammo.destroy(this.quat);
@@ -184,7 +184,7 @@ export class AmmoShape implements IBaseShape {
setWrapper () {
const shape = Ammo.castObject(this._btShape, Ammo.btCollisionShape);
shape.wrapped = this;
shape['wrapped'] = this;
}
setScale () {
@@ -226,14 +226,17 @@ export class CannonRigidBody implements IRigidBody {
setGroup (v: number): void {
this.impl.collisionFilterGroup = v;
if (!this.impl.isAwake()) this.impl.wakeUp();
}
addGroup (v: number): void {
this.impl.collisionFilterGroup |= v;
if (!this.impl.isAwake()) this.impl.wakeUp();
}
removeGroup (v: number): void {
this.impl.collisionFilterGroup &= ~v;
if (!this.impl.isAwake()) this.impl.wakeUp();
}
/** mask */
@@ -243,14 +246,17 @@ export class CannonRigidBody implements IRigidBody {
setMask (v: number): void {
this.impl.collisionFilterMask = v;
if (!this.impl.isAwake()) this.impl.wakeUp();
}
addMask (v: number): void {
this.impl.collisionFilterMask |= v;
if (!this.impl.isAwake()) this.impl.wakeUp();
}
removeMask (v: number): void {
this.impl.collisionFilterMask &= ~v;
if (!this.impl.isAwake()) this.impl.wakeUp();
}
}
@@ -123,14 +123,17 @@ export class CannonShape implements IBaseShape {
setGroup (v: number): void {
this._body.collisionFilterGroup = v;
if (!this._body.isAwake()) this._body.wakeUp();
}
addGroup (v: number): void {
this._body.collisionFilterGroup |= v;
if (!this._body.isAwake()) this._body.wakeUp();
}
removeGroup (v: number): void {
this._body.collisionFilterGroup &= ~v;
if (!this._body.isAwake()) this._body.wakeUp();
}
/** mask */
@@ -140,14 +143,17 @@ export class CannonShape implements IBaseShape {
setMask (v: number): void {
this._body.collisionFilterMask = v;
if (!this._body.isAwake()) this._body.wakeUp();
}
addMask (v: number): void {
this._body.collisionFilterMask |= v;
if (!this._body.isAwake()) this._body.wakeUp();
}
removeMask (v: number): void {
this._body.collisionFilterMask &= ~v;
if (!this._body.isAwake()) this._body.wakeUp();
}
/**
@@ -185,8 +185,8 @@ export class ColliderComponent extends Eventify(Component) {
* @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`.
* @param target - The event callback target.
*/
public on (type: TriggerEventType | CollisionEventType, callback: Function, target?: Object): any {
super.on(type, callback, target);
public on (type: TriggerEventType | CollisionEventType, callback: Function, target?: Object, once?: boolean): any {
super.on(type, callback, target, once);
}
/**
+2 -2
View File
@@ -1,7 +1,6 @@
/**
* @category terrain
*/
import { builtinResMgr } from '../core/3d/builtin';
import { RenderableComponent } from '../core/3d/framework/renderable-component';
import { Texture2D } from '../core/assets';
@@ -10,6 +9,7 @@ import { Material } from '../core/assets/material';
import { RenderingSubMesh } from '../core/assets/mesh';
import { Component } from '../core/components';
import { ccclass, disallowMultiple, executeInEditMode, help, property } from '../core/data/class-decorator';
import { isValid } from '../core/data/object';
import { director } from '../core/director';
import { GFXBuffer } from '../core/gfx/buffer';
import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../core/gfx/define';
@@ -985,7 +985,7 @@ export class Terrain extends Component {
for (let i = 0; i < this._layers.length; ++i) {
const temp = this._layers[i];
if (temp != null && temp.detailMap != null) {
if (temp && temp.detailMap && isValid(temp.detailMap)) {
const layer = new TerrainLayerInfo();
layer.slot = i;
layer.tileSize = temp.tileSize;
+2 -2
View File
@@ -13,7 +13,7 @@ module.exports = {
CameraComponent: 'https://docs.cocos.com/creator3d/manual/en/editor/components/camera-component.html',
CanvasComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/canvas.html',
SkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/en/engine/animation/skeletal-animation.html',
BatchedSkinningModel: 'https://docs.cocos.com/creator3d/manual/en/engine/animation/skeletal-animation.html',
BatchedSkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/en/engine/animation/skeletal-animation.html',
DirectionalLightComponent: 'https://docs.cocos.com/creator3d/manual/en/concepts/scene/light/dir-light.html',
SphereLightComponent: 'https://docs.cocos.com/creator3d/manual/en/concepts/scene/light/sphere-light.html',
SpotLightComponent: 'https://docs.cocos.com/creator3d/manual/en/concepts/scene/light/spot-light.html',
@@ -34,7 +34,7 @@ module.exports = {
LabelOutlineComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/label-outline.html',
RichTextComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/richtext.html',
ScrollBarComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/scrollbar.html',
ScrollView: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/scrollview.html',
ScrollViewComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/scrollview.html',
SliderComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/slider.html',
ToggleContainerComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/toggleContainer.html',
ToggleComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/toggle.html',
+2 -2
View File
@@ -13,7 +13,7 @@ module.exports = {
CameraComponent: 'https://docs.cocos.com/creator3d/manual/zh/editor/components/camera-component.html',
CanvasComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/canvas.html',
SkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/zh/engine/animation/skeletal-animation.html',
BatchedSkinningModel: 'https://docs.cocos.com/creator3d/manual/zh/engine/animation/skeletal-animation.html',
BatchedSkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/zh/engine/animation/skeletal-animation.html',
DirectionalLightComponent: 'https://docs.cocos.com/creator3d/manual/zh/concepts/scene/light/dir-light.html',
SphereLightComponent: 'https://docs.cocos.com/creator3d/manual/zh/concepts/scene/light/sphere-light.html',
SpotLightComponent: 'https://docs.cocos.com/creator3d/manual/zh/concepts/scene/light/spot-light.html',
@@ -34,7 +34,7 @@ module.exports = {
LabelOutlineComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/label-outline.html',
RichTextComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/richtext.html',
ScrollBarComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/scrollbar.html',
ScrollView: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/scrollview.html',
ScrollViewComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/scrollview.html',
SliderComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/slider.html',
ToggleContainerComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/toggleContainer.html',
ToggleComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/toggle.html',
+3 -3
View File
@@ -2798,9 +2798,9 @@
}
},
"@cocos/cannon": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@cocos/cannon/-/cannon-1.1.0.tgz",
"integrity": "sha512-hdQsL7P7tugPP4y14cCW2ITNpmnrwjqT1nS+mCacfatQ+G5aA2kKPH55dimUjNsAkO5XdZQhM13f7GgF+Votog=="
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@cocos/cannon/-/cannon-1.1.1.tgz",
"integrity": "sha512-LkOCfgqD+jpypZ7U2/P+LCrG2z+OeiSG06HN9PX33HoTt216cmGkoFXhzezyBhtjsguXdFkeDl+Zc/eT5Qsezw=="
},
"@jest/console": {
"version": "24.9.0",
+1 -1
View File
@@ -53,6 +53,6 @@
},
"dependencies": {
"@cocos/ammo": "^1.0.6",
"@cocos/cannon": "^1.1.0"
"@cocos/cannon": "^1.1.1"
}
}
+97 -2
View File
@@ -1,5 +1,5 @@
import { AnimationClip, js, AnimationState, Node, Component, Vec3 } from '../../cocos/core';
import { ComponentPath } from '../../cocos/core/animation/animation';
import { AnimationClip, js, AnimationState, Node, Component, Vec3, AnimationManager } from '../../cocos/core';
import { ComponentPath, HierarchyPath } from '../../cocos/core/animation/animation';
import { ccclass } from '../../cocos/core/data/class-decorator';
test('Common target', () => {
@@ -65,3 +65,98 @@ test('Common target', () => {
expect(testComponent.c).toEqual(c);
}
});
test('Common targets that modify eulerAngles', () => {
const animationManager = new AnimationManager();
const mockInstance = jest.spyOn((global as any).cc.director, 'getAnimationManager').mockImplementation(() => {
return animationManager;
});
const partialNodeName = 'partial';
const clip = new AnimationClip('default');
clip.duration = 2.0;
const keys = [0, 0.1, 0.2];
const eulerValues = [new Vec3(), new Vec3(1), new Vec3(2)];
const eulerXValues = [0, 1, 2];
clip.keys = [keys];
clip.commonTargets = [{
modifiers: [new HierarchyPath(partialNodeName), 'eulerAngles'],
}];
clip.curves = [{
modifiers: ['eulerAngles'],
data: {keys: 0, values: eulerValues},
}, {
commonTarget: 0, // euler angles
modifiers: ['x'],
data: {keys: 0, values: eulerXValues},
}];
const state = new AnimationState(clip, clip.name);
state.weight = 1.0;
const node = new Node();
const partialNode = new Node(partialNodeName);
node.addChild(partialNode);
state.initialize(node);
animationManager.update(0);
state.play();
state.pause();
state.setTime(keys[1]);
state.update(0);
animationManager.update(0);
expect(node.eulerAngles).toEqual(eulerValues[1]);
expect(partialNode.eulerAngles.x).toEqual(eulerXValues[1]);
mockInstance.mockRestore();
});
test('animation state', () => {
const animationManager = new AnimationManager();
const mockInstance = jest.spyOn((global as any).cc.director, 'getAnimationManager').mockImplementation(() => {
return animationManager;
});
const clip = new AnimationClip('default');
clip.duration = 2.0;
const keys = [
0,
0.1,
0.2,
];
const values = [
new Vec3(),
new Vec3(1),
new Vec3(2),
];
clip.keys = [keys];
clip.curves = [{
modifiers: [
'position',
],
data: {
keys: 0,
values,
},
}];
const state = new AnimationState(clip, clip.name);
state.weight = 1.0;
const node = new Node();
state.initialize(node);
animationManager.update(0);
state.play();
state.pause();
state.setTime(keys[1]);
state.update(0);
animationManager.update(0);
expect(node.getPosition()).toEqual(values[1]);
mockInstance.mockRestore();
});
+3 -1
View File
@@ -1,7 +1,7 @@
import { Node, AnimationComponent, director, AnimationClip, math, AnimationState } from '../../cocos/core';
test('Animation events(general)', () => {
jest.spyOn((global as any).cc.director, 'getAnimationManager').mockImplementation(() => {
const mockInstance = jest.spyOn((global as any).cc.director, 'getAnimationManager').mockImplementation(() => {
return {
addAnimation: () => { },
removeAnimation: () => { },
@@ -100,6 +100,8 @@ test('Animation events(general)', () => {
testMagic.clear();
state.update(clip.duration / 2 + clip.duration / 4);
testMagic.expectAndClear(AnimationComponent.EventType.LASTFRAME);
mockInstance.mockRestore();
});
test('Animation event(last-frame event optimization)', () => {
+517
View File
@@ -0,0 +1,517 @@
import { CallbacksInvoker } from '../../cocos/core/event/callbacks-invoker';
import Event from '../../cocos/core/event/event';
import { Node } from '../../cocos/core/scene-graph/node';
import { Component } from '../../cocos/core/components/component';
import { CCObject } from '../../cocos/core/data/object';
test('test', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn();
let cb3 = jest.fn();
ci.on('a', cb1);
expect(ci.hasEventListener('a', function () {})).toBeFalsy();
expect(ci.hasEventListener('a', cb1)).toBeTruthy();
ci.on('a', cb2);
ci.on('b', cb3);
ci.on('nil', undefined);
ci.emit('a');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(1);
ci.emit('b');
expect(cb3.mock.calls.length).toBe(1);
ci.off('a', cb2);
ci.emit('a');
expect(cb1.mock.calls.length).toBe(2);
expect(cb2.mock.calls.length).toBe(1);
ci.on('a', cb2);
expect(ci.hasEventListener('a')).toBeTruthy();
ci.removeAll('a');
expect(ci.hasEventListener('a')).toBeFalsy();
ci.emit('a');
expect(cb1.mock.calls.length).toBe(2);
expect(cb2.mock.calls.length).toBe(1);
});
test('remove self during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn(function () {
ci.off('eve', cb1);
});
let cb2 = jest.fn();
ci.on('eve', cb1);
ci.on('eve', cb2);
ci.emit('eve');
expect(cb2.mock.calls.length).toBe(1);
ci.emit('eve');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(2);
});
test('remove self with target during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn(function () {
ci.off('eve', cb1, target);
});
let cb2 = jest.fn();
let target = {};
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.emit('eve');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(1);
ci.emit('eve');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(2);
});
test('remove previous during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn(function () {
ci.off('eve', cb1);
});
ci.on('eve', cb1);
ci.on('eve', cb2);
ci.emit('eve');
expect(ci.hasEventListener('eve', cb1)).toBeFalsy();
expect(ci.hasEventListener('eve', cb2)).toBeTruthy();
});
test('remove previous with target during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn(function () {
ci.off('eve', cb1, target);
});
let target = {};
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.emit('eve');
expect(ci.hasEventListener('eve', cb1, target)).toBeFalsy();
expect(ci.hasEventListener('eve', cb2, target)).toBeTruthy();
});
test('remove last during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn(function () {
ci.off('eve', cb2);
});
ci.on('eve', cb1);
ci.on('eve', cb2);
ci.emit('eve');
expect(ci.hasEventListener('eve', cb1)).toBeTruthy();
expect(ci.hasEventListener('eve', cb2)).toBeFalsy();
});
test('remove last with target during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn(function () {
ci.off('eve', cb2, target);
});
let target = {};
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.emit('eve');
expect(ci.hasEventListener('eve', cb1, target)).toBeTruthy();
expect(ci.hasEventListener('eve', cb2, target)).toBeFalsy();
});
test('remove multiple callbacks during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn(function () {
ci.off('eve', cb1);
ci.off('eve', cb3, target);
});
let cb3 = jest.fn(function () {
ci.off('eve', cb2, target);
});
let target = {};
ci.on('eve', cb1);
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.on('eve', cb3);
ci.on('eve', cb3, target);
ci.emit('eve');
expect(cb1.mock.calls.length).toBe(2);
expect(cb2.mock.calls.length).toBe(1);
expect(cb3.mock.calls.length).toBe(1);
expect(ci.hasEventListener('eve', cb1, target)).toBeTruthy();
expect(ci.hasEventListener('eve', cb1)).toBeFalsy();
expect(ci.hasEventListener('eve', cb2, target)).toBeFalsy();
expect(ci.hasEventListener('eve', cb3, target)).toBeFalsy();
});
test('remove all callbacks during invoking', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn(function () {
ci.removeAll('eve');
});
let cb3 = jest.fn(function () {
ci.off('eve', cb2, target);
});
let target = {};
ci.on('eve', cb1);
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.on('eve', cb3);
ci.on('eve', cb3, target);
ci.emit('eve');
expect(cb1.mock.calls.length).toBe(2);
expect(cb2.mock.calls.length).toBe(1);
expect(cb3.mock.calls.length).toBe(0);
expect(ci.hasEventListener('eve')).toBeFalsy();
});
test('remove and add again during invoking (node)', function () {
let target = new Object();
let node = new Node();
let cb1 = function () {
node.off('eve', cb1, target);
node.on('eve', cb1, target);
};
node.on('eve', cb1, target);
node.dispatchEvent(new Event('eve'));
expect(node.hasEventListener('eve', cb1, target)).toBeTruthy();
});
test('remove twice and add again during invoking (node)', function () {
let target = new Object();
let node = new Node();
let cb1 = function () {
node.off('eve', cb1, target);
node.off('eve', cb1, target);
node.on('eve', cb1, target);
};
node.on('eve', cb1, target);
node.dispatchEvent(new Event('eve'));
expect(node.hasEventListener('eve', cb1, target)).toBeTruthy();
});
test('remove and check has during invoking (node)', function () {
let target = new Object();
let node = new Node();
let cb1 = function () {
node.off('eve', cb1, target);
expect(node.hasEventListener('eve', cb1, target)).toBeFalsy();
};
node.on('eve', cb1, target);
node.dispatchEvent(new Event('eve'));
});
test('CallbacksInvoker support target', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn(function () {
if (this && this.name)
this.count++;
});
let cb2 = jest.fn();
let cb3 = jest.fn();
let target1 = {
name: 'CallbackTarget1',
count: 0
};
let target2 = {
name: 'CallbackTarget2',
count: 0
};
ci.on('a', cb1);
ci.on('a', cb1, target1);
ci.on('a', cb1);
ci.on('a', cb1, target2);
ci.on('a', cb2, target2);
ci.on('a', cb2, target1);
ci.on('a', cb3);
ci.on('a', cb3, target1);
ci.on('b', cb1, target1);
expect(ci.hasEventListener('a', cb2)).toBeFalsy();
expect(ci.hasEventListener('a', cb2, target1)).toBeTruthy();
expect(ci.hasEventListener('a', cb3)).toBeTruthy();
ci.emit('a');
expect(cb1.mock.calls.length).toBe(3);
expect(target1.count).toBe(1);
expect(target2.count).toBe(1);
expect(cb2.mock.calls.length).toBe(2);
expect(cb3.mock.calls.length).toBe(2);
expect(ci.hasEventListener('a', cb1.bind(target1))).toBeFalsy();
ci.off('b', cb1);
ci.off('b', cb1, target2);
expect(ci.hasEventListener('b', cb1, target1)).toBeTruthy();
ci.off('b', cb1, target1);
expect(ci.hasEventListener('b', cb1, target1)).toBeFalsy();
cb1.mockClear();
target1.count = 0;
target2.count = 0;
cb2.mockClear();
cb3.mockClear();
ci.off('a', cb1, target2);
ci.off('a', cb1, target1);
ci.off('a', cb2, target2);
ci.off('a', cb3, target2);
ci.emit('a');
expect(target1.count).toBe(0);
expect(target2.count).toBe(0);
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(1);
expect(cb3.mock.calls.length).toBe(2);
});
test('CallbacksInvoker remove target', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn();
let cb2 = jest.fn();
let cb3 = jest.fn();
let target1 = {
name: 'CallbackTarget1',
count: 0
};
let target2 = {
name: 'CallbackTarget2',
count: 0
};
ci.on('a', cb1);
ci.on('a', cb1, target1);
ci.on('a', cb1);
ci.on('a', cb1, target2);
ci.on('a', cb2, target2);
ci.on('a', cb2, target1);
ci.on('a', cb3);
ci.on('a', cb3, target1);
ci.emit('a');
expect(cb1.mock.calls.length).toBe(3);
expect(cb2.mock.calls.length).toBe(2);
expect(cb3.mock.calls.length).toBe(2);
ci.removeAll(target1);
cb1.mockClear();
cb2.mockClear();
cb3.mockClear();
ci.emit('a');
expect(cb1.mock.calls.length).toBe(2);
expect(cb2.mock.calls.length).toBe(1);
expect(cb3.mock.calls.length).toBe(1);
ci.removeAll(target2);
cb1.mockClear();
cb2.mockClear();
cb3.mockClear();
ci.emit('a');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(0);
expect(cb3.mock.calls.length).toBe(1);
});
test('event type conflict with object prototype', function () {
let ci = new CallbacksInvoker();
let cb1 = jest.fn(function () {
ci.off('toString', cb1);
});
let cb2 = jest.fn();
ci.on('toString', cb1);
ci.on('toString', cb2);
ci.emit('toString');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(1);
ci.emit('toString');
expect(cb1.mock.calls.length).toBe(1);
expect(cb2.mock.calls.length).toBe(2);
});
test('nest invoke', function () {
let ci = new CallbacksInvoker();
let actualSequence = [];
let isParentLoop = true;
let cb1 = function () {
actualSequence.push(cb1);
if (isParentLoop) {
isParentLoop = false;
ci.emit('visit');
}
};
let cb2 = function () {
actualSequence.push(cb2);
};
ci.on('visit', cb1);
ci.on('visit', cb2);
ci.emit('visit');
expect(actualSequence).toEqual([cb1, cb1, cb2, cb2]);
});
test('remove during nest invoke', function () {
let ci = new CallbacksInvoker();
let actualSequence = [];
let isParentLoop = true;
let cb1 = function () {
actualSequence.push(cb1);
if (isParentLoop) {
isParentLoop = false;
ci.emit('visit');
}
else {
ci.off('visit', cb1);
expect(ci.hasEventListener('visit')).toBeFalsy();
}
};
ci.on('visit', cb1);
ci.emit('visit');
expect(actualSequence).toEqual([cb1, cb1]);
});
test('remove many during nest invoke', function () {
let ci = new CallbacksInvoker();
let actualSequence = [];
let isParentLoop = true;
let cb1 = function () {
actualSequence.push(cb1);
};
let cb2 = function () {
actualSequence.push(cb2);
if (isParentLoop) {
isParentLoop = false;
ci.emit('visit');
}
else {
ci.off('visit', cb1);
ci.off('visit', cb2);
}
};
let cb3 = function () {
actualSequence.push(cb3);
};
ci.on('visit', cb1);
ci.on('visit', cb2);
ci.on('visit', cb3);
ci.emit('visit');
expect(actualSequence).toEqual([cb1, cb2, cb1, cb2, cb3, cb3]);
});
test('Destroyed node should no longer be invoked as target', () => {
let ci = new CallbacksInvoker();
let node = new Node();
let cb1 = jest.fn(() => {
node.setPosition(100, 0, 0);
});
ci.on('test', cb1, node);
expect(ci.hasEventListener('test', cb1, node)).toBeTruthy();
ci.emit('test');
expect(node.position.x).toBe(100);
expect(cb1.mock.calls.length).toBe(1);
node.destroy();
expect(ci.hasEventListener('test', cb1, node)).toBeFalsy();
ci.emit('test');
expect(cb1.mock.calls.length).toBe(1);
node = new Node();
let cb2 = jest.fn(() => {
node.destroy();
});
ci.on('test', cb2, node);
expect(ci.hasEventListener('test', cb2, node)).toBeTruthy();
ci.emit('test');
expect(cb1.mock.calls.length).toBe(1);
ci.emit('test');
expect(cb1.mock.calls.length).toBe(1);
expect(ci.hasEventListener('test', cb2, node)).toBeFalsy();
});
test('Destroyed component should no longer be invoked as target', () => {
let ci = new CallbacksInvoker();
let node = new Node();
let comp = node.addComponent(Component);
let cb1 = jest.fn(function () {
this.node.setPosition(100, 0, 0);
});
ci.on('test', cb1, comp);
expect(ci.hasEventListener('test', cb1, comp)).toBeTruthy();
ci.emit('test');
expect(node.position.x).toBe(100);
expect(cb1.mock.calls.length).toBe(1);
comp.destroy();
expect(ci.hasEventListener('test', cb1, comp)).toBeFalsy();
ci.emit('test');
expect(cb1.mock.calls.length).toBe(1);
node = new Node();
comp = node.addComponent(Component);
let cb2 = jest.fn(() => {
node.destroy();
// Force destroy node with the component
CCObject._deferredDestroy();
});
ci.on('test', cb2, comp);
expect(ci.hasEventListener('test', cb2, comp)).toBeTruthy();
ci.emit('test');
expect(cb1.mock.calls.length).toBe(1);
ci.emit('test');
expect(cb1.mock.calls.length).toBe(1);
});
+20
View File
@@ -35,4 +35,24 @@ test('Eventify', () => {
derived.once(eventName, eventCallback);
derived.emit(eventName);
expect(hookOnOff).toBeCalledTimes(2);
});
test('Overwrite Eventify.prototype.on', () => {
class Base {}
class Derived extends Eventify(Base) {
public on <TFunction extends Function> (type: string, callback: TFunction, thisArg?: any, once?: boolean) {
return super.on(type, callback, thisArg, once);
}
}
const derived = new Derived();
const eventName = 'event';
const onceFn = jest.fn(() => {});
derived.once(eventName, onceFn);
derived.emit(eventName);
expect(onceFn).toBeCalledTimes(1);
derived.emit(eventName);
expect(onceFn).toBeCalledTimes(1);
});
-451
View File
@@ -1,451 +0,0 @@
largeModule('CallbacksInvoker');
test('test', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback();
var cb2 = Callback();
var cb3 = Callback();
ci.on('a', cb1);
strictEqual(ci.hasEventListener('a', function () {}), false, '`has` should return false if the callback not exists');
strictEqual(ci.hasEventListener('a', cb1), true, '`has` should return true if the callback exists');
ci.on('a', cb2);
ci.on('b', cb3);
ci.on('nil', undefined);
cb1.enable();
cb2.enable();
ci.emit('a');
cb1.once('1 should be called');
cb2.once('2 should be called');
cb3.enable();
ci.emit('b');
cb3.once('3 should be called');
ci.off('a', cb2);
cb2.setDisabledMessage('callback should not be emitted after removed');
cb1.enable();
ci.emit('a');
cb1.once('callback should still be emitted if not excatly the one being removed');
ci.on('a', cb2);
strictEqual(ci.hasEventListener('a'), true, '`has` should return true if has any callback');
ci.removeAll('a');
strictEqual(ci.hasEventListener('a'), false, '`has` should return false if all callbacks removed');
cb1.setDisabledMessage('should not be called after all removed');
cb2.setDisabledMessage('should not be called after all removed');
ci.emit('a');
});
test('remove self during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback(function () {
ci.off('eve', cb1);
}).enable();
var cb2 = Callback().enable();
ci.on('eve', cb1);
ci.on('eve', cb2);
ci.emit('eve');
cb2.once('it should be called correctly if previous callback deregistered itself');
cb1.disable('should not call after removed');
ci.emit('eve');
});
test('remove self with target during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback(function () {
ci.off('eve', cb1, target);
}).enable();
var cb2 = Callback().enable();
var target = {};
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.emit('eve');
cb2.once('it should be called correctly if previous callback deregistered itself');
cb1.disable('should not call after removed');
ci.emit('eve');
});
test('remove previous during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback().enable();
var cb2 = Callback(function () {
ci.off('eve', cb1);
}).enable();
ci.on('eve', cb1);
ci.on('eve', cb2);
ci.emit('eve');
strictEqual(ci.hasEventListener('eve', cb1), false, 'previous callback should be removed');
strictEqual(ci.hasEventListener('eve', cb2), true, 'self callback should not be removed');
});
test('remove previous with target during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback().enable();
var cb2 = Callback(function () {
ci.off('eve', cb1, target);
}).enable();
var target = {};
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.emit('eve');
strictEqual(ci.hasEventListener('eve', cb1, target), false, 'previous callback should be removed');
strictEqual(ci.hasEventListener('eve', cb2, target), true, 'self callback should not be removed');
});
test('remove last during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback().enable();
var cb2 = Callback(function () {
ci.off('eve', cb2);
}).enable();
ci.on('eve', cb1);
ci.on('eve', cb2);
ci.emit('eve');
strictEqual(ci.hasEventListener('eve', cb1), true, 'previous callback should not be removed');
strictEqual(ci.hasEventListener('eve', cb2), false, 'self callback should be removed');
});
test('remove last with target during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback().enable();
var cb2 = Callback(function () {
ci.off('eve', cb2, target);
}).enable();
var target = {};
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.emit('eve');
strictEqual(ci.hasEventListener('eve', cb1, target), true, 'previous callback should not be removed');
strictEqual(ci.hasEventListener('eve', cb2, target), false, 'self callback should be removed');
});
test('remove multiple callbacks during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback().enable();
var cb2 = Callback(function () {
ci.off('eve', cb1);
ci.off('eve', cb3, target);
}).enable();
var cb3 = Callback(function () {
ci.off('eve', cb2, target);
}).enable();
var target = {};
ci.on('eve', cb1);
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.on('eve', cb3);
ci.on('eve', cb3, target);
ci.emit('eve');
cb1.expect(2, 'first callback should be invoked twice');
cb2.expect(1, 'second callback should be invoked once');
cb3.expect(1, 'third callback should be invoked once');
strictEqual(ci.hasEventListener('eve', cb1, target), true, 'first callback with target should not be removed');
strictEqual(ci.hasEventListener('eve', cb1), false, 'first callback should be removed');
strictEqual(ci.hasEventListener('eve', cb2, target), false, 'second callback with target should be removed');
strictEqual(ci.hasEventListener('eve', cb3, target), false, 'third callback with target should be removed');
});
test('remove all callbacks during invoking', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback().enable();
var cb2 = Callback(function () {
ci.removeAll('eve');
}).enable();
var cb3 = Callback(function () {
ci.off('eve', cb2, target);
}).enable();
var target = {};
ci.on('eve', cb1);
ci.on('eve', cb1, target);
ci.on('eve', cb2, target);
ci.on('eve', cb3);
ci.on('eve', cb3, target);
ci.emit('eve');
cb1.expect(2, 'first callback should be invoked twice');
cb2.expect(1, 'second callback should be invoked once');
cb3.expect(0, 'third callback should never invoked');
strictEqual(ci.hasEventListener('eve'), false, 'All callbacks should be removed');
});
test('remove and add again during invoking', function () {
var target = new Object();
var ci = new cc._Test.EventListeners();
var cb1 = function () {
ci.off('eve', cb1, target);
ci.on('eve', cb1, target);
};
ci.on('eve', cb1, target);
ci.emit(new cc.Event.EventCustom('eve'));
strictEqual(ci.hasEventListener('eve', cb1, target), true, 'first callback should be added back');
});
test('remove twice and add again during invoking', function () {
var target = new Object();
var ci = new cc._Test.EventListeners();
var cb1 = function () {
ci.off('eve', cb1, target);
ci.off('eve', cb1, target);
ci.on('eve', cb1, target);
};
ci.on('eve', cb1, target);
ci.emit(new cc.Event.EventCustom('eve'));
strictEqual(ci.hasEventListener('eve', cb1, target), true, 'first callback should be added back');
});
test('remove and check has during invoking', function () {
var target = new Object();
var ci = new cc._Test.EventListeners();
var cb1 = function () {
ci.off('eve', cb1, target);
strictEqual(ci.hasEventListener('eve', cb1, target), false, 'first callback should be removed');
};
ci.on('eve', cb1, target);
ci.emit(new cc.Event.EventCustom('eve'));
});
test('CallbacksInvoker support target', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = function () {
cb1.count++;
if (this.name)
this.count++;
};
cb1.count = 0;
var cb2 = Callback();
var cb3 = Callback();
var target1 = {
name: 'CallbackTarget1',
count: 0
};
var target2 = {
name: 'CallbackTarget2',
count: 0
};
ci.on('a', cb1);
ci.on('a', cb1, target1);
ci.on('a', cb1);
ci.on('a', cb1, target2);
ci.on('a', cb1, target2);
ci.on('a', cb2, target2);
ci.on('a', cb2, target1);
ci.on('a', cb3);
ci.on('a', cb3, target1);
ci.on('b', cb1, target1);
strictEqual(ci.hasEventListener('a', cb2), false, '`has` should return false if the callback without target not exists');
strictEqual(ci.hasEventListener('a', cb2, target1), true, '`has` should return true if the callback with correct target exists');
strictEqual(ci.hasEventListener('a', cb3), true, '`has` should return true if the callback without target exists');
cb2.enable();
cb3.enable();
ci.emit('a');
strictEqual(cb1.count, 5, 'callback1 should be invoked five times');
strictEqual(target1.count, 1, 'callback1 should be invoked one time with target1');
strictEqual(target2.count, 2, 'callback2 should be invoked two times with target2');
cb2.expect(2, 'callback2 should be called twice');
cb3.expect(2, 'callback3 should be called twice');
strictEqual(ci.hasEventListener('a', target1), false, '`has` should return false if the target is given');
ci.off('b', cb1);
ci.off('b', cb1, target2);
strictEqual(ci.hasEventListener('b', cb1, target1), true, 'remove callback without the correct target should fail');
ci.off('b', cb1, target1);
strictEqual(ci.hasEventListener('b', cb1, target1), false, 'remove callback with the correct callback and target should succeed');
cb1.count = 0;
target1.count = 0;
target2.count = 0;
cb2.calledCount = 0;
cb3.calledCount = 0;
ci.off('a', cb1, target2);
ci.off('a', cb1, target1);
ci.off('a', cb2, target2);
ci.off('a', cb3, target2);
ci.emit('a');
strictEqual(target1.count, 0, 'callback1 with target1 should not be invoked after remove');
strictEqual(target2.count, 1, 'callback1 with target2 should be invoked only once after remove one');
strictEqual(cb1.count, 3, 'callback1 should be invoked three times after removed two');
cb2.expect(1, 'callback2 should be called once');
cb3.expect(2, 'callback3 should be called twice');
});
test('CallbacksInvoker remove target', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback();
var cb2 = Callback();
var cb3 = Callback();
var target1 = {
name: 'CallbackTarget1',
count: 0
};
var target2 = {
name: 'CallbackTarget2',
count: 0
};
ci.on('a', cb1);
ci.on('a', cb1, target1);
ci.on('a', cb1);
ci.on('a', cb1, target2);
ci.on('a', cb1, target2);
ci.on('a', cb2, target2);
ci.on('a', cb2, target1);
ci.on('a', cb3);
ci.on('a', cb3, target1);
cb1.enable();
cb2.enable();
cb3.enable();
ci.emit('a');
cb1.expect(5, 'callback1 should be called five times');
cb2.expect(2, 'callback2 should be called twice');
cb3.expect(2, 'callback3 should be called twice');
ci.removeAll(target1);
cb1.calledCount = 0;
cb2.calledCount = 0;
cb3.calledCount = 0;
ci.emit('a');
cb1.expect(4, 'removed one, callback1 should be called four times');
cb2.expect(1, 'removed one, callback2 should be called once');
cb3.expect(1, 'removed one, callback3 should be called once');
ci.removeAll(target2);
cb1.calledCount = 0;
cb2.calledCount = 0;
cb3.calledCount = 0;
ci.emit('a');
cb1.expect(2, 'removed two, callback1 should be called twice');
cb2.expect(0, 'removed one, callback2 should not be called');
cb3.expect(1, 'callback3 should be called once');
});
test('event type conflict with object prototype', function () {
var ci = new cc._Test.CallbacksInvoker();
var cb1 = Callback(function () {
ci.off('toString', cb1);
}).enable();
var cb2 = Callback().enable();
ci.on('toString', cb1);
ci.on('toString', cb2);
ci.emit('toString');
cb2.once('it should be called correctly if previous callback deregistered itself');
cb1.disable('should not call after removed');
ci.emit('toString');
});
test('nest invoke', function () {
var ci = new cc._Test.CallbacksInvoker();
var actualSequence = [];
var isParentLoop = true;
var cb1 = function () {
actualSequence.push(cb1);
if (isParentLoop) {
isParentLoop = false;
ci.emit('visit');
}
};
var cb2 = function () {
actualSequence.push(cb2);
};
ci.on('visit', cb1);
ci.on('visit', cb2);
ci.emit('visit');
deepEqual(actualSequence, [cb1, cb1, cb2, cb2], 'support nest invoke');
});
test('remove during nest invoke', function () {
var ci = new cc._Test.CallbacksInvoker();
var actualSequence = [];
var isParentLoop = true;
var cb1 = function () {
actualSequence.push(cb1);
if (isParentLoop) {
isParentLoop = false;
ci.emit('visit');
}
else {
ci.off('visit', cb1);
strictEqual(ci.hasEventListener('visit'), false, 'all callbacks removed');
}
};
ci.on('visit', cb1);
ci.emit('visit');
deepEqual(actualSequence, [cb1, cb1], 'invoke sequence');
});
test('remove many during nest invoke', function () {
var ci = new cc._Test.CallbacksInvoker();
var actualSequence = [];
var isParentLoop = true;
var cb1 = function () {
actualSequence.push(cb1);
};
var cb2 = function () {
actualSequence.push(cb2);
if (isParentLoop) {
isParentLoop = false;
ci.emit('visit');
}
else {
ci.off('visit', cb1);
ci.off('visit', cb2);
}
};
var cb3 = function () {
actualSequence.push(cb3);
};
ci.on('visit', cb1);
ci.on('visit', cb2);
ci.on('visit', cb3);
ci.emit('visit');
deepEqual(actualSequence, [cb1, cb2, cb1, cb2, cb3, cb3], 'invoke sequence');
});