From 8c017485872d52b364635e95fe8c9c0b99c25586 Mon Sep 17 00:00:00 2001 From: zxg0622 <247274249@qq.com> Date: Wed, 6 Mar 2019 09:14:20 +0800 Subject: [PATCH 1/4] fix particle burst bug (#3965) --- cocos/3d/framework/particle/burst.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/3d/framework/particle/burst.ts b/cocos/3d/framework/particle/burst.ts index 9460be9fba..e0cf1a9198 100644 --- a/cocos/3d/framework/particle/burst.ts +++ b/cocos/3d/framework/particle/burst.ts @@ -55,7 +55,7 @@ export default class Burst { } public update (psys, dt: number) { - if (psys.loop && this._remainingCount === 0) { + if (this._remainingCount === 0) { this._remainingCount = this._repeatCount; this._curTime = this._time; } From b6483dc2509f84259f36e3722cc7a096c676786e Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 6 Mar 2019 09:14:53 +0800 Subject: [PATCH 2/4] default effect (#3968) --- cocos/3d/assets/material.ts | 5 +++-- cocos/3d/assets/texture-cube.ts | 5 +++-- .../framework/particle/animator/texture-animation.ts | 2 +- cocos/3d/framework/particle/emitter/shape-module.ts | 2 +- cocos/3d/framework/particle/particle.ts | 2 +- .../particle/renderer/particle-system-renderer.ts | 1 - cocos/renderer/scene/render-scene.ts | 3 +-- cocos/renderer/scene/skybox.ts | 10 +++++++--- cocos/scene-graph/scene-globals.ts | 3 ++- cocos/scene-graph/scene.ts | 4 ++-- 10 files changed, 21 insertions(+), 16 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 8b6f7f6f8b..91173e50ab 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -29,6 +29,7 @@ import { GFXBindingType } from '../../gfx/define'; import { GFXTextureView } from '../../gfx/texture-view'; import { Effect, IDefineMap } from '../../renderer/core/effect'; import { Pass, PassOverrides } from '../../renderer/core/pass'; +import { builtinResMgr } from '../builtin'; import { RenderableComponent } from '../framework/renderable-component'; import { EffectAsset } from './effect-asset'; @@ -198,9 +199,9 @@ export class Material extends Asset { protected _update (asset: EffectAsset | null = this._effectAsset, keepProps: boolean = true) { // get effect asset this._effectAsset = asset; - if (!this._effectAsset) { return; } + asset = asset || builtinResMgr.get('default-material').effectAsset!; // create passes - this._passes = Effect.parseEffect(this._effectAsset, { + this._passes = Effect.parseEffect(asset, { techIdx: this._techIdx, defines: this._defines, }); diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 7a0d0767cb..2d10261ad1 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -80,8 +80,9 @@ export class TextureCube extends TextureBase { } /** - * @param textures - * @deprecated Manually assign to mipmaps property instead. + * convenient util for cubemap creation (even with custom mipmaps) + * @param texture - texture asset array containing six faces in a row + * @param out - the resulting texture cube asset */ public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) { const mipmaps: ITextureCubeMipmap[] = []; diff --git a/cocos/3d/framework/particle/animator/texture-animation.ts b/cocos/3d/framework/particle/animator/texture-animation.ts index 77a0c034dc..36ca742e5e 100644 --- a/cocos/3d/framework/particle/animator/texture-animation.ts +++ b/cocos/3d/framework/particle/animator/texture-animation.ts @@ -3,7 +3,7 @@ import { Enum } from "../../../../core/value-types"; import CurveRange from "./curve-range"; import { CCClass } from "../../../../core/data"; import { property, ccclass } from "../../../../core/data/class-decorator"; -import ParticleSystemComponent from "../particle-system-component"; +import { ParticleSystemComponent } from "../particle-system-component"; import Particle from "../particle"; // tslint:disable: max-line-length diff --git a/cocos/3d/framework/particle/emitter/shape-module.ts b/cocos/3d/framework/particle/emitter/shape-module.ts index ef145999a0..21ed1e1bfc 100644 --- a/cocos/3d/framework/particle/emitter/shape-module.ts +++ b/cocos/3d/framework/particle/emitter/shape-module.ts @@ -4,7 +4,7 @@ import { Enum, Vec3 } from '../../../../core/value-types'; import CurveRange from '../animator/curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; -import ParticleSystemComponent from '../particle-system-component'; +import { ParticleSystemComponent } from '../particle-system-component'; // tslint:disable: max-line-length const _intermediVec = vec3.create(0, 0, 0); diff --git a/cocos/3d/framework/particle/particle.ts b/cocos/3d/framework/particle/particle.ts index 291ee35ea9..a9ef803f23 100644 --- a/cocos/3d/framework/particle/particle.ts +++ b/cocos/3d/framework/particle/particle.ts @@ -1,6 +1,6 @@ import { vec3, color4 } from '../../../core/vmath'; import { Color } from '../../../core/value-types'; -import ParticleSystemComponent from './particle-system-component'; +import { ParticleSystemComponent } from './particle-system-component'; export default class Particle { public particleSystem: ParticleSystemComponent; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 97d59e3e9b..4333d7c8a5 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -4,7 +4,6 @@ import { mat4, vec2, vec3, vec4 } from '../../../../core/vmath'; import { GFXAttributeName, GFXFormat } from '../../../../gfx/define'; import { IGFXInputAttribute } from '../../../../gfx/input-assembler'; import * as renderer from '../../../../renderer'; -import gfx from '../../../../renderer/gfx'; import ParticleBatchModel from '../../../../renderer/models/particle-batch-model'; import { Material } from '../../../assets/material'; import RecyclePool from '../../../memop/recycle-pool'; diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index b9a5feefbe..58a825ad31 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -93,8 +93,7 @@ export class RenderScene { constructor (root: Root) { this._root = root; this._ambient = new Ambient (this); - this._mainLight = new DirectionalLight(this, 'Main Light'); - this._mainLight.node = new Node('Main Light'); + this._mainLight = new DirectionalLight(this, 'Main Light', new Node('Main Light')); this._skybox = new Skybox(this); } diff --git a/cocos/renderer/scene/skybox.ts b/cocos/renderer/scene/skybox.ts index f1c24cb6a7..87da09c4da 100644 --- a/cocos/renderer/scene/skybox.ts +++ b/cocos/renderer/scene/skybox.ts @@ -11,9 +11,7 @@ export class Skybox extends Model { set cubemap (val: TextureCube | null) { this._cubemap = val || this._default; this._material.setProperty('cubeMap', this._cubemap); - for (const pso of this._matPSORecord.get(this._material)!) { - pso.pipelineLayout.layouts[0].update(); - } + this._updateBindingLayout(); } get cubemap () { return this._cubemap; @@ -25,6 +23,7 @@ export class Skybox extends Model { this._material.destroy(); this._material.initialize({ defines: { USE_RGBE_CUBEMAP: val } }); this.setSubModelMaterial(0, this._material); + this._updateBindingLayout(); } get isRGBE () { return this._isRGBE; @@ -50,5 +49,10 @@ export class Skybox extends Model { const mesh = createMesh(box({ width: 2, height: 2, length: 2 })); const subMeshData = mesh.renderingMesh!.getSubmesh(0)!; this.initSubModel(0, subMeshData, this._material); + this._updateBindingLayout(); + } + + protected _updateBindingLayout () { + this._matPSORecord.get(this._material)![0].pipelineLayout.layouts[0].update(); } } diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index bb7ce56b3b..d0adc9212e 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -118,8 +118,9 @@ export class SkyboxInfo { set renderScene (val: RenderScene) { this._resource = val.skybox; - this.cubemap = this._cubemap; this.isRGBE = this._isRGBE; + this.cubemap = this._cubemap; + this.enabled = this._enabled; } } cc.SkyboxInfo = SkyboxInfo; diff --git a/cocos/scene-graph/scene.ts b/cocos/scene-graph/scene.ts index ba334503eb..058a19a98f 100644 --- a/cocos/scene-graph/scene.ts +++ b/cocos/scene-graph/scene.ts @@ -64,8 +64,7 @@ export class Scene extends Node { super(name); this._activeInHierarchy = false; if (cc.director && cc.director.root) { - const rs = this._renderScene = cc.director.root.createScene({}); - this._globals.renderScene = rs; + this._renderScene = cc.director.root.createScene({}); } } @@ -95,6 +94,7 @@ export class Scene extends Node { this._inited = true; } this.walk(BaseNode._setScene); + this._globals.renderScene = this._renderScene!; } protected _activate (active: boolean) { From ed93473d677bb3f9f35c02be5320ae98d7b2f521 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Wed, 6 Mar 2019 09:15:22 +0800 Subject: [PATCH 3/4] fix error (#3969) * fix error * repair overridePipelineState bug per Fram --- cocos/3d/ui/assembler/mask/stencil-manager.ts | 154 ++--- cocos/3d/ui/components/label-component.ts | 4 +- cocos/3d/ui/components/sprite-component.ts | 4 +- cocos/3d/ui/components/ui-render-component.ts | 22 +- .../ui/components/ui-transfrom-component.ts | 29 +- cocos/3d/ui/components/widget-manager.ts | 8 +- cocos/assets/CCSpriteFrame.ts | 58 +- cocos/components/component.d.ts | 2 + cocos/components/component.js | 6 +- .../platform/event-manager/CCEventListener.ts | 8 + cocos/gfx/define.ts | 4 + cocos/renderer/ui/ui.ts | 1 + cocos/scene-graph/node-event-processor.ts | 631 ++++++++++-------- cocos/scene-graph/node.ts | 14 - 14 files changed, 493 insertions(+), 452 deletions(-) diff --git a/cocos/3d/ui/assembler/mask/stencil-manager.ts b/cocos/3d/ui/assembler/mask/stencil-manager.ts index fff2199af7..20a288e673 100644 --- a/cocos/3d/ui/assembler/mask/stencil-manager.ts +++ b/cocos/3d/ui/assembler/mask/stencil-manager.ts @@ -1,6 +1,8 @@ import { GFXComparisonFunc, GFXStencilOp } from '../../../../gfx/define'; import { Material } from '../../../assets/material'; import { MaskComponent } from '../../components/mask-component'; +import { Pass, Effect } from '../../../../renderer'; +import { IPassInfo } from '../../../assets/effect-asset'; // import { GFXStencilOp } from '../../../../gfx/define'; // import { MaskComponent } from '../../components/mask-component'; @@ -65,29 +67,6 @@ function updateDynamicStencilStates (material: Material, state: IStencilStateUpd } -function overrideStencilState (material: Material, state: IStencilState) { - material.overridePipelineStates({ - depthStencilState: { - stencilTestFront: state.stencilTest, - stencilFuncFront: state.func, - stencilReadMaskFront: state.stencilMask, - stencilWriteMaskFront: state.writeMask, - stencilFailOpFront: state.failOp, - stencilZFailOpFront: state.zFailOp, - stencilPassOpFront: state.passOp, - stencilRefFront: state.ref, - stencilTestBack: state.stencilTest, - stencilFuncBack: state.func, - stencilReadMaskBack: state.stencilMask, - stencilWriteMaskBack: state.writeMask, - stencilFailOpBack: state.failOp, - stencilZFailOpBack: state.zFailOp, - stencilPassOpBack: state.passOp, - stencilRefBack: state.ref, - }, - }); -} - export class StencilManager { public static sharedManager: StencilManager | null = null; public stage = Stage.DISABLED; @@ -134,58 +113,52 @@ export class StencilManager { } public handleMaterial (mat: Material){ + const pattern = this._stencilPattern; if (this.stage === Stage.DISABLED) { + pattern.stencilTest = false; + } else { + pattern.stencilTest = true; + if (this.stage === Stage.ENABLED) { + pattern.func = GFXComparisonFunc.EQUAL; + pattern.failOp = GFXStencilOp.KEEP; + pattern.stencilMask = pattern.ref = this.getStencilRef(); + pattern.writeMask = this.getWriteMask(); + } else if (this.stage === Stage.CLEAR) { + pattern.func = GFXComparisonFunc.NEVER; + pattern.failOp = GFXStencilOp.ZERO; + pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask(); + } else if (this.stage === Stage.ENTER_LEVEL) { + pattern.func = GFXComparisonFunc.NEVER; + pattern.failOp = GFXStencilOp.REPLACE; + pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask(); + } + } - } else if (this.stage === Stage.ENABLED) { - this.updateMaskTargetMaterial(mat); - } else if (this.stage === Stage.CLEAR) { - this.updateClearMaskMaterial(mat); - } else if (this.stage === Stage.ENTER_LEVEL){ - this.updateMaskMaterial(mat); + const state = this._stencilPattern; + if (this._changed(mat.passes[0])){ + mat.overridePipelineStates({ + depthStencilState: { + stencilTestFront: state.stencilTest, + stencilFuncFront: state.func, + stencilReadMaskFront: state.stencilMask, + stencilWriteMaskFront: state.writeMask, + stencilFailOpFront: state.failOp, + stencilZFailOpFront: state.zFailOp, + stencilPassOpFront: state.passOp, + stencilRefFront: state.ref, + stencilTestBack: state.stencilTest, + stencilFuncBack: state.func, + stencilReadMaskBack: state.stencilMask, + stencilWriteMaskBack: state.writeMask, + stencilFailOpBack: state.failOp, + stencilZFailOpBack: state.zFailOp, + stencilPassOpBack: state.passOp, + stencilRefBack: state.ref, + }, + }); } } - public updateMaskMaterial (material: Material) { - const pattern = this._stencilPattern; - pattern.func = GFXComparisonFunc.NEVER; - pattern.failOp = GFXStencilOp.REPLACE; - pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask(); - overrideStencilState(material, pattern); - } - - public updateClearMaskMaterial (material: Material) { - const pattern = this._stencilPattern; - pattern.func = GFXComparisonFunc.NEVER; - pattern.failOp = GFXStencilOp.ZERO; - pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask(); - overrideStencilState(material, pattern); - } - - public updateMaskTargetMaterial (material: Material) { - const pattern = this._stencilPattern; - pattern.func = GFXComparisonFunc.EQUAL; - pattern.failOp = GFXStencilOp.KEEP; - pattern.stencilMask = pattern.ref = this.getStencilRef(); - pattern.writeMask = this.getWriteMask(); - overrideStencilState(material, pattern); - } - - // public updateMaskMaterial (material: Material) { - // updateDynamicStencilStates (material, { - // func: GFXComparisonFunc.ALWAYS, - // writeMask: this._protectAncestorMasks(), - // ref: this._getWriteMaskForTopMask(), - // }); - // } - - // public updateClearMaskMaterial (material: Material) { - // updateDynamicStencilStates(material, { - // func: GFXComparisonFunc.NEVER, - // writeMask: this._protectAncestorMasks(), - // ref: 0, - // }); - // } - public getWriteMask () { return 0x00000001 << (this._maskStack.length - 1); } @@ -202,21 +175,36 @@ export class StencilManager { return result; } - // private _readAncestorMasks (): number { - // let result = 0; - // this._maskStack.forEach((mask, iBit) => { - // result |= (1 << iBit); - // }); - // return result; - // } + public getInvertedRef () { + let result = 0; + for (let i = 0; i < this._maskStack.length - 1; ++i) { + result += (0x01 << i); + } + return result; + } - // private _protectAncestorMasks (): number { - // return ~this._readAncestorMasks(); - // } + public reset () { + // reset stack and stage + this._maskStack.length = 0; + this.stage = Stage.DISABLED; + } - // private _getWriteMaskForTopMask (): number { - // return 1 << this._maskStack.length; - // } + private _changed (pass: Pass) { + const stencilState = pass.depthStencilState; + const pattern = this._stencilPattern; + if (pattern.stencilTest !== stencilState.stencilTestFront || + pattern.func !== stencilState.stencilFuncFront || + pattern.failOp !== stencilState.stencilFailOpFront || + pattern.zFailOp !== stencilState.stencilZFailOpFront || + pattern.passOp !== stencilState.stencilPassOpFront || + pattern.stencilMask !== stencilState.stencilReadMaskFront || + pattern.writeMask !== stencilState.stencilWriteMaskFront || + pattern.ref !== stencilState.stencilRefFront) { + return true; + } + + return false; + } } StencilManager.sharedManager = new StencilManager(); diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index ae4a3463a5..28f9e774c9 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -31,10 +31,10 @@ import { ImageAsset } from '../../../assets/image-asset'; import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import macro from '../../../core/platform/CCMacro'; import { ccenum } from '../../../core/value-types/enum'; +import { UI } from '../../../renderer/ui/ui'; import { FontAtlas } from '../assembler/label/bmfontUtils'; import { ISharedLabelData } from '../assembler/label/ttfUtils'; import { UIRenderComponent } from './ui-render-component'; -import { UI } from '../../../renderer/ui/ui'; /** * !#en Enum for text alignment. @@ -539,7 +539,7 @@ export class LabelComponent extends UIRenderComponent { private _texture: SpriteFrame | null = null; private _ttfTexture: SpriteFrame | null = null; private _userDefinedFont: Font | null = null; - private _assemblerData: ISharedLabelData|null = null; + private _assemblerData: ISharedLabelData | null = null; private _fontAtlas: FontAtlas | null = null; constructor () { diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 29d8ef4e8b..3cfc07c20b 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -501,7 +501,7 @@ export class SpriteComponent extends UIRenderComponent { if (!this._renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); - this._renderData.material = this.sharedMaterial; + this._renderData.material = this._material; this.markForUpdateRenderData(); } } @@ -509,7 +509,7 @@ export class SpriteComponent extends UIRenderComponent { private _activateMaterial () { const spriteFrame = this._spriteFrame; - const material = this.sharedMaterial; + const material = this._material; // WebGL if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { // if (!material) { diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index c17d2612d2..5ebfc91a5d 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -150,6 +150,10 @@ export class UIRenderComponent extends Component { this._instanceMaterial(); } + get material () { + return this._material; + } + /** * !#en find the rendered camera * !#zh 查找被渲染相机 @@ -162,18 +166,6 @@ export class UIRenderComponent extends Component { return this._renderData; } - get material () { - return this._material; - } - - set material (value: Material | null) { - if (this._material === value) { - return; - } - - this._updateMaterial(value); - } - public static Assembler: IAssemblerManager | null = null; public static PostAssembler: IAssemblerManager | null = null; @@ -255,7 +247,7 @@ export class UIRenderComponent extends Component { // } // this._allocedDatas.length = 0; this.destroyRenderData(); - this.material = null; + this._updateMaterial(null); this._renderData = null; } @@ -338,7 +330,7 @@ export class UIRenderComponent extends Component { } protected _updateColor () { - const material = this.material; + const material = this._material; if (material) { material.setProperty('color', this._color); // material.updateHash(); @@ -387,7 +379,7 @@ export class UIRenderComponent extends Component { private _instanceMaterial (){ if (this._sharedMaterial) { - this.material = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); + this._updateMaterial(Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false)); } } } diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index 90449e4ce4..d96f66762b 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -1,5 +1,6 @@ import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { EventListener } from '../../../core/platform/event-manager/CCEventListener'; import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/value-types'; import * as math from '../../../core/vmath/index'; import { EventType } from '../../../scene-graph/node-event-enum'; @@ -225,22 +226,20 @@ export class UITransformComponent extends Component { testPt.y += this._anchorPoint.y * h; if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { - // console.log('wpos '+this.node.getWorldPosition().toString()); - // console.log('click '+this.node.name); - // if (listener && listener.mask) { - // const mask = listener.mask; - // const parent = this; - // // find mask parent, should hit test it - // if (parent === mask.node) { - // const comp = parent.getComponent(MaskComponent); - // return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true; - // } else { - // listener.mask = null; - // return true; - // } - // } else { + if (listener && listener.mask) { + const mask = listener.mask; + const parent = this.node; + // find mask parent, should hit test it + if (parent === mask.node) { + const comp = parent.getComponent(cc.MaskComponent); + return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true; + } else { + listener.mask = null; + return true; + } + } else { return true; - // } + } } else { return false; } diff --git a/cocos/3d/ui/components/widget-manager.ts b/cocos/3d/ui/components/widget-manager.ts index 00887cfd9d..0e72bb4636 100644 --- a/cocos/3d/ui/components/widget-manager.ts +++ b/cocos/3d/ui/components/widget-manager.ts @@ -235,7 +235,7 @@ function align (node: Node, widget: WidgetComponent) { } function visitNode (node: Node) { - const widget = node.uiWidgetComp; + const widget = node.getComponent(WidgetComponent); if (widget) { if (CC_DEV) { // widget._validateTargetInDEV(); @@ -448,7 +448,7 @@ function updateAlignment (node: Node) { } // node._widget will be null when widget is disabled - const widget = node.uiWidgetComp; + const widget = node.getComponent(WidgetComponent); if (widget && parent) { align(node, widget); } @@ -483,7 +483,6 @@ export const widgetManager = cc._widgetManager = { } }, add (widget: WidgetComponent) { - widget.node.uiWidgetComp = widget; this._nodesOrderDirty = true; if (CC_EDITOR /*&& !cc.engine.isPlaying*/) { const renderComp = widget.node.getComponent(UIRenderComponent); @@ -499,7 +498,6 @@ export const widgetManager = cc._widgetManager = { } }, remove (widget: WidgetComponent) { - widget.node.uiWidgetComp = null; this._activeWidgetsIterator.remove(widget); if (CC_EDITOR && !cc.engine.isPlaying) { widget.node.off(Event.POSITION_PART, adjustWidgetToAllowMovingInEditor, widget); @@ -514,7 +512,7 @@ export const widgetManager = cc._widgetManager = { }, refreshWidgetOnResized (node: Node) { if (Node.isNode(node)){ - const widget = node.uiWidgetComp; + const widget = node.getComponent(WidgetComponent); // const widget: WidgetComponent | null = null; if (widget) { if (widget!.alignMode === AlignMode.ON_WINDOW_RESIZE) { diff --git a/cocos/assets/CCSpriteFrame.ts b/cocos/assets/CCSpriteFrame.ts index d58191d97e..79d0c344c5 100644 --- a/cocos/assets/CCSpriteFrame.ts +++ b/cocos/assets/CCSpriteFrame.ts @@ -26,15 +26,12 @@ ****************************************************************************/ import { ccclass } from '../core/data/class-decorator'; -import EventTarget from '../core/event/event-target'; import { EventTargetFactory } from '../core/event/event-target-factory'; -import { addon } from '../core/utils/js'; -import Rect, { rect } from '../core/value-types/rect'; -import Size, { size } from '../core/value-types/size'; -import Vec2, { v2 } from '../core/value-types/vec2'; +import { Rect, Size, Vec2 } from '../core/value-types'; +import { vec2 } from '../core/vmath'; +import { ImageAsset } from './image-asset'; import { Texture2D } from './texture-2d'; import textureUtil from './texture-util'; -import { ImageAsset } from './image-asset'; const INSET_LEFT = 0; const INSET_TOP = 1; @@ -121,6 +118,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { get insetTop () { return this._capInsets[INSET_TOP]; } + set insetTop (value) { this._capInsets[INSET_TOP] = value; // if (this._texture) { @@ -138,6 +136,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { get insetBottom () { return this._capInsets[INSET_BOTTOM]; } + set insetBottom (value) { this._capInsets[INSET_BOTTOM] = value; // if (this._texture) { @@ -155,6 +154,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { get insetLeft () { return this._capInsets[INSET_LEFT]; } + set insetLeft (value) { this._capInsets[INSET_LEFT] = value; // if (this._texture) { @@ -172,6 +172,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { get insetRight () { return this._capInsets[INSET_RIGHT]; } + set insetRight (value) { this._capInsets[INSET_RIGHT] = value; // if (this._texture) { @@ -183,7 +184,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { return this._atlasUuid; } - set atlasUuid (value) { + set atlasUuid (value: string) { this._atlasUuid = value; } @@ -217,7 +218,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { // store original info before packed to dynamic atlas private _original = null; - private _atlasUuid?: string; + private _atlasUuid: string = ''; private _atlasSize = new Size(); @@ -291,8 +292,13 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { * !#en Returns the rect of the sprite frame in the texture. * !#zh 获取 SpriteFrame 的纹理矩形区域 */ - public getRect () { - return rect(this._rect); + public getRect (out?: Rect) { + if (out) { + out.set(this._rect); + return out; + } + + return this._rect.clone(); } /** @@ -307,8 +313,13 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { * !#en Returns the original size of the trimmed image. * !#zh 获取修剪前的原始大小 */ - public getOriginalSize () { - return size(this._originalSize); + public getOriginalSize (out?: Size) { + if (out) { + out.set(this._originalSize); + return out; + } + + return this._originalSize.clone(); } /** @@ -345,8 +356,8 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { // return; // } // let w = texture.width, h = texture.height; - let w = self.width; - let h = self.height; + const w = self.width; + const h = self.height; // if (self._rotated && cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { // // TODO: rotate texture for canvas @@ -362,15 +373,15 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { if (self._rect) { self.checkRect(this.image!); } else { - self.setRect(cc.rect(0, 0, w, h)); + self.setRect(new Rect(0, 0, w, h)); } if (!self._originalSize) { - self.setOriginalSize(cc.size(w, h)); + self.setOriginalSize(new Size(w, h)); } if (!self._offset) { - self.setOffset(cc.v2(0, 0)); + self.setOffset(new Vec2(0, 0)); } self._calculateUV(); @@ -401,8 +412,13 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { * !#en Returns the offset of the frame in the texture. * !#zh 获取偏移量 */ - public getOffset () { - return v2(this._offset); + public getOffset (out?: Vec2) { + if (out) { + out.set(this._offset); + return out; + } + + return this._offset.clone(); } /** @@ -411,7 +427,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { * @param offsets */ public setOffset (offsets: Vec2) { - this._offset = new Vec2(offsets); + vec2.set(this._offset, offsets.x, offsets.y); } /** @@ -536,7 +552,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { // this._texture = null; // TODO - release texture // } - public checkRect(texture: ImageAsset) { + public checkRect (texture: ImageAsset) { const rect = this._rect; let maxX = rect.x; let maxY = rect.y; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index cddda4eb6d..33b0750f02 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -30,6 +30,7 @@ import IDGenerator from '../core/utils/id-generator'; import { ccclass, property } from '../core/data/class-decorator'; import { Node } from '../scene-graph/node'; import { RenderScene } from '../renderer/scene/render-scene'; +import { EventTarget } from '../core/event/event-target'; export class Component extends CCObject { node: Node; @@ -53,4 +54,5 @@ export class Component extends CCObject { // friend to class BaseNode public _id: string; public _enabled: boolean; + public _eventTargets: Array; } diff --git a/cocos/components/component.js b/cocos/components/component.js index 867c106ea6..50168cb464 100644 --- a/cocos/components/component.js +++ b/cocos/components/component.js @@ -215,10 +215,10 @@ class Component extends CCObject { /** * Register all related EventTargets, * all event callbacks will be removed in _onPreDestroy - * @property {Array} __eventTargets + * @property {Array} _eventTargets * @private */ - this.__eventTargets = []; + this._eventTargets = []; } // PUBLIC @@ -341,7 +341,7 @@ class Component extends CCObject { this.unscheduleAllCallbacks(); // Remove all listeners - var eventTargets = this.__eventTargets; + var eventTargets = this._eventTargets; for (var i = 0, l = eventTargets.length; i < l; ++i) { var target = eventTargets[i]; target && target.targetOff(this); diff --git a/cocos/core/platform/event-manager/CCEventListener.ts b/cocos/core/platform/event-manager/CCEventListener.ts index df8636f435..833cfe209d 100644 --- a/cocos/core/platform/event-manager/CCEventListener.ts +++ b/cocos/core/platform/event-manager/CCEventListener.ts @@ -1,3 +1,5 @@ +import { MaskComponent } from "../../../3d/ui/components/mask-component"; + /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. @@ -137,6 +139,12 @@ export class EventListener { return listener!; } + // hack: How to solve the problem of uncertain attribute + // callback's this object + public owner: Object | null = null; + public mask: MaskComponent | null = null; + public _previousIn?: boolean = false; + public _target: any = null; // Event callback function diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 6c580647cb..51a47c65f0 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -1,3 +1,5 @@ +import { ccenum } from '../core/value-types/enum'; + // Extensions export enum WebGLEXT { COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, @@ -358,6 +360,8 @@ export enum GFXBlendFactor { ONE_MINUS_CONSTANT_ALPHA, } +ccenum(GFXBlendFactor); + export enum GFXColorMask { NONE = 0x0, R = 0x1, diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 18daffb9c9..c8dcee592f 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -654,6 +654,7 @@ export class UI { this._currTexView = null; this._meshBufferUseCount = 0; this._requireBufferBatch(); + StencilManager.sharedManager!.reset(); // this._commitUIRenderDataPool.reset(); // this._commitUICanvas.length = 0; } diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index 92289db425..d3371bea01 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -1,13 +1,14 @@ -import { Node } from "./node"; -import { eventManager } from '../core/platform/event-manager'; +import { Component } from '../components/component'; import EventTarget from '../core/event/event-target'; -import { EventListener } from "../core/platform/event-manager/CCEventListener"; +import { eventManager } from '../core/platform/event-manager'; +import { EventListener } from '../core/platform/event-manager/CCEventListener'; +import Touch from '../core/platform/event-manager/CCTouch'; +import { EventMouse, EventTouch} from '../core/platform/event-manager/index'; import { array } from '../core/utils/js'; -import { EventMouse, EventTouch} from "../core/platform/event-manager/index"; -import { EventType } from "./node-event-enum"; +import { Node } from './node'; +import { EventType } from './node-event-enum'; const _cachedArray = new Array(16); -_cachedArray.length = 0; let _currentHovered: Node | null = null; const _touchEvents = [ @@ -26,7 +27,8 @@ const _mouseEvents = [ EventType.MOUSE_WHEEL.toString(), ]; -const _touchStartHandler = function (touch, event: EventTouch) { +// TODO: rearrange event +function _touchStartHandler (this: EventListener, touch: Touch, event: EventTouch) { const pos = touch.getLocation(); const node = this.owner; @@ -38,17 +40,26 @@ const _touchStartHandler = function (touch, event: EventTouch) { return true; } return false; -}; -const _touchMoveHandler = function (touch, event: EventTouch) { - const node = this.owner; +} + +function _touchMoveHandler (this: EventListener, touch: Touch, event: EventTouch) { + const node = this.owner as Node; + if (!node || !node.uiTransfromComp) { + return; + } + event.type = EventType.TOUCH_MOVE.toString(); event.touch = touch; event.bubbles = true; node.dispatchEvent(event); -}; -const _touchEndHandler = function (touch, event: EventTouch) { +} + +function _touchEndHandler (this: EventListener, touch: Touch, event: EventTouch) { const pos = touch.getLocation(); - const node = this.owner; + const node = this.owner as Node; + if (!node || !node.uiTransfromComp) { + return; + } if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.TOUCH_END.toString(); @@ -58,29 +69,41 @@ const _touchEndHandler = function (touch, event: EventTouch) { event.touch = touch; event.bubbles = true; node.dispatchEvent(event); -}; -const _touchCancelHandler = function (touch, event: EventTouch) { - const node = this.owner; +} + +function _touchCancelHandler (this: EventListener, touch: Touch, event: EventTouch) { + const node = this.owner as Node; + if (!node || !node.uiTransfromComp) { + return; + } event.type = EventType.TOUCH_CANCEL.toString(); event.touch = touch; event.bubbles = true; node.dispatchEvent(event); -}; +} -const _mouseDownHandler = function (event: EventMouse) { +function _mouseDownHandler (this: EventListener, event: EventMouse) { const pos = event.getLocation(); - const node = this.owner; + const node = this.owner as Node; + if (!node || !node.uiTransfromComp) { + return; + } if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.MOUSE_DOWN.toString(); event.bubbles = true; node.dispatchEvent(event); } -}; -const _mouseMoveHandler = function (event: EventMouse) { +} + +function _mouseMoveHandler (this: EventListener, event: EventMouse) { const pos = event.getLocation(); - const node = this.owner; + const node = this.owner as Node; + if (!node || !node.uiTransfromComp){ + return; + } + const hit = node.uiTransfromComp.isHit(pos, this); if (hit) { if (!this._previousIn) { @@ -92,7 +115,7 @@ const _mouseMoveHandler = function (event: EventMouse) { _currentHovered!.eventProcessor.mouseListener!._previousIn = false; } } - _currentHovered = this.owner; + _currentHovered = node; event.type = EventType.MOUSE_ENTER.toString(); node.dispatchEvent(event); this._previousIn = true; @@ -113,34 +136,43 @@ const _mouseMoveHandler = function (event: EventMouse) { // Event processed, cleanup // event.propagationStopped = true; event.propagationStopped = true; -}; -const _mouseUpHandler = function (event: EventMouse) { +} + +function _mouseUpHandler (this: EventListener, event: EventMouse) { const pos = event.getLocation(); - const node = this.owner; + const node = this.owner as Node; + if (!node || !node.uiTransfromComp) { + return; + } if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.MOUSE_UP.toString(); event.bubbles = true; node.dispatchEvent(event); // event.propagationStopped = true; - event.propagationStopped=true; + event.propagationStopped = true; } -}; -const _mouseWheelHandler = function (event: EventTouch) { +} + +function _mouseWheelHandler (this: EventListener, event: EventTouch) { const pos = event.getLocation(); - const node = this.owner; + const node = this.owner as Node; + if (!node || !node.uiTransfromComp) { + return; + } if (node.uiTransfromComp!.isHit(pos, this)) { event.type = EventType.MOUSE_WHEEL.toString(); event.bubbles = true; node.dispatchEvent(event); // event.propagationStopped = true; - event.propagationStopped=true; + event.propagationStopped = true; } -}; +} -function _doDispatchEvent(owner: Node, event: EventTouch) { - let target, i; +function _doDispatchEvent (owner: Node, event: EventTouch) { + let target; + let i = 0; event.target = owner; // Event.CAPTURING_PHASE @@ -150,10 +182,10 @@ function _doDispatchEvent(owner: Node, event: EventTouch) { event.eventPhase = 1; for (i = _cachedArray.length - 1; i >= 0; --i) { target = _cachedArray[i]; - if (target._capturingListeners) { + if (target._capturingTargets) { event.currentTarget = target; // fire event - target._capturingListeners.emit(event.type, event, _cachedArray); + target._capturingTargets.emit(event.type, event, _cachedArray); // check if propagation stopped if (event.propagationStopped) { _cachedArray.length = 0; @@ -167,11 +199,11 @@ function _doDispatchEvent(owner: Node, event: EventTouch) { // checks if destroyed in capturing callbacks event.eventPhase = 2; event.currentTarget = owner; - if (owner.eventProcessor.capturingListeners) { - owner.eventProcessor.capturingListeners.emit(event.type, event); + if (owner.eventProcessor.capturingTargets) { + owner.eventProcessor.capturingTargets.emit(event.type, event); } - if (!event.propagationImmediateStopped && owner.eventProcessor.bubblingListeners) { - owner.eventProcessor.bubblingListeners.emit(event.type, event); + if (!event.propagationImmediateStopped && owner.eventProcessor.bubblingTargets) { + owner.eventProcessor.bubblingTargets.emit(event.type, event); } if (!event.propagationStopped && event.bubbles) { @@ -181,10 +213,10 @@ function _doDispatchEvent(owner: Node, event: EventTouch) { event.eventPhase = 3; for (i = 0; i < _cachedArray.length; ++i) { target = _cachedArray[i]; - if (target._bubblingListeners) { + if (target._bubblingTargets) { event.currentTarget = target; // fire event - target._bubblingListeners.emit(event.type, event); + target._bubblingTargets.emit(event.type, event); // check if propagation stopped if (event.propagationStopped) { _cachedArray.length = 0; @@ -196,15 +228,15 @@ function _doDispatchEvent(owner: Node, event: EventTouch) { _cachedArray.length = 0; } -function _searchMaskInParent(node: Node | null) { - var Mask = cc.MaskComponent; +function _searchMaskInParent (node: Node | null) { + const Mask = cc.MaskComponent; if (Mask) { let index = 0; for (let curr = node; curr && Node.isNode(curr); curr = curr.parent, ++index) { if (curr.getComponent(Mask)) { return { - index: index, - node: curr + index, + node: curr, }; } } @@ -212,25 +244,35 @@ function _searchMaskInParent(node: Node | null) { return null; } -function _checkListeners(listeners: EventTarget, events) { - if (listeners) { - for (let i = 0; i < events.length; ++i) { - if (listeners.hasEventListener(events[i])) { - return true; +function _checkListeners (node: Node, events: string[]) { + if (!node._persistNode) { + let i = 0; + if (node.eventProcessor.bubblingTargets) { + for (; i < events.length; ++i) { + if (node.eventProcessor.bubblingTargets.hasEventListener(events[i])) { + return true; + } } } + if (node.eventProcessor.capturingTargets) { + for (; i < events.length; ++i) { + if (node.eventProcessor.capturingTargets.hasEventListener(events[i])) { + return true; + } + } + } + return false; } - - return false; + return true; } export class NodeEventProcessor { - public get node(): Node { + public get node (): Node { return this._node; } // Event listeners - public bubblingListeners: EventTarget | null = null; - public capturingListeners: EventTarget | null = null; + public bubblingTargets: EventTarget | null = null; + public capturingTargets: EventTarget | null = null; // Touch event listener public touchListener: EventListener | null = null; // Mouse event listener @@ -238,13 +280,228 @@ export class NodeEventProcessor { private _node: Node; - constructor(node: Node) { + constructor (node: Node) { this._node = node; } + /** + * !#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.propagationStopped = true` 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 之后传递额外的参数作为事件回调的参数列表 + * @method on + * @param {String|Node.EventType} type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. + * @param {Function} 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 {Event|any} [callback.event] event or first argument when emit + * @param {any} [callback.arg2] arg2 + * @param {any} [callback.arg3] arg3 + * @param {any} [callback.arg4] arg4 + * @param {any} [callback.arg5] arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @param {Boolean} [useCapture=false] - 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 {Function} - Just returns the incoming callback so you can save the anonymous function easier. + * @typescript + * on(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. + * this.node.on(cc.Node.EventType.TOUCH_START, callback, this); + * this.node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); + */ + public on (type: string, callback: Function, target?: Object, useCapture?: Object) { + const forDispatch = this._checknSetupSysEvent(type); + if (forDispatch) { + return this._onDispatch(type, callback, target, useCapture); + } else { + // switch (type) { + // case EventType.POSITION_CHANGED: + // this._eventMask |= POSITION_ON; + // break; + // case EventType.SCALE_CHANGED: + // this._eventMask |= SCALE_ON; + // break; + // case EventType.ROTATION_CHANGED: + // this._eventMask |= ROTATION_ON; + // break; + // case EventType.SIZE_CHANGED: + // this._eventMask |= SIZE_ON; + // break; + // case EventType.ANCHOR_CHANGED: + // this._eventMask |= ANCHOR_ON; + // break; + // } + if (!this.bubblingTargets) { + this.bubblingTargets = new EventTarget(); + } + return this.bubblingTargets.on(type, callback, target); + } + } + + /** + * !#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 + * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @method once + * @param {String} type - A string representing the event type to listen for. + * @param {Function} 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 {Event|any} [callback.event] event or first argument when emit + * @param {any} [callback.arg2] arg2 + * @param {any} [callback.arg3] arg3 + * @param {any} [callback.arg4] arg4 + * @param {any} [callback.arg5] arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @typescript + * once(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback); + */ + public once (type: string, callback: Function, target?: Object, useCapture?: Object) { + const forDispatch = this._checknSetupSysEvent(type); + const eventType_hasOnceListener = '__ONCE_FLAG:' + type; + + let listeners: EventTarget; + if (forDispatch && useCapture) { + listeners = this.capturingTargets = this.capturingTargets || new EventTarget(); + } + else { + listeners = this.bubblingTargets = this.bubblingTargets || new EventTarget(); + } + + const hasOnceListener = listeners!.hasEventListener(eventType_hasOnceListener, callback, target); + if (!hasOnceListener) { + const self = this; + const onceWrapper = (...args) => { + self.off(type, onceWrapper, target); + listeners.remove(eventType_hasOnceListener, callback, target); + callback.call(self._node, ...args); + }; + this.on(type, onceWrapper, target); + listeners.add(eventType_hasOnceListener, callback, target); + } + } + + /** + * !#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 注册的回调。 + * @method off + * @param {String} type - A string representing the event type being removed. + * @param {Function} [callback] - The callback to remove. + * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @param {Boolean} [useCapture=false] - 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 + * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this); + * node.off(cc.Node.EventType.TOUCH_START, callback, this.node); + * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this); + */ + public off (type: string, callback?: Function, target?: Object, useCapture?: Object) { + const touchEvent = _touchEvents.indexOf(type) !== -1; + const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1; + if (touchEvent || mouseEvent) { + this._offDispatch(type, callback, target, useCapture); + + if (touchEvent) { + if (this.touchListener && !_checkListeners(this._node, _touchEvents)) { + eventManager.removeListener(this.touchListener); + this.touchListener = null; + } + } else if (mouseEvent) { + if (this.mouseListener && !_checkListeners(this._node, _mouseEvents)) { + eventManager.removeListener(this.mouseListener); + this.mouseListener = null; + } + } + } else if (this.bubblingTargets) { + this.bubblingTargets.off(type, callback, target); + + // const hasListeners = this.bubblingTargets.hasEventListener(type); + // All listener removed + // if (!hasListeners) { + // switch (type) { + // case EventType.POSITION_CHANGED: + // this._eventMask &= ~POSITION_ON; + // break; + // case EventType.SCALE_CHANGED: + // this._eventMask &= ~SCALE_ON; + // break; + // case EventType.ROTATION_CHANGED: + // this._eventMask &= ~ROTATION_ON; + // break; + // case EventType.SIZE_CHANGED: + // this._eventMask &= ~SIZE_ON; + // break; + // case EventType.ANCHOR_CHANGED: + // this._eventMask &= ~ANCHOR_ON; + // break; + // } + // } + } + } + + /** + * !#en + * Trigger an event directly with the event name and necessary arguments. + * !#zh + * 通过事件名发送自定义事件 + * + * @method emit + * @param {String} 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 + * + * eventTarget.emit('fire', event); + * eventTarget.emit('fire', message, emitter); + */ + public emit (type, ...args: any[]) { + if (this.bubblingTargets) { + this.bubblingTargets.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 分发事件到事件流中。 + * + * @method dispatchEvent + * @param {Event} event - The Event object that is dispatched into the event flow + */ + public dispatchEvent (event: EventTouch) { + _doDispatchEvent(this._node, event); + _cachedArray.length = 0; + } + // EVENT TARGET - public _checknSetupSysEvent(type) { + private _checknSetupSysEvent (type: string) { let newAdded = false; let forDispatch = false; if (_touchEvents.indexOf(type) !== -1) { @@ -290,125 +547,7 @@ export class NodeEventProcessor { return forDispatch; } - /** - * !#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.propagationStopped = true` 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 之后传递额外的参数作为事件回调的参数列表 - * @method on - * @param {String|Node.EventType} type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. - * @param {Function} 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 {Event|any} [callback.event] event or first argument when emit - * @param {any} [callback.arg2] arg2 - * @param {any} [callback.arg3] arg3 - * @param {any} [callback.arg4] arg4 - * @param {any} [callback.arg5] arg5 - * @param {Object} [target] - The target (this object) to invoke the callback, can be null - * @param {Boolean} [useCapture=false] - 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 {Function} - Just returns the incoming callback so you can save the anonymous function easier. - * @typescript - * on(type: string, callback: T, target?: any, useCapture?: boolean): T - * @example - * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. - * this.node.on(cc.Node.EventType.TOUCH_START, callback, this); - * this.node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); - */ - public on(type: string, callback: Function, target?: Object, useCapture?: Object) { - const forDispatch = this._checknSetupSysEvent(type); - if (forDispatch) { - return this._onDispatch(type, callback, target, useCapture); - } else { - // switch (type) { - // case EventType.POSITION_CHANGED: - // this._eventMask |= POSITION_ON; - // break; - // case EventType.SCALE_CHANGED: - // this._eventMask |= SCALE_ON; - // break; - // case EventType.ROTATION_CHANGED: - // this._eventMask |= ROTATION_ON; - // break; - // case EventType.SIZE_CHANGED: - // this._eventMask |= SIZE_ON; - // break; - // case EventType.ANCHOR_CHANGED: - // this._eventMask |= ANCHOR_ON; - // break; - // } - if (!this.bubblingListeners) { - this.bubblingListeners = new EventTarget(); - } - return this.bubblingListeners.on(type, callback, target); - } - } - - /** - * !#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 - * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。 - * - * @method once - * @param {String} type - A string representing the event type to listen for. - * @param {Function} 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 {Event|any} [callback.event] event or first argument when emit - * @param {any} [callback.arg2] arg2 - * @param {any} [callback.arg3] arg3 - * @param {any} [callback.arg4] arg4 - * @param {any} [callback.arg5] arg5 - * @param {Object} [target] - The target (this object) to invoke the callback, can be null - * @typescript - * once(type: string, callback: T, target?: any, useCapture?: boolean): T - * @example - * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback); - */ - once(type: string, callback: Function, target: Object, useCapture?: Object) { - let forDispatch = this._checknSetupSysEvent(type); - let eventType_hasOnceListener = '__ONCE_FLAG:' + type; - - let listeners: EventTarget | null = null; - if (forDispatch && useCapture) { - listeners = this.capturingListeners = this.capturingListeners || new EventTarget(); - } - else { - listeners = this.bubblingListeners = this.bubblingListeners || new EventTarget(); - } - - let hasOnceListener = listeners!.hasEventListener(eventType_hasOnceListener, callback, target); - if (!hasOnceListener) { - let self = this; - let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { - self.off(type, onceWrapper, target); - listeners.remove(eventType_hasOnceListener, callback, target); - callback.call(this._node, arg1, arg2, arg3, arg4, arg5); - }; - this.on(type, onceWrapper, target); - listeners.add(eventType_hasOnceListener, callback, target); - } - } - - public _onDispatch(type: string, callback: Function, target?: Object, useCapture?: Object) { + private _onDispatch (type: string, callback: Function, target?: Object, useCapture?: Object) { // Accept also patameters like: (type, callback, useCapture) if (typeof target === 'boolean') { useCapture = target; @@ -421,141 +560,49 @@ export class NodeEventProcessor { let listeners: EventTarget | null = null; if (useCapture) { - listeners = this.capturingListeners = this.capturingListeners || new EventTarget(); + listeners = this.capturingTargets = this.capturingTargets || new EventTarget(); } else { - listeners = this.bubblingListeners = this.bubblingListeners || new EventTarget(); + listeners = this.bubblingTargets = this.bubblingTargets || new EventTarget(); } if (!listeners.hasEventListener(type, callback, target)) { listeners.add(type, callback, target); - if (target && target.__eventTargets) { - target.__eventTargets.push(this); + if (target && (target as Component)._eventTargets) { + (target as Component)._eventTargets.push(this._node); } } return callback; } - /** - * !#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 注册的回调。 - * @method off - * @param {String} type - A string representing the event type being removed. - * @param {Function} [callback] - The callback to remove. - * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed - * @param {Boolean} [useCapture=false] - 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 - * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this); - * node.off(cc.Node.EventType.TOUCH_START, callback, this.node); - * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this); - */ - public off(type: string, callback?: Function, target?: Object, useCapture?: Object) { - const touchEvent = _touchEvents.indexOf(type) !== -1; - const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1; - if (touchEvent || mouseEvent) { - this._offDispatch(type, callback, target, useCapture); - - if (touchEvent) { - if (this.touchListener && !_checkListeners(this.touchListener, _touchEvents)) { - eventManager.removeListener(this.touchListener); - this.touchListener = null; - } - } else if (mouseEvent) { - if (this.mouseListener && !_checkListeners(this.mouseListener, _mouseEvents)) { - eventManager.removeListener(this.mouseListener); - this.mouseListener = null; - } - } - } else if (this.bubblingListeners) { - this.bubblingListeners.off(type, callback, target); - - const hasListeners = this.bubblingListeners.hasEventListener(type); - // All listener removed - // if (!hasListeners) { - // switch (type) { - // case EventType.POSITION_CHANGED: - // this._eventMask &= ~POSITION_ON; - // break; - // case EventType.SCALE_CHANGED: - // this._eventMask &= ~SCALE_ON; - // break; - // case EventType.ROTATION_CHANGED: - // this._eventMask &= ~ROTATION_ON; - // break; - // case EventType.SIZE_CHANGED: - // this._eventMask &= ~SIZE_ON; - // break; - // case EventType.ANCHOR_CHANGED: - // this._eventMask &= ~ANCHOR_ON; - // break; - // } - // } - } - } - - public _offDispatch(type: string, callback: Function, target?: Object, useCapture?: Object) { + private _offDispatch (type: string, callback?: Function, target?: Object, useCapture?: Object) { // Accept also patameters like: (type, callback, useCapture) if (typeof target === 'boolean') { useCapture = target; target = undefined; } else { useCapture = !!useCapture; } if (!callback) { - this.capturingListeners && this.capturingListeners.removeAll(type); - this.bubblingListeners && this.bubblingListeners.removeAll(type); + if (this.capturingTargets){ + this.capturingTargets.removeAll(type); + } + + if (this.bubblingTargets){ + this.bubblingTargets.removeAll(type); + } } else { - const listeners = useCapture ? this.capturingListeners : this.bubblingListeners; + const listeners = useCapture ? this.capturingTargets : this.bubblingTargets; if (listeners) { listeners.remove(type, callback, target); - if (target && target.__eventTargets) { - array.fastRemove(target.__eventTargets, this); + if (target && (target as Component)._eventTargets) { + array.fastRemove((target as Component)._eventTargets, this); } } } } - /** - * !#en - * Trigger an event directly with the event name and necessary arguments. - * !#zh - * 通过事件名发送自定义事件 - * - * @method emit - * @param {String} 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 - * - * eventTarget.emit('fire', event); - * eventTarget.emit('fire', message, emitter); - */ - public emit(type, ...args: any[]) { - if (this.bubblingListeners) { - this.bubblingListeners.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 分发事件到事件流中。 - * - * @method dispatchEvent - * @param {Event} event - The Event object that is dispatched into the event flow - */ - public dispatchEvent(event: EventTouch) { - _doDispatchEvent(this._node, event); - _cachedArray.length = 0; - } - /** * Get all the targets listening to the supplied type of event in the target's capturing phase. * The capturing phase comprises the journey from the root to the last node BEFORE the event target's node. @@ -568,11 +615,11 @@ export class NodeEventProcessor { * @param {Array} array - the array to receive targets * @example {@link cocos2d/core/event/_getCapturingTargets.js} */ - _getCapturingTargets(type, array) { - var parent = this._node.parent; + private _getCapturingTargets (type: string, targets: Node[]) { + let parent = this._node.parent; while (parent) { - if (parent.eventProcessor.capturingListeners && parent.eventProcessor.capturingListeners.hasEventListener(type)) { - array.push(parent); + if (parent.eventProcessor.capturingTargets && parent.eventProcessor.capturingTargets.hasEventListener(type)) { + targets.push(parent); } parent = parent.parent; } @@ -589,11 +636,11 @@ export class NodeEventProcessor { * @param {String} type - the event type * @param {Array} array - the array to receive targets */ - _getBubblingTargets(type, array) { - var parent = this._node.parent; + private _getBubblingTargets (type: string, targets: Node[]) { + let parent = this._node.parent; while (parent) { - if (parent.eventProcessor.bubblingListeners && parent.eventProcessor.bubblingListeners.hasEventListener(type)) { - array.push(parent); + if (parent.eventProcessor.bubblingTargets && parent.eventProcessor.bubblingTargets.hasEventListener(type)) { + targets.push(parent); } parent = parent.parent; } diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 17263f6341..47a784b397 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -1,5 +1,4 @@ import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component'; -import { WidgetComponent } from '../3d/ui/components/widget-component'; import { ccclass, property } from '../core/data/class-decorator'; import { Mat4, Quat, Vec3 } from '../core/value-types'; import Size from '../core/value-types/size'; @@ -56,7 +55,6 @@ class Node extends BaseNode { protected _eventProcessor; private _uiTransfromComp: UITransformComponent | null = null; - private _uiWidgetComp: WidgetComponent | null = null; @property({ type: Vec3, @@ -97,18 +95,6 @@ class Node extends BaseNode { this._uiTransfromComp = value; } - get uiWidgetComp () { - if (!this._uiWidgetComp) { - this._uiWidgetComp = this.getComponent(WidgetComponent); - } - - return this._uiWidgetComp; - } - - set uiWidgetComp (value: WidgetComponent | null) { - this._uiWidgetComp = value; - } - get width () { return this.uiTransfromComp!.width; } From 19c390b8d9f7048e7d49c0f3dc1059dbd7901538 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Wed, 6 Mar 2019 09:15:48 +0800 Subject: [PATCH 4/4] modify default physics material (#3970) --- cocos/3d/framework/physics/default-material.ts | 11 +++++++++++ .../physics/detail/physics-based-component.ts | 5 ++++- cocos/3d/framework/physics/rigid-body-component.ts | 7 ++++++- cocos/3d/framework/physics/world.ts | 10 +++------- 4 files changed, 24 insertions(+), 9 deletions(-) create mode 100644 cocos/3d/framework/physics/default-material.ts diff --git a/cocos/3d/framework/physics/default-material.ts b/cocos/3d/framework/physics/default-material.ts new file mode 100644 index 0000000000..86be5e723e --- /dev/null +++ b/cocos/3d/framework/physics/default-material.ts @@ -0,0 +1,11 @@ + +import { PhysicsMaterial } from '../../assets/physics/material'; + +export const DefaultPhysicsMaterial: PhysicsMaterial = (() => { + const result = new PhysicsMaterial(); + result.friction = 0.3; + result.restitution = 0.3; + return result; +})(); + +cc.DefaultPhysicsMaterial = DefaultPhysicsMaterial; diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts index c33a2686e7..bf916b2bce 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -5,6 +5,7 @@ import { Quat, Vec3 } from '../../../../core/value-types'; import { quat, vec3 } from '../../../../core/vmath'; import { Node } from '../../../../scene-graph/node'; import { BoxColliderComponent, ColliderComponentBase, SphereColliderComponent } from '../collider-component'; +import { DefaultPhysicsMaterial } from '../default-material'; import { getWrap, setWrap } from '../util'; import { PhysicsWorld } from '../world'; @@ -103,7 +104,9 @@ class SharedRigidBody { private _worldScale: Vec3 = new Vec3(1, 1, 1); constructor (node: Node, world: PhysicsWorld) { - this._body = new CANNON.Body(); + this._body = new CANNON.Body({ + material: DefaultPhysicsMaterial._getImpl(), + }); this._node = node; setWrap(this._body, this._node); this._world = world; diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 0dcef3adc4..fa59b52bbf 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -10,6 +10,7 @@ import { import { Quat, Vec3 } from '../../../core/value-types'; import { vec3 } from '../../../core/vmath'; import { PhysicsMaterial } from '../../assets/physics/material'; +import { DefaultPhysicsMaterial as DefaultPhysicsMaterial } from './default-material'; import { PhysicsBasedComponent, TransformSource } from './detail/physics-based-component'; import { toCannonVec3 } from './util'; @@ -62,12 +63,16 @@ export class RigidBodyComponent extends PhysicsBasedComponent { this.mass = this._mass; this.linearDamping = this._linearDamping; this.angularDamping = this._angularDamping; + this.material = this._material; + this.useGravity = this._useGravity; } public onDisable () { this.mass = NonRigidBodyProperties.mass; this.linearDamping = NonRigidBodyProperties.linearDamping; this.angularDamping = NonRigidBodyProperties.angularDamping; + this.material = DefaultPhysicsMaterial; + this.useGravity = true; } @property({ @@ -80,7 +85,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set material (value) { this._material = value; if (this._body) { - this._body.material = this._material ? this._material._getImpl() : null; + this._body.material = (this._material || DefaultPhysicsMaterial)._getImpl(); } } diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts index 41218b2e3f..d65de3f7f2 100644 --- a/cocos/3d/framework/physics/world.ts +++ b/cocos/3d/framework/physics/world.ts @@ -5,6 +5,7 @@ import { Node } from '../../../scene-graph/node'; import { PhysicsMaterial } from '../../assets/physics/material'; import { Constraint } from './constraints'; import { ContactMaterial } from './contact-material'; +import { DefaultPhysicsMaterial } from './default-material'; import { getWrap, setWrap, toCannonOptions } from './util'; export interface IRaycastOptions { @@ -40,24 +41,19 @@ cc.RaycastResult = RaycastResult; export class PhysicsWorld { private _cannonWorld: CANNON.World; - private _defaultMaterial: PhysicsMaterial; private _defaultContactMaterial: ContactMaterial; private _beforeStepEvent: CANNON.IEvent = { type: 'beforeStep', }; constructor () { - this._defaultMaterial = new PhysicsMaterial(); - const mtl = new PhysicsMaterial(); - mtl.friction = 0.3; - mtl.restitution = 0; - this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, mtl); + this._defaultContactMaterial = new ContactMaterial(DefaultPhysicsMaterial, DefaultPhysicsMaterial); this._cannonWorld = new CANNON.World(); setWrap(this._cannonWorld, this); this._cannonWorld.gravity.set(0, -9.81, 0); this._cannonWorld.broadphase = new CANNON.NaiveBroadphase(); - this._cannonWorld.defaultMaterial = this._defaultMaterial._getImpl(); + this._cannonWorld.defaultMaterial = DefaultPhysicsMaterial._getImpl(); this._cannonWorld.defaultContactMaterial = this._defaultContactMaterial._getImpl(); }