diff --git a/cocos/2d/base-ui/widget-manager.ts b/cocos/2d/base-ui/widget-manager.ts deleted file mode 100644 index 7f3d37d7cc..0000000000 --- a/cocos/2d/base-ui/widget-manager.ts +++ /dev/null @@ -1,516 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// import { WidgetComponent } from '../../3d/ui/components/widget-component'; -import { array } from '../../core/utils/js'; -import { Enum, Size, Vec3 } from '../../core/value-types'; -import { Node } from '../../scene-graph/node'; -const Event = Node.EventType; - -const TOP = 1 << 0; -const MID = 1 << 1; // vertical center -const BOT = 1 << 2; -const LEFT = 1 << 3; -const CENTER = 1 << 4; // horizontal center -const RIGHT = 1 << 5; -const HORIZONTAL = LEFT | CENTER | RIGHT; -const VERTICAL = TOP | MID | BOT; - -enum AlignMode { - ONCE = 0, - ON_WINDOW_RESIZE = 1, - ALWAYS = 2, -} - -Enum(AlignMode); - -// returns a readonly size of the node -export function getReadonlyNodeSize (parent) { - // TODO: check with Editor - // if (parent instanceof cc.Scene) { - // return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect; - // } else { - // return parent._contentSize; - // } - - return cc.visibleRect; -} - -export function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseScale) { - let scaleX = widgetNode._parent._scale.x; - let scaleY = widgetNode._parent._scale.y; - let translateX = 0; - let translateY = 0; - for (let node = widgetNode._parent; ;) { - const pos = node._position; - translateX += pos.x; - translateY += pos.y; - node = node._parent; // loop increment - if (!node) { - // ERROR: widgetNode should be child of target - out_inverseTranslate.x = out_inverseTranslate.y = 0; - out_inverseScale.x = out_inverseScale.y = 1; - return; - } - if (node !== target) { - const sx = node._scale.x; - const sy = node._scale.y; - translateX *= sx; - translateY *= sy; - scaleX *= sx; - scaleY *= sy; - } else { - break; - } - } - out_inverseScale.x = scaleX !== 0 ? (1 / scaleX) : 1; - out_inverseScale.y = scaleY !== 0 ? (1 / scaleY) : 1; - out_inverseTranslate.x = -translateX; - out_inverseTranslate.y = -translateY; -} - -const tInverseTranslate = cc.Vec2.ZERO; -const tInverseScale = cc.Vec2.ONE; - -// align to borders by adjusting node's position and size (ignore rotation) -function align (node, widget) { - const hasTarget = widget._target; - let target; - let inverseTranslate; - let inverseScale; - if (hasTarget) { - target = hasTarget; - inverseTranslate = tInverseTranslate; - inverseScale = tInverseScale; - computeInverseTransForTarget(node, target, inverseTranslate, inverseScale); - } else { - target = node._parent; - } - const targetSize = getReadonlyNodeSize(target); - const targetAnchor = target._anchorPoint; - - const isRoot = !CC_EDITOR && target instanceof cc.Scene; - let x = node._position.x; - let y = node._position.y; - const anchor = node._anchorPoint; - - if (widget._alignFlags & HORIZONTAL) { - - let localLeft; - let localRight; - const targetWidth = targetSize.width; - if (isRoot) { - localLeft = cc.visibleRect.left.x; - localRight = cc.visibleRect.right.x; - } else { - localLeft = -targetAnchor.x * targetWidth; - localRight = localLeft + targetWidth; - } - - // adjust borders according to offsets - localLeft += widget._isAbsLeft ? widget._left : widget._left * targetWidth; - localRight -= widget._isAbsRight ? widget._right : widget._right * targetWidth; - - if (hasTarget) { - localLeft += inverseTranslate.x; - localLeft *= inverseScale.x; - localRight += inverseTranslate.x; - localRight *= inverseScale.x; - } - - let width; - let anchorX = anchor.x; - let scaleX = node._scale.x; - if (scaleX < 0) { - anchorX = 1.0 - anchorX; - scaleX = -scaleX; - } - if (widget.isStretchWidth) { - width = localRight - localLeft; - if (scaleX !== 0) { - node.width = width / scaleX; - } - x = localLeft + anchorX * width; - } else { - width = node.width * scaleX; - if (widget.isAlignHorizontalCenter) { - let localHorizontalCenter = widget._isAbsHorizontalCenter ? - widget._horizontalCenter : widget._horizontalCenter * targetWidth; - let targetCenter = (0.5 - targetAnchor.x) * targetSize.width; - if (hasTarget) { - localHorizontalCenter *= inverseScale.x; - targetCenter += inverseTranslate.x; - targetCenter *= inverseScale.x; - } - x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter; - } else if (widget.isAlignLeft) { - x = localLeft + anchorX * width; - } else { - x = localRight + (anchorX - 1) * width; - } - } - } - - if (widget._alignFlags & VERTICAL) { - - let localTop; - let localBottom; - const targetHeight = targetSize.height; - if (isRoot) { - localBottom = cc.visibleRect.bottom.y; - localTop = cc.visibleRect.top.y; - } else { - localBottom = -targetAnchor.y * targetHeight; - localTop = localBottom + targetHeight; - } - - // adjust borders according to offsets - localBottom += widget._isAbsBottom ? widget._bottom : widget._bottom * targetHeight; - localTop -= widget._isAbsTop ? widget._top : widget._top * targetHeight; - - if (hasTarget) { - // transform - localBottom += inverseTranslate.y; - localBottom *= inverseScale.y; - localTop += inverseTranslate.y; - localTop *= inverseScale.y; - } - - let height; - let anchorY = anchor.y; - let scaleY = node._scale.y; - if (scaleY < 0) { - anchorY = 1.0 - anchorY; - scaleY = -scaleY; - } - if (widget.isStretchHeight) { - height = localTop - localBottom; - if (scaleY !== 0) { - node.height = height / scaleY; - } - y = localBottom + anchorY * height; - } else { - height = node.height * scaleY; - if (widget.isAlignVerticalCenter) { - let localVerticalCenter = widget._isAbsVerticalCenter ? - widget._verticalCenter : widget._verticalCenter * targetHeight; - let targetMiddle = (0.5 - targetAnchor.y) * targetSize.height; - if (hasTarget) { - localVerticalCenter *= inverseScale.y; - targetMiddle += inverseTranslate.y; - targetMiddle *= inverseScale.y; - } - y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter; - } else if (widget.isAlignBottom) { - y = localBottom + anchorY * height; - } else { - y = localTop + (anchorY - 1) * height; - } - } - } - - node.setPosition(x, y); -} - -function visitNode (node: Node) { - const widget = node.uiWidgetComp; - if (widget) { - if (CC_DEV) { - // widget._validateTargetInDEV(); - } - align(node, widget); - if ((!CC_EDITOR /*|| animationState.animatedSinceLastFrame*/) && widget.alignMode !== AlignMode.ALWAYS) { - widget.enabled = false; - } else { - activeWidgets.push(widget); - } - } - const children = node.children; - for (const child of children) { - if (child.active) { - visitNode(child); - } - } -} - -if (CC_EDITOR) { - const animationState = { - previewing: false, - time: 0, - animatedSinceLastFrame: false, - }; -} - -function refreshScene () { - // check animation editor - // if (CC_EDITOR && !Editor.isBuilder) { - // const AnimUtils = Editor.require('scene://utils/animation'); - // const EditMode = Editor.require('scene://edit-mode'); - // if (AnimUtils && EditMode) { - // const nowPreviewing = (EditMode.curMode().name === 'animation' && !!AnimUtils.Cache.animation); - // if (nowPreviewing !== animationState.previewing) { - // animationState.previewing = nowPreviewing; - // if (nowPreviewing) { - // animationState.animatedSinceLastFrame = true; - // const component = cc.engine.getInstanceById(AnimUtils.Cache.component); - // if (component) { - // const animation = component.getAnimationState(AnimUtils.Cache.animation); - // animationState.time = animation.time; - // } - // } else { - // animationState.animatedSinceLastFrame = false; - // } - // } else if (nowPreviewing) { - // const component = cc.engine.getInstanceById(AnimUtils.Cache.component); - // if (component) { - // const animation = component.getAnimationState(AnimUtils.Cache.animation); - // if (animationState.time !== animation.time) { - // animationState.animatedSinceLastFrame = true; - // animationState.time = AnimUtils.Cache.animation.time; - // } - // } - // } - // } - // } - - const scene = cc.director.getScene(); - if (scene) { - widgetManager.isAligning = true; - if (widgetManager._nodesOrderDirty) { - activeWidgets.length = 0; - visitNode(scene); - widgetManager._nodesOrderDirty = false; - } else { - // // let i; - // let widget; - // const iterator = widgetManager._activeWidgetsIterator; - // // TODO: animation - // let AnimUtils; - // if (CC_EDITOR && - // (AnimUtils = Editor.require('scene://utils/animation')) && - // AnimUtils.Cache.animation) { - // const editingNode = cc.engine.getInstanceById(AnimUtils.Cache.rNode); - // if (editingNode) { - // for (i = activeWidgets.length - 1; i >= 0; i--) { - // widget = activeWidgets[i]; - // const node = widget.node; - // if (widget.alignMode !== AlignMode.ALWAYS && - // animationState.animatedSinceLastFrame && - // node.isChildOf(editingNode) - // ) { - // // widget contains in activeWidgets should aligned at least once - // widget.enabled = false; - // } else { - // align(node, widget); - // } - // } - // } - // } else { - // // loop reversely will not help to prevent out of sync - // // because user may remove more than one item during a step. - // for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) { - // widget = activeWidgets[iterator.i]; - // align(widget.node, widget); - // } - // } - } - widgetManager.isAligning = false; - } - - // check animation editor - if (CC_EDITOR) { - // animationState.animatedSinceLastFrame = false; - } -} - -function adjustWidgetToAllowMovingInEditor (oldPos: Vec3) { - if (!CC_EDITOR) { - return; - } - - if (widgetManager.isAligning) { - return; - } - const newPos = this.node.position; - const delta = newPos.sub(oldPos); - - let target = this.node._parent; - const inverseScale = cc.Vec2.ONE; - - if (this._target) { - target = this._target; - computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale); - } - - const targetSize = getReadonlyNodeSize(target); - let deltaInPercent; - if (targetSize.width !== 0 && targetSize.height !== 0) { - deltaInPercent = new cc.Vec2(delta.x / targetSize.width, delta.y / targetSize.height); - } else { - deltaInPercent = cc.Vec2.ZERO; - } - - if (this.isAlignTop) { - this.top -= (this.isAbsoluteTop ? delta.y : deltaInPercent.y) * inverseScale.y; - } - if (this.isAlignBottom) { - this.bottom += (this.isAbsoluteBottom ? delta.y : deltaInPercent.y) * inverseScale.y; - } - if (this.isAlignLeft) { - this.left += (this.isAbsoluteLeft ? delta.x : deltaInPercent.x) * inverseScale.x; - } - if (this.isAlignRight) { - this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * inverseScale.x; - } - if (this.isAlignHorizontalCenter) { - this.horizontalCenter += (this.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x) * inverseScale.x; - } - if (this.isAlignVerticalCenter) { - this.verticalCenter += (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; - } -} - -function adjustWidgetToAllowResizingInEditor (oldSize: Size) { - if (!CC_EDITOR) { - return; - } - - if (widgetManager.isAligning) { - return; - } - const newSize = this.node.getContentSize(); - const delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height); - - let target = this.node._parent; - const inverseScale = cc.Vec2.ONE; - if (this._target) { - target = this._target; - computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale); - } - - const targetSize = getReadonlyNodeSize(target); - let deltaInPercent; - if (targetSize.width !== 0 && targetSize.height !== 0) { - deltaInPercent = new cc.Vec2(delta.x / targetSize.width, delta.y / targetSize.height); - } else { - deltaInPercent = cc.Vec2.ZERO; - } - - const anchor = this.node._anchorPoint; - - if (this.isAlignTop) { - this.top -= (this.isAbsoluteTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; - } - if (this.isAlignBottom) { - this.bottom -= (this.isAbsoluteBottom ? delta.y : deltaInPercent.y) * anchor.y * inverseScale.y; - } - if (this.isAlignLeft) { - this.left -= (this.isAbsoluteLeft ? delta.x : deltaInPercent.x) * anchor.x * inverseScale.x; - } - if (this.isAlignRight) { - this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; - } -} - -const activeWidgets = []; - -// updateAlignment from scene to node recursively -function updateAlignment (node: Node) { - const parent = node.parent; - if (parent && cc.Node.isNode(parent)) { - updateAlignment(parent); - } - - // node._widget will be null when widget is disabled - const widget = node.uiWidgetComp || node.getComponent(cc.WidgetComponent); - if (widget && parent) { - align(node, widget); - } -} - -export const widgetManager = cc._widgetManager = { - _AlignFlags: { - TOP, - MID, // vertical center - BOT, - LEFT, - CENTER, // horizontal center - RIGHT, - }, - isAligning: false, - _nodesOrderDirty: false, - _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets), - - init (director) { - director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene); - - if (CC_EDITOR && cc.engine) { - cc.engine.on('design-resolution-changed', this.onResized.bind(this)); - } else { - if (cc.sys.isMobile) { - window.addEventListener('resize', this.onResized.bind(this)); - } else { - cc.view.on('canvas-resize', this.onResized, this); - } - } - }, - add (widget) { - widget.node._widget = widget; - this._nodesOrderDirty = true; - if (CC_EDITOR && !cc.engine.isPlaying) { - widget.node.on(Event.POSITION_CHANGED, adjustWidgetToAllowMovingInEditor, widget); - widget.node.on(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); - } - }, - remove (widget) { - widget.node._widget = null; - this._activeWidgetsIterator.remove(widget); - if (CC_EDITOR && !cc.engine.isPlaying) { - widget.node.off(Event.POSITION_CHANGED, adjustWidgetToAllowMovingInEditor, widget); - widget.node.off(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); - } - }, - onResized () { - const scene = cc.director.getScene(); - if (scene) { - this.refreshWidgetOnResized(scene); - } - }, - refreshWidgetOnResized (node) { - const widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); - if (widget) { - if (widget.alignMode === AlignMode.ON_WINDOW_RESIZE) { - widget.enabled = true; - } - } - - const children = node._children; - for (const child of children) { - this.refreshWidgetOnResized(child); - } - }, - updateAlignment, - AlignMode, -}; diff --git a/cocos/2d/label/label-outline.ts b/cocos/2d/label/label-outline.ts index 578adefa0a..86594e6116 100644 --- a/cocos/2d/label/label-outline.ts +++ b/cocos/2d/label/label-outline.ts @@ -38,9 +38,11 @@ */ import { Component } from '../../components/component'; +import { Color } from '../../core/value-types'; +import { LabelComponent } from '../../3d/ui/components/label-component'; export class LabelOutline extends Component { - private _color = cc.color(255, 255, 255, 255); + private _color = new Color(255, 255, 255, 255); private _width = 1; /** @@ -55,7 +57,11 @@ export class LabelOutline extends Component { return this._color; } set color (value) { - this._color = cc.color(value); + if(this._color === value){ + return + } + + this._color = value; this._updateRenderData(); } @@ -67,19 +73,23 @@ export class LabelOutline extends Component { * @example * outline.width = 3; */ - get width () { + get width() { return this._width; } - set width (value) { + set width(value) { + if (this._width === value) { + return; + } + this._width = value; this._updateRenderData(); } private _updateRenderData () { - const label = this.node.getComponent(cc.Label); + const label = this.node.getComponent(LabelComponent); if (label) { - label._updateRenderData(true); + label.updateRenderData(true); } } } diff --git a/cocos/3d/framework/index.ts b/cocos/3d/framework/index.ts index cfabdc8433..eb60ab64c9 100644 --- a/cocos/3d/framework/index.ts +++ b/cocos/3d/framework/index.ts @@ -24,14 +24,14 @@ THE SOFTWARE. ****************************************************************************/ -import { CameraComponent } from './camera-component'; import AnimationComponent from './animation-component'; +import { CameraComponent } from './camera-component'; import LightComponent from './light-component'; import { ModelComponent } from './model-component'; +import { BoxColliderComponent, SphereColliderComponent, ColliderComponentBase } from './physics/collider-component'; +import { RigidBodyComponent } from './physics/rigid-body-component'; import SkinningModelComponent from './skinning-model-component'; import SkyboxComponent from './skybox-component'; -import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component'; -import { RigidBodyComponent } from './physics/rigid-body-component'; export * from './physics'; import ParticleSystemComponent from './particle/particle-system-component'; @@ -56,6 +56,7 @@ cc.SkinningModelComponent = SkinningModelComponent; cc.SkyboxComponent = SkyboxComponent; cc.RigidBodyComponent = RigidBodyComponent; +cc.ColliderComponentBase = ColliderComponentBase; cc.BoxColliderComponent = BoxColliderComponent; cc.SphereColliderComponent = SphereColliderComponent; cc.ParticleSystemComponent = ParticleSystemComponent; diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index 770ee6630e..139af8c67c 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -116,9 +116,9 @@ export class ModelComponent extends RenderableComponent { * !#ch 投射阴影方式 * @type {Number} */ - @property({ - type: ModelShadowCastingMode, - }) + // @property({ + // type: ModelShadowCastingMode, + // }) get shadowCastingMode () { return this._shadowCastingMode; } @@ -134,7 +134,7 @@ export class ModelComponent extends RenderableComponent { * !#ch 是否接受阴影? * @type {Boolean} */ - @property + // @property get receiveShadows () { return this._receiveShadows; } @@ -192,7 +192,11 @@ export class ModelComponent extends RenderableComponent { return; } - this._createModel(); + if (this._model) { + this._model.destroy(); + } else { + this._createModel(); + } this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); @@ -206,7 +210,6 @@ export class ModelComponent extends RenderableComponent { protected _createModel () { if (!this.node.scene) { return; } const scene = this._getRenderScene(); - if (this._model && scene.models.find((c) => c === this._model)) { return; } this._model = scene.createModel(this._getModelConstructor(), this.node); } diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts index 1f9a8c63aa..7b7ab856d5 100644 --- a/cocos/3d/framework/physics/body.ts +++ b/cocos/3d/framework/physics/body.ts @@ -1,10 +1,10 @@ import CANNON from 'cannon'; +import { Quat } from '../../../core/value-types'; import Vec3 from '../../../core/value-types/vec3'; import { vec3 } from '../../../core/vmath'; import { Node } from '../../../scene-graph/node'; import { PhysicsMaterial as PhysicsMaterial } from '../../assets/physics/material'; -import { setWrap, getWrap } from './util'; -import { Quat } from '../../../core/value-types'; +import { getWrap, setWrap } from './util'; export enum DataFlow { PUSHING, @@ -32,7 +32,9 @@ export class PhysicsBody { private _useGravity = true; - constructor() { + private _velocity = new Vec3(); + + constructor () { const cannonBodyOptions: CANNON.IBodyOptions = { mass: 0, // material: new CANNON.Material(''), @@ -50,16 +52,16 @@ export class PhysicsBody { }; } - public bind(node: Node) { + public bind (node: Node) { this._node = node; this.pullTransform(); } - public destroy() { + public destroy () { this._cannonBody.removeEventListener('collide', this._onCollidedListener); } - public _onAdded() { + public _onAdded () { this.pullTransform(); this._onWorldBeforeStepListener = this._onWorldBeforeStep.bind(this); @@ -69,7 +71,7 @@ export class PhysicsBody { this._cannonBody.world.addEventListener('postStep', this._onWorldPostStepListener); } - public _onRemoved() { + public _onRemoved () { if (this._cannonBody.world) { if (this._onWorldPostStepListener) { this._cannonBody.world.removeEventListener('postStep', this._onWorldPostStepListener); @@ -83,11 +85,11 @@ export class PhysicsBody { } } - public _getCannonBody() { + public _getCannonBody () { return this._cannonBody; } - public addShape(shape: PhysicsShape) { + public addShape (shape: PhysicsShape) { // if (this._node) { // shape.__debugNodeName = this._node.name; // } @@ -99,11 +101,11 @@ export class PhysicsBody { this.commitShapesUpdate(); } - public removeShape(shape: PhysicsShape) { + public removeShape (shape: PhysicsShape) { throw new Error(`not impl`); } - public getCenter(shape: PhysicsShape) { + public getCenter (shape: PhysicsShape) { const iShape = this._cannonBody.shapes.indexOf(shape._getCannonShape()); if (iShape >= 0) { const shapeOffset = this._cannonBody.shapeOffsets[iShape]; @@ -112,26 +114,32 @@ export class PhysicsBody { throw new Error(`shape not found.`); } - get velocity() { - return this._cannonBody.velocity; + get velocity () { + vec3.copy(this._velocity, this._cannonBody.velocity); + return this._velocity; } - get force() { + set velocity (value: Vec3) { + vec3.set(this._velocity, value.x, value.y, value.z); + vec3.copy(this._cannonBody.velocity, this._velocity); + } + + get force () { return this._cannonBody.force; } - public applyForce(force: Vec3, position?: Vec3) { + public applyForce (force: Vec3, position?: Vec3) { if (!position) { position = this._cannonBody.position; } this._cannonBody.applyForce(force, position); } - get material() { + get material () { return this._material; } - set material(value) { + set material (value) { this._material = value; if (!this._material) { return; @@ -140,11 +148,11 @@ export class PhysicsBody { this._cannonBody.material = this._material._getImpl(); } - get mass() { + get mass () { return this._cannonBody.mass; } - set mass(value) { + set mass (value) { this._cannonBody.mass = value; this._cannonBody.updateMassProperties(); if (this._cannonBody.type !== CANNON.Body.KINEMATIC) { @@ -153,11 +161,11 @@ export class PhysicsBody { } } - get isKinematic() { + get isKinematic () { return this._cannonBody.type === CANNON.Body.KINEMATIC; } - set isKinematic(value) { + set isKinematic (value) { if (value) { this._cannonBody.type = CANNON.Body.KINEMATIC; } else { @@ -166,11 +174,11 @@ export class PhysicsBody { this._onBodyTypeUpdated(); } - get useGravity() { + get useGravity () { return this._useGravity; } - set useGravity(value) { + set useGravity (value) { this._useGravity = value; if (this._useGravity) { this._cannonBody.world.removeEventListener('beforeStep', this._cancelGravityListener); @@ -179,40 +187,40 @@ export class PhysicsBody { } } - get freezeRotation() { + get freezeRotation () { return this._cannonBody.fixedRotation; } - set freezeRotation(value) { + set freezeRotation (value) { this._cannonBody.fixedRotation = value; this._cannonBody.updateMassProperties(); } - get linearDamping() { + get linearDamping () { return this._cannonBody.linearDamping; } - set linearDamping(value) { + set linearDamping (value) { this._cannonBody.linearDamping = value; } - get angularDamping() { + get angularDamping () { return this._cannonBody.angularDamping; } - set angularDamping(value) { + set angularDamping (value) { this._cannonBody.angularDamping = value; } - get isTrigger() { + get isTrigger () { return this._cannonBody.collisionResponse; } - set isTrigger(value) { + set isTrigger (value) { this._cannonBody.collisionResponse = value; } - get dataFlow() { + get dataFlow () { return this._dataflow; } @@ -221,24 +229,24 @@ export class PhysicsBody { * @param {number} group The group which this body will be put into. * @param {number} mask The groups which this body can collide with. */ - public setCollisionFilter(group: number, mask: number) { + public setCollisionFilter (group: number, mask: number) { this._cannonBody.collisionFilterGroup = group; this._cannonBody.collisionFilterMask = mask; } - public setWorldPosition(position: Vec3) { + public setWorldPosition (position: Vec3) { this._cannonBody.position.set(position.x, position.y, position.z); } - public setWorldScale(scale: Vec3) { + public setWorldScale (scale: Vec3) { this._pullScale(scale); } - public setWorldRotation(rotation: Quat) { + public setWorldRotation (rotation: Quat) { this._cannonBody.quaternion.set(rotation.x, rotation.y, rotation.z, rotation.w); } - public pullTransform() { + public pullTransform () { if (!this._node) { return; } @@ -254,7 +262,7 @@ export class PhysicsBody { * Is this body currently in contact with the specified body? * @param {CannonBody} body The body to test against. */ - public isInContactWith(body: PhysicsBody) { + public isInContactWith (body: PhysicsBody) { if (!this._cannonBody.world) { return false; } @@ -263,21 +271,21 @@ export class PhysicsBody { this._cannonBody.id, body._cannonBody.id) > 0; } - public commitShapesUpdate() { + public commitShapesUpdate () { this._cannonBody.updateBoundingRadius(); } - private _onCollided(event: CANNON.ICollisionEvent) { + private _onCollided (event: CANNON.ICollisionEvent) { // console.log(`Collided {${getWrap(event.body)._node.name}} and {${getWrap(event.target)._node.name}}.`); } - private _onWorldBeforeStep(event: CANNON.IEvent) { + private _onWorldBeforeStep (event: CANNON.IEvent) { if (this._dataflow === DataFlow.PULLING) { this._pull(); } } - private _onWorldPostStep(event: CANNON.IEvent) { + private _onWorldPostStep (event: CANNON.IEvent) { if (this._dataflow === DataFlow.PUSHING) { this._push(); } @@ -286,7 +294,7 @@ export class PhysicsBody { /** * Pull node's transform information into rigidbody. */ - private _pull() { + private _pull () { if (!this._node) { return; } @@ -298,7 +306,7 @@ export class PhysicsBody { this.pullTransform(); } - private _pullScale(scale: Vec3) { + private _pullScale (scale: Vec3) { let shapeUpdated = false; this._shapes.forEach((shape) => { let calcShapeOffset = false; @@ -329,7 +337,7 @@ export class PhysicsBody { /** * Push the rigidbody's transform information back to node. */ - private _push() { + private _push () { if (!this._node) { return; } @@ -342,15 +350,15 @@ export class PhysicsBody { } } - private _resetBodyTypeAccordingMess() { + private _resetBodyTypeAccordingMess () { if (this.mass <= 0) { this._cannonBody.type = CANNON.Body.STATIC; } else { - this._cannonBody.type = CANNON.Body.DYNAMIC + this._cannonBody.type = CANNON.Body.DYNAMIC; } } - private _onBodyTypeUpdated() { + private _onBodyTypeUpdated () { if (this._cannonBody.type !== CANNON.Body.STATIC) { this._dataflow = DataFlow.PUSHING; } else { @@ -360,62 +368,62 @@ export class PhysicsBody { } export class PhysicsShape { + + public get center () { + return this._center; + } + + public set center (value) { + vec3.copy(this._center, value); + } + + public get scale () { + return this._scale; + } + + public set scale (value) { + vec3.copy(this._scale, value); + this._onShapeParamUpdated(); + } + + public _centerChanged = true; // public __debugNodeName: string = ''; private _scale: Vec3 = new Vec3(1.0, 1.0, 1.0); private _center: Vec3 = new Vec3(0, 0, 0); - public _centerChanged = true; - - public get center() { - return this._center; - } - - public set center(value) { - vec3.copy(this._center, value); - } - - constructor(private _cannonShape: CANNON.Shape) { + constructor (private _cannonShape: CANNON.Shape) { setWrap(this._cannonShape, this); } - public get scale() { - return this._scale; - } - - public set scale(value) { - vec3.copy(this._scale, value); - this._onShapeParamUpdated(); - } - - public _getCannonShape() { + public _getCannonShape () { return this._cannonShape as T; } - protected _onShapeParamUpdated() { + protected _onShapeParamUpdated () { } } export class PhysicsBoxShape extends PhysicsShape { private _size: Vec3; - constructor(size: Vec3) { + constructor (size: Vec3) { super(new CANNON.Box(new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2))); this._size = new Vec3(size.x, size.y, size.z); } - public get size() { + public get size () { return this._size; } - public set size(value) { + public set size (value) { vec3.copy(this._size, value); this._onShapeParamUpdated(); } - protected _onShapeParamUpdated() { + protected _onShapeParamUpdated () { const shape = this._getCannonShape(); if (!shape.halfExtents) { shape.halfExtents = new CANNON.Vec3(); @@ -434,22 +442,22 @@ export class PhysicsBoxShape extends PhysicsShape { export class PhysicsSphereShape extends PhysicsShape { private _radius: number; - constructor(radius: number) { + constructor (radius: number) { super(new CANNON.Sphere(radius)); this._radius = radius; } - public get radius() { + public get radius () { return this._radius; } - public set radius(value) { + public set radius (value) { this._radius = value; this._onShapeParamUpdated(); } - protected _onShapeParamUpdated() { + protected _onShapeParamUpdated () { const shape = this._getCannonShape(); shape.radius = this._radius * maxComponent(this.scale); // shape.updateBoundingSphereRadius(); @@ -458,6 +466,6 @@ export class PhysicsSphereShape extends PhysicsShape { } } -function maxComponent(v: { x: number, y: number, z: number }) { +function maxComponent (v: { x: number, y: number, z: number }) { return Math.max(v.x, Math.max(v.y, v.z)); } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index f1c856df6f..1205e7cf91 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -18,7 +18,6 @@ export class RenderableComponent extends Component { } @property({ - default: [], type: Material, displayName: 'Materials', }) diff --git a/cocos/3d/primitive/plane.js b/cocos/3d/primitive/plane.js deleted file mode 100644 index 0b2828a0d2..0000000000 --- a/cocos/3d/primitive/plane.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -import { vec3 } from '../../core/vmath'; - -let temp1 = vec3.create(0, 0, 0); -let temp2 = vec3.create(0, 0, 0); -let temp3 = vec3.create(0, 0, 0); -let r = vec3.create(0, 0, 0); -let c00 = vec3.create(0, 0, 0); -let c10 = vec3.create(0, 0, 0); -let c01 = vec3.create(0, 0, 0); - -/** - * @param {Number} width - * @param {Number} length - * @param {Object} opts - * @param {Number} opts.widthSegments - * @param {Number} opts.lengthSegments - */ -export default function (width = 10, length = 10, opts = {}) { - let uSegments = opts.widthSegments !== undefined ? opts.widthSegments : 10; - let vSegments = opts.lengthSegments !== undefined ? opts.lengthSegments : 10; - - let hw = width * 0.5; - let hl = length * 0.5; - - let positions = []; - let normals = []; - let uvs = []; - let indices = []; - let minPos = vec3.create(-hw, 0, -hl); - let maxPos = vec3.create(hw, 0, hl); - let boundingRadius = Math.sqrt(width * width + length * length); - - vec3.set(c00, -hw, 0, hl); - vec3.set(c10, hw, 0, hl); - vec3.set(c01, -hw, 0, -hl); - - for (let y = 0; y <= vSegments; y++) { - for (let x = 0; x <= uSegments; x++) { - let u = x / uSegments; - let v = y / vSegments; - - vec3.lerp(temp1, c00, c10, u); - vec3.lerp(temp2, c00, c01, v); - vec3.sub(temp3, temp2, c00); - vec3.add(r, temp1, temp3); - - positions.push(r.x, r.y, r.z); - normals.push(0, 1, 0); - uvs.push(u, v); - - if ((x < uSegments) && (y < vSegments)) { - let useg1 = uSegments + 1; - let a = x + y * useg1; - let b = x + (y + 1) * useg1; - let c = (x + 1) + (y + 1) * useg1; - let d = (x + 1) + y * useg1; - - indices.push(a, d, b); - indices.push(d, c, b); - } - } - } - - return { - positions, - normals, - uvs, - indices, - minPos, - maxPos, - boundingRadius - }; -} diff --git a/cocos/3d/primitive/plane.ts b/cocos/3d/primitive/plane.ts new file mode 100644 index 0000000000..7b5ede6391 --- /dev/null +++ b/cocos/3d/primitive/plane.ts @@ -0,0 +1,124 @@ +import { Vec3 } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; + +interface IPlaneOptions extends RecursivePartial { + /** + * Plane extent on X-axis. + */ + width: number; + + /** + * Plane extent on Z-axis. + */ + length: number; + + /** + * Segment count on X-axis. + */ + widthSegments: number; + + /** + * Segment count on Z-axis. + */ + lengthSegments: number; +} + +function applyDefaultPlaneOptions (options?: RecursivePartial): IPlaneOptions { + options = applyDefaultGeometryOptions(options); + options.width = 10; + options.length = 10; + options.widthSegments = 10; + options.lengthSegments = 10; + return options as IPlaneOptions; +} + +const temp1 = vec3.create(0, 0, 0); +const temp2 = vec3.create(0, 0, 0); +const temp3 = vec3.create(0, 0, 0); +const r = vec3.create(0, 0, 0); +const c00 = vec3.create(0, 0, 0); +const c10 = vec3.create(0, 0, 0); +const c01 = vec3.create(0, 0, 0); + +/** + * This function generates a plane on XOZ plane with positive Y direction. + * @param options Options. + */ +export default function (options?: IPlaneOptions): IGeometry { + const normalizedOptions = applyDefaultPlaneOptions(options); + + const { + width, + length, + widthSegments: uSegments, + lengthSegments: vSegments, + } = normalizedOptions; + + const hw = width * 0.5; + const hl = length * 0.5; + + const positions: number[] = []; + const uvs: number[] = []; + const indices: number[] = []; + const minPos = new Vec3(-hw, 0, -hl); + const maxPos = new Vec3(hw, 0, hl); + const boundingRadius = Math.sqrt(width * width + length * length); + + vec3.set(c00, -hw, 0, hl); + vec3.set(c10, hw, 0, hl); + vec3.set(c01, -hw, 0, -hl); + + for (let y = 0; y <= vSegments; y++) { + for (let x = 0; x <= uSegments; x++) { + const u = x / uSegments; + const v = y / vSegments; + + vec3.lerp(temp1, c00, c10, u); + vec3.lerp(temp2, c00, c01, v); + vec3.sub(temp3, temp2, c00); + vec3.add(r, temp1, temp3); + + positions.push(r.x, r.y, r.z); + if (normalizedOptions.includeUV) { + uvs.push(u, v); + } + + if ((x < uSegments) && (y < vSegments)) { + const useg1 = uSegments + 1; + const a = x + y * useg1; + const b = x + (y + 1) * useg1; + const c = (x + 1) + (y + 1) * useg1; + const d = (x + 1) + y * useg1; + + indices.push(a, d, b); + indices.push(d, c, b); + } + } + } + + const result: IGeometry = { + positions, + indices, + minPos, + maxPos, + boundingRadius, + }; + + if (normalizedOptions.includeNormal) { + const nVertex = (vSegments + 1) * (uSegments + 1); + const normals = new Array(3 * nVertex); + result.normals = normals; + for (let i = 0; i < nVertex; ++i) { + normals[i * 3 + 0] = 0; + normals[i * 3 + 1] = 1; + normals[i * 3 + 2] = 0; + } + } + + if (normalizedOptions.includeUV) { + result.uvs = uvs; + } + + return result; +} diff --git a/cocos/3d/primitive/transform.ts b/cocos/3d/primitive/transform.ts index 57eb6bd39f..f5e536cafa 100644 --- a/cocos/3d/primitive/transform.ts +++ b/cocos/3d/primitive/transform.ts @@ -44,3 +44,31 @@ export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: geometry.boundingRadius = Math.max(Math.max(x, y), z); return geometry; } + +export function wireframed (geometry: IGeometry) { + const { indices } = geometry; + if (!indices) { + return geometry; + } + + const offsets = [[0, 1], [1, 2], [2, 0]]; + const lines: number[] = []; + const lineIDs = {}; + + for (let i = 0; i < indices.length; i += 3) { + for (let k = 0; k < 3; ++k) { + const i1 = indices[i + offsets[k][0]]; + const i2 = indices[i + offsets[k][1]]; + + // check if we already have the line in our lines + const id = (i1 > i2) ? ((i2 << 16) | i1) : ((i1 << 16) | i2); + if (lineIDs[id] === undefined) { + lineIDs[id] = 0; + lines.push(i1, i2); + } + } + } + + geometry.indices = lines; + return geometry; + } diff --git a/cocos/3d/ui/assembler/assembler.ts b/cocos/3d/ui/assembler/assembler.ts index be2e5b929f..7a0518cd34 100644 --- a/cocos/3d/ui/assembler/assembler.ts +++ b/cocos/3d/ui/assembler/assembler.ts @@ -26,17 +26,19 @@ import { UIRenderComponent } from '../components/ui-render-component'; import { RenderData } from '../../../renderer/ui/renderData'; import { UI } from '../../../renderer/ui/ui'; +import { ISharedLabelData } from './label/ttfUtils'; export interface IAssembler { - useModel: boolean; + useModel?: boolean; fillBuffers (component: UIRenderComponent, render: UI): void; updateRenderData? (component: UIRenderComponent): void; createData? (component: UIRenderComponent): RenderData; updateVerts? (component: UIRenderComponent, start?: number, end?: number): void; updateWorldVerts? (component: UIRenderComponent): void; updateUVs?(component: UIRenderComponent, start?: number, end?: number); - getAssemblerData?(): void; + getAssemblerData?(): ISharedLabelData; + resetAssemblerData?(assemblerData: ISharedLabelData):void } export interface IAssemblerManager { diff --git a/cocos/3d/ui/assembler/label/ttf.ts b/cocos/3d/ui/assembler/label/ttf.ts index 90b1e1800b..6d100fa26f 100644 --- a/cocos/3d/ui/assembler/label/ttf.ts +++ b/cocos/3d/ui/assembler/label/ttf.ts @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -import ttfUtls from '../../../../2d/renderer/utils/label/ttf'; +import { ttfUtils } from './ttfUtils'; import * as js from '../../../../core/utils/js'; import { RenderData } from '../../../../renderer/ui/renderData'; import { UI, IUIRenderData } from '../../../../renderer/ui/ui'; @@ -76,10 +76,10 @@ export const ttf: IAssembler = { const renderData: RenderData|null = comp.renderData; const node = comp.node; - const width = node.width; - const height = node.height; - const appx = node.anchorX * width; - const appy = node.anchorY * height; + const width = node.width!; + const height = node.height!; + const appx = node.anchorX! * width; + const appy = node.anchorY! * height; const datas = renderData!.datas; datas[0].x = -appx; @@ -93,4 +93,4 @@ export const ttf: IAssembler = { }, }; -js.addon(ttf, ttfUtls); +js.addon(ttf, ttfUtils); diff --git a/cocos/2d/renderer/utils/label/ttf.js b/cocos/3d/ui/assembler/label/ttfUtils.ts similarity index 86% rename from cocos/2d/renderer/utils/label/ttf.js rename to cocos/3d/ui/assembler/label/ttfUtils.ts index 718b1ed788..8aca91df24 100644 --- a/cocos/2d/renderer/utils/label/ttf.js +++ b/cocos/3d/ui/assembler/label/ttfUtils.ts @@ -26,34 +26,36 @@ import macro from '../../../../core/platform/CCMacro'; import * as textUtils from '../../../../core/utils/text-utils'; import { Component } from '../../../../components/component'; -import { LabelComponent } from '../../../../3d/ui/components/label-component'; -import { LabelOutline } from '../../../label/label-outline'; +import { LabelComponent } from '../../components/label-component'; +import { LabelOutline } from '../../../../2d/label/label-outline'; +import { SpriteFrame } from '../../../../assets/CCSpriteFrame'; +import { Size, Color } from '../../../../core/value-types'; const Overflow = LabelComponent.Overflow; const WHITE = cc.Color.WHITE; const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component); -let _context = null; -let _canvas = null; -let _texture = null; +let _context: CanvasRenderingContext2D | null = null; +let _canvas: HTMLCanvasElement | null = null; +let _texture: SpriteFrame | null = null; let _fontDesc = ''; let _string = ''; let _fontSize = 0; let _drawFontsize = 0; -let _splitedStrings = []; -let _canvasSize = cc.size(); +let _splitedStrings: string[] = []; +let _canvasSize = new Size(); let _lineHeight = 0; let _hAlign = 0; let _vAlign = 0; -let _color = null; +let _color = new Color(); let _fontFamily = ''; let _overflow = Overflow.NONE; let _isWrapText = false; // outline let _isOutlined = false; -let _outlineColor = null; +let _outlineColor = new Color(); let _outlineWidth = 0; let _margin = 0; @@ -61,10 +63,16 @@ let _isBold = false; let _isItalic = false; let _isUnderline = false; -let _sharedLabelData; +// let _sharedLabelData; // -let _canvasPool = { +interface ICanvasPool { + pool: ISharedLabelData[], + get(): ISharedLabelData, + put(canvas: ISharedLabelData):void, +} + +let _canvasPool: ICanvasPool = { pool: [], get() { let data = this.pool.pop(); @@ -80,7 +88,7 @@ let _canvasPool = { return data; }, - put(canvas) { + put(canvas: ISharedLabelData) { if (this.pool.length >= 32) { return; } @@ -88,8 +96,13 @@ let _canvasPool = { } }; +export interface ISharedLabelData { + canvas: HTMLCanvasElement, + context: CanvasRenderingContext2D | null +} -export default { + +export const ttfUtils = { getAssemblerData() { // if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { // _sharedLabelData = _canvasPool.get(); @@ -107,14 +120,14 @@ export default { return sharedLabelData; }, - _resetAssemblerData(assemblerData) { + resetAssemblerData(assemblerData: ISharedLabelData) { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS && assemblerData) { _canvasPool.put(assemblerData); } }, - updateRenderData(comp) { - if (!comp._renderData.vertDirty) return; + updateRenderData(comp: LabelComponent) { + if (!comp.renderData||!comp.renderData.vertDirty) return; this._updateFontFamly(comp); this._updateProperties(comp); @@ -122,24 +135,24 @@ export default { this._calculateSplitedStrings(); this._updateLabelDimensions(); this._calculateTextBaseline(); - this._updateTexture(comp); + this._updateTexture(); comp._actualFontSize = _fontSize; comp.node.setContentSize(_canvasSize); this.updateVerts(comp); - comp._renderData.vertDirty = comp._renderData.uvDirty = false; + comp.markForUpdateRenderData(false); _context = null; _canvas = null; _texture = null; }, - updateVerts() { + updateVerts(comp: LabelComponent) { }, - _updateFontFamly(comp) { + _updateFontFamly(comp: LabelComponent) { if (!comp.useSystemFont) { if (comp.font) { if (comp.font._nativeAsset) { @@ -148,7 +161,7 @@ export default { else { cc.loader.load(comp.font.nativeUrl, function (err, fontFamily) { _fontFamily = fontFamily || 'Arial'; - comp._updateRenderData(true); + comp.updateRenderData(true); }); } } @@ -161,22 +174,26 @@ export default { } }, - _updateProperties(comp) { - let assemblerData = comp._assemblerData; + _updateProperties(comp: LabelComponent) { + let assemblerData = comp.assemblerData; + if(!assemblerData){ + return; + } + _context = assemblerData.context; _canvas = assemblerData.canvas; - _texture = comp._texture; + _texture = comp.texture; _string = comp.string.toString(); _fontSize = comp._fontSize; _drawFontsize = _fontSize; _overflow = comp.overflow; - _canvasSize.width = comp.node.width; - _canvasSize.height = comp.node.height; + _canvasSize.width = comp.node.width!; + _canvasSize.height = comp.node.height!; _lineHeight = comp._lineHeight; _hAlign = comp.horizontalAlign; _vAlign = comp.verticalAlign; - _color = comp._color; + _color = comp.color; _isBold = comp._isBold; _isItalic = comp._isItalic; _isUnderline = comp._isUnderline; @@ -196,9 +213,9 @@ export default { if (outline && outline.enabled) { _isOutlined = true; _margin = _outlineWidth = outline.width; - _outlineColor = cc.color(outline.color); + _outlineColor = outline.color.clone(); // TODO: temporary solution, cascade opacity for outline color - _outlineColor.a = _outlineColor.a * comp.node.color.a / 255.0; + _outlineColor.a = _outlineColor.a * comp.color.a / 255.0; } else { _isOutlined = false; @@ -236,6 +253,10 @@ export default { }, _updateTexture() { + if (!_context || !_canvas){ + return; + } + _context.clearRect(0, 0, _canvas.width, _canvas.height); _context.font = _fontDesc; @@ -270,7 +291,9 @@ export default { } // _texture.handleLoadedTexture(); - _texture.mipmaps = [_texture.image]; + if (_texture) { + _texture.mipmaps = [_texture.image!]; + } }, _calculateUnderlineStartPosition() { @@ -318,12 +341,16 @@ export default { } } + if(!_canvas){ + return; + } + _canvas.width = _canvasSize.width; _canvas.height = _canvasSize.height; }, _calculateTextBaseline() { - let node = this._node; + // let node = this._node; let hAlign; let vAlign; @@ -336,7 +363,6 @@ export default { else { hAlign = 'left'; } - _context.textAlign = hAlign; if (_vAlign === macro.VerticalTextAlignment.TOP) { vAlign = 'top'; @@ -347,7 +373,11 @@ export default { else { vAlign = 'bottom'; } - _context.textBaseline = vAlign; + + if (_context) { + _context.textAlign = hAlign; + _context.textBaseline = vAlign; + } }, _calculateSplitedStrings() { @@ -361,7 +391,7 @@ export default { let textFragment = textUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, - this._measureText(_context)); + this._measureText(_context!)); _splitedStrings = _splitedStrings.concat(textFragment); } } @@ -392,24 +422,28 @@ export default { return nodeSpacingY | 0; }, - _calculateParagraphLength(paragraphedStrings, ctx) { - let paragraphLength = []; + _calculateParagraphLength(paragraphedStrings: string[], ctx: CanvasRenderingContext2D) { + let paragraphLength: number[] = []; for (let i = 0; i < paragraphedStrings.length; ++i) { - let width = textUtils.safeMeasureText(ctx, paragraphedStrings[i]); + let width: number = textUtils.safeMeasureText(ctx, paragraphedStrings[i]); paragraphLength.push(width); } return paragraphLength; }, - _measureText(ctx) { + _measureText(ctx: CanvasRenderingContext2D) { return function (string) { return textUtils.safeMeasureText(ctx, string); }; }, _calculateLabelFont() { + if(!_context){ + return; + } + _fontDesc = this._getFontDesc(); _context.font = _fontDesc; diff --git a/cocos/3d/ui/assembler/mask-assembler.ts b/cocos/3d/ui/assembler/mask-assembler.ts index 2b2f09747f..d4aa731232 100644 --- a/cocos/3d/ui/assembler/mask-assembler.ts +++ b/cocos/3d/ui/assembler/mask-assembler.ts @@ -125,8 +125,8 @@ export const maskAssembler: IAssembler = { fillBuffers (mask: MaskComponent, ui: UI) { stencilManager.enter(mask); - const maskGeometry = mask._getMaskGeometry(); - const maskMaterial = mask._getMaskMaterial(); + const maskGeometry = mask.getMaskGeometry(); + const maskMaterial = mask.getMaskMaterial(); if (maskGeometry && maskMaterial) { const meshBuffer = createMeshBuffer(ui, maskGeometry); const nVert = Math.floor(maskGeometry.positions.length / 3); @@ -154,8 +154,8 @@ export const maskEndAssembler: IAssembler = { fillBuffers (mask: MaskComponent, ui: UI) { stencilManager.exit(); - const clearGeometry = mask._getClearGeometry(); - const clearMaterial = mask._getClearMaterial(); + const clearGeometry = mask.getClearGeometry(); + const clearMaterial = mask.getClearMaterial(); if (clearGeometry && clearMaterial) { const meshBuffer = createMeshBuffer(ui, clearGeometry); meshBuffer.vData!.set(clearGeometry.positions); diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/3d/ui/assembler/sprite/sliced.ts index af4bc1443d..b663efd743 100644 --- a/cocos/3d/ui/assembler/sprite/sliced.ts +++ b/cocos/3d/ui/assembler/sprite/sliced.ts @@ -70,7 +70,7 @@ export const sliced: IAssembler = { if (renderData && frame) { const vertDirty = renderData.vertDirty; if (vertDirty) { - this.updateVerts(sprite); + this.updateVerts!(sprite); this.updateWorldVerts!(sprite); } } @@ -80,10 +80,10 @@ export const sliced: IAssembler = { const renderData: RenderData | null = sprite.renderData; const datas: IRenderData[] = renderData!.datas; const node: Node = sprite.node; - const width = node.width; - const height = node.height; - const appx = node.anchorX * width; - const appy = node.anchorY * height; + const width = node.width!; + const height = node.height!; + const appx = node.anchorX! * width; + const appy = node.anchorY! * height; const frame: SpriteFrame|null = sprite.spriteFrame; const leftWidth = frame!.insetLeft; @@ -142,8 +142,7 @@ export const sliced: IAssembler = { // const uintbuf = buffer._uintVData, const ibuf: Uint16Array|null = buffer.iData; - // for (let i = 4; i < 20; ++i) { - for (let i = 4; i < 16; ++i) { + for (let i = 4; i < 20; ++i) { const vert = datas[i]; const uvs = uvSliced[i - 4]; diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts index 0da8e7e80d..f5dac4c178 100644 --- a/cocos/3d/ui/components/button-component.ts +++ b/cocos/3d/ui/components/button-component.ts @@ -28,14 +28,15 @@ import { SpriteFrame } from '../../../assets/CCSpriteFrame'; import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import Event from '../../../core/event/event'; -import { EventTouch } from '../../../core/platform/event-manager'; +import { EventTouch, EventMouse } from '../../../core/platform/event-manager'; import { lerp } from '../../../core/utils/misc'; -import { Color, Enum, Vec3 } from '../../../core/value-types/index'; +import { Color, Vec3 } from '../../../core/value-types/index'; +import { ccenum } from '../../../core/value-types/enum'; import * as math from '../../../core/vmath/index'; import { Node } from '../../../scene-graph'; import { SpriteComponent } from './sprite-component'; import { UIRenderComponent } from './ui-render-component'; +import { EventType } from '../../../scene-graph/node-event-enum'; /** * !#en Enum for transition type. @@ -71,7 +72,14 @@ enum Transition { SCALE = 3, } -Enum(Transition); +ccenum(Transition); + +enum State { + NORMAL = 'normal', + HOVER = 'hover', + PRESSED = 'pressed', + DISABLED = 'disabled', +}; /** * !#en @@ -117,7 +125,7 @@ Enum(Transition); * @example * * // Add an event to the button. - * button.node.on(cc.Node.EventType.TOUCH_START, function (event) { + * button.node.on(EventType.TOUCH_START, function (event) { * cc.log("This is a callback after the trigger event"); * }); * // You could also add a click event @@ -149,14 +157,14 @@ export class ButtonComponent extends Component { } set interactable (value: boolean) { - if (CC_EDITOR) { - if (value) { - this._previousNormalSprite = this.normalSprite; - } else { - this.normalSprite = this._previousNormalSprite; - } - } - this._interactable = !this._interactable; + // if (CC_EDITOR) { + // if (value) { + // this._previousNormalSprite = this.normalSprite; + // } else { + // this.normalSprite = this._previousNormalSprite; + // } + // } + this._interactable = value; this._updateState(); if (!this._interactable) { @@ -175,6 +183,7 @@ export class ButtonComponent extends Component { * !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰 * @property {Boolean} enableAutoGrayEffect */ + // TODO: // enableAutoGrayEffect: { // default: false, // tooltip: CC_DEV && 'i18n:COMPONENT.button.auto_gray_effect', @@ -297,7 +306,7 @@ export class ButtonComponent extends Component { return; } - this._duration = 0.1; + this._duration = value; } /** @@ -332,12 +341,17 @@ export class ButtonComponent extends Component { return this._normalSprite; } - set normalSprite (value: SpriteFrame) { + set normalSprite (value: SpriteFrame | null) { if (this._normalSprite === value) { return; } this._normalSprite = value; + const sprite = this.node.getComponent(SpriteComponent); + if(sprite){ + sprite.spriteFrame = value; + } + this._updateState(); } @@ -353,7 +367,7 @@ export class ButtonComponent extends Component { return this._pressedSprite; } - set pressedSprite (value: SpriteFrame) { + set pressedSprite (value: SpriteFrame | null) { if (this._pressedSprite === value) { return; } @@ -374,7 +388,7 @@ export class ButtonComponent extends Component { return this._hoverSprite; } - set hoverSprite (value: SpriteFrame) { + set hoverSprite (value: SpriteFrame | null) { if (this._hoverSprite === value) { return; } @@ -395,7 +409,7 @@ export class ButtonComponent extends Component { return this._disabledSprite; } - set disabledSprite (value: SpriteFrame) { + set disabledSprite (value: SpriteFrame | null) { if (this._disabledSprite === value) { return; } @@ -419,7 +433,9 @@ export class ButtonComponent extends Component { * -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 * @property {Node} target */ - @property + @property({ + type: Node + }) get target () { return this._target; } @@ -451,70 +467,69 @@ export class ButtonComponent extends Component { public static Transition = Transition; @property - public _interactable: boolean = true; + private _interactable: boolean = true; @property - public _transition: number = Transition.NONE; + private _transition: number = Transition.NONE; @property - public _normalColor: Color = new Color(214, 214, 214, 255); + private _normalColor: Color = new Color(214, 214, 214, 255); @property - public _hoverColor: Color = new Color(211, 211, 211, 255); + private _hoverColor: Color = new Color(211, 211, 211, 255); @property - public _pressColor: Color = Color.WHITE; + private _pressColor: Color = Color.WHITE; @property - public _disabledColor: Color = new Color(124, 124, 124, 255); + private _disabledColor: Color = new Color(124, 124, 124, 255); @property - public _normalSprite: SpriteFrame | null = null; + private _normalSprite: SpriteFrame | null = null; @property - public _hoverSprite: SpriteFrame | null = null; + private _hoverSprite: SpriteFrame | null = null; @property - public _pressedSprite: SpriteFrame | null = null; + private _pressedSprite: SpriteFrame | null = null; @property - public _disabledSprite: SpriteFrame | null = null; + private _disabledSprite: SpriteFrame | null = null; @property - public _duration: number = 0.1; + private _duration: number = 0.1; @property - public _zoomScale: number = 1.2; + private _zoomScale: number = 1.2; @property - public _target: Node = null; + private _target: Node | null = null; @property - public _clickEvents: ComponentEventHandler[] = []; + private _clickEvents: ComponentEventHandler[] = []; - public _pressed: boolean = false; - public _hovered: boolean = false; - public _fromColor: Color = new Color(); - public _toColor: Color = new Color(); - public _time: number = 0; - public _transitionFinished: boolean = true; - public _fromScale: Vec3 = new Vec3(); - public _toScale: Vec3 = new Vec3(); - public _originalScale: Vec3 = new Vec3(); - public _sprite: SpriteComponent | null = null; - public _previousNormalSprite: SpriteFrame | null = null; - - constructor () { - super(); - if (CC_EDITOR) { - this._previousNormalSprite = null; - } - } + private _pressed: boolean = false; + private _hovered: boolean = false; + private _fromColor: Color = new Color(); + private _toColor: Color = new Color(); + private _time: number = 0; + private _transitionFinished: boolean = true; + private _fromScale: Vec3 = new Vec3(); + private _toScale: Vec3 = new Vec3(); + private _originalScale: Vec3 = new Vec3(); + private _sprite: SpriteComponent | null = null; + private _targetScale: Vec3 = new Vec3(); public __preload () { if (!this.target) { this.target = this.node; } + + const sprite = this.node.getComponent(SpriteComponent); + if (sprite) { + this._normalSprite = sprite.spriteFrame; + } + this._applyTarget(); this._updateState(); } - public _resetState () { + private _resetState () { this._pressed = false; this._hovered = false; - // // Restore button status - const target = this.target; - const renderComp = this.target.getComponent(UIRenderComponent); - const transition = this.transition; - if (transition === Transition.COLOR && this.interactable) { - renderComp.color = this.normalColor; + // Restore button status + const target = this._target; + const renderComp = target.getComponent(UIRenderComponent); + const transition = this._transition; + if (transition === Transition.COLOR && this._interactable) { + renderComp.color = this._normalColor; } else if (transition === Transition.SCALE) { target.scale = this._originalScale; } @@ -538,33 +553,35 @@ export class ButtonComponent extends Component { // if (!CC_EDITOR) { this._registerEvent(); - } else { - this.node.on('spriteframe-changed', (comp) => { - if (this._transition === Transition.SPRITE) { - this._normalSprite = comp.spriteFrame; - } - }, this); } + // else { + // this.node.on('spriteframe-changed', (comp) => { + // if (this._transition === Transition.SPRITE) { + // this._normalSprite = comp.spriteFrame; + // } + // }, this); + // } } public onDisable () { this._resetState(); if (!CC_EDITOR) { - this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this); - this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this); + this.node.off(EventType.TOUCH_START, this._onTouchBegan, this); + this.node.off(EventType.TOUCH_MOVE, this._onTouchMove, this); + this.node.off(EventType.TOUCH_END, this._onTouchEnded, this); + this.node.off(EventType.TOUCH_CANCEL, this._onTouchCancel, this); - this.node.off(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); - this.node.off(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); - } else { - this.node.off('spriteframe-changed'); + this.node.off(EventType.MOUSE_ENTER, this._onMouseMoveIn, this); + this.node.off(EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); } + // else { + // this.node.off('spriteframe-changed'); + // } } public update (dt: number) { - const target = this._target; + const target = this._target? this._target: this.node;; if (this._transitionFinished) { return; } @@ -588,23 +605,24 @@ export class ButtonComponent extends Component { if (this._transition === Transition.COLOR) { renderComp.color = this._fromColor.lerp(this._toColor, ratio); } else if (this.transition === Transition.SCALE) { - // target.scale = lerp(this._fromScale, this._toScale, ratio); - target.scaleX = lerp(this._fromScale.x, this._toScale.x, ratio); - target.scaleY = lerp(this._fromScale.y, this._toScale.y, ratio); + target.getScale(this._targetScale); + this._targetScale.x = lerp(this._fromScale.x, this._toScale.x, ratio); + this._targetScale.y = lerp(this._fromScale.y, this._toScale.y, ratio); + target.setScale(this._targetScale); } } - public _registerEvent () { - this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this); - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this); + private _registerEvent () { + this.node.on(EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(EventType.TOUCH_MOVE, this._onTouchMove, this); + this.node.on(EventType.TOUCH_END, this._onTouchEnded, this); + this.node.on(EventType.TOUCH_CANCEL, this._onTouchCancel, this); - this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); - this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); + this.node.on(EventType.MOUSE_ENTER, this._onMouseMoveIn, this); + this.node.on(EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); } - public _getTargetSprite (target: Node | null) { + private _getTargetSprite (target: Node | null) { let sprite = null; if (target) { sprite = target.getComponent(cc.SpriteComponent); @@ -612,7 +630,7 @@ export class ButtonComponent extends Component { return sprite; } - public _applyTarget () { + private _applyTarget () { this._sprite = this._getTargetSprite(this._target); if (this._target) { math.vec3.copy(this._originalScale, this.target._lscale); @@ -620,7 +638,7 @@ export class ButtonComponent extends Component { } // touch event handler - public _onTouchBegan (event: Event | null) { + private _onTouchBegan(event?: EventTouch) { if (!this._interactable || !this.enabledInHierarchy) { return; } this._pressed = true; @@ -630,7 +648,7 @@ export class ButtonComponent extends Component { }; } - public _onTouchMove (event: Event | null) { + private _onTouchMove(event?: EventTouch) { if (!this._interactable || !this.enabledInHierarchy || !this._pressed) { return; } // mobile phone will not emit _onMouseMoveOut, // so we have to do hit test when touch moving @@ -647,21 +665,22 @@ export class ButtonComponent extends Component { if (this._transition === Transition.SCALE && this._target) { if (hit) { - this._fromScale = this._originalScale; + math.vec3.copy(this._fromScale, this._originalScale); math.vec3.scale(this._toScale, this._originalScale, this._zoomScale); this._transitionFinished = false; } else { this._time = 0; this._transitionFinished = true; - this._target.scaleX = this._originalScale.x; - this._target.scaleY = this._originalScale.y; + if(this._target){ + this._target!.setScale(this._originalScale); + } } } else { let state; if (hit) { - state = 'pressed'; + state = State.PRESSED; } else { - state = 'normal'; + state = State.NORMAL; } this._applyTransition(state); } @@ -671,8 +690,10 @@ export class ButtonComponent extends Component { } } - public _onTouchEnded (event: Event | null) { - if (!this._interactable || !this.enabledInHierarchy) { return; } + private _onTouchEnded(event?: EventTouch) { + if (!this._interactable || !this.enabledInHierarchy) { + return; + } if (this._pressed) { ComponentEventHandler.emitEvents(this._clickEvents, event); @@ -686,14 +707,14 @@ export class ButtonComponent extends Component { }; } - public _onTouchCancel () { + private _onTouchCancel(event?: EventTouch) { if (!this._interactable || !this.enabledInHierarchy) { return; } this._pressed = false; this._updateState(); } - public _onMouseMoveIn () { + private _onMouseMoveIn (event?: EventMouse) { if (this._pressed || !this.interactable || !this.enabledInHierarchy) { return; } if (this._transition === Transition.SPRITE && !this._hoverSprite) { return; } @@ -703,7 +724,7 @@ export class ButtonComponent extends Component { } } - public _onMouseMoveOut () { + private _onMouseMoveOut(event?: EventMouse) { if (this._hovered) { this._hovered = false; this._updateState(); @@ -711,27 +732,25 @@ export class ButtonComponent extends Component { } // state handler - public _updateState () { + private _updateState () { const state = this._getButtonState(); this._applyTransition(state); // this._updateDisabledState(); } - public _getButtonState () { - let state; + private _getButtonState () { + let state = State.NORMAL; if (!this._interactable) { - state = 'disabled'; + state = State.DISABLED; } else if (this._pressed) { - state = 'pressed'; + state = State.PRESSED; } else if (this._hovered) { - state = 'hover'; - } else { - state = 'normal'; + state = State.HOVER; } - return state; + return state.toString(); } - public _updateColorTransition (state: string) { + private _updateColorTransition (state: string) { const color = this[state + 'Color']; const target = this._target; if(!target){ @@ -753,36 +772,40 @@ export class ButtonComponent extends Component { } } - public _updateSpriteTransition (state: string) { + private _updateSpriteTransition (state: string) { const sprite = this[state + 'Sprite']; if (this._sprite && sprite) { this._sprite.spriteFrame = sprite; } } - public _updateScaleTransition (state: string) { - if (state === 'pressed') { + private _updateScaleTransition (state: string) { + if(!this._interactable){ + return; + } + + if (state === State.PRESSED) { this._zoomUp(); } else { this._zoomBack(); } } - public _zoomUp () { + private _zoomUp () { math.vec3.copy(this._fromScale, this._originalScale); math.vec3.scale(this._toScale, this._originalScale, this._zoomScale); this._time = 0; this._transitionFinished = false; } - public _zoomBack () { + private _zoomBack () { math.vec3.copy(this._fromScale, this.target._lscale); math.vec3.copy(this._toScale, this._originalScale); this._time = 0; this._transitionFinished = false; } - public _applyTransition (state: string) { + private _applyTransition (state: string) { const transition = this._transition; if (transition === Transition.COLOR) { this._updateColorTransition(state); @@ -793,7 +816,7 @@ export class ButtonComponent extends Component { } } - public _resizeNodeToTargetNode () { + protected _resizeNodeToTargetNode () { if (CC_EDITOR && this._target) { this.node.setContentSize(this.target.getContentSize()); } @@ -814,6 +837,8 @@ export class ButtonComponent extends Component { // } } +cc.ButtonComponent = ButtonComponent; + /** * !#en * Note: This event is emitted from the node to which the component belongs. diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index eccf9e0c02..499b5f8e92 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -27,11 +27,10 @@ import { CameraComponent } from '../../../3d/framework/camera-component'; import { Component } from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import Rect from '../../../core/value-types/rect'; -import Size from '../../../core/value-types/size'; import { GFXClearFlag } from '../../../gfx/define'; -import { Camera, ICameraInfo } from '../../../renderer/scene/camera'; +import { Camera } from '../../../renderer/scene/camera'; import { Node } from '../../../scene-graph/node'; +import { Color, Rect, Size } from '../../../core/value-types'; /** * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 @@ -51,11 +50,12 @@ export class CanvasComponent extends Component { type: Size, }) get designResolution () { - return cc.size(this._designResolution); + return this._designResolution; } set designResolution (value: Size) { this._designResolution.width = value.width; this._designResolution.height = value.height; + this.node.emit('design-resolution-changed', this._designResolution); this.applySettings(); this.alignWithScreen(); } @@ -96,19 +96,6 @@ export class CanvasComponent extends Component { } } - // /** - // * !#en priority in render - // * !#zh 显示优先级 - // */ - // @property - // get priority () { - // return this._priority; - // } - - // set priority (value: number) { - // this._priority = value; - // } - get visibility () { if (this._camera) { return this._camera.view.visibility; @@ -161,8 +148,6 @@ export class CanvasComponent extends Component { } public __preload () { - // hack - cc.eventManager.setEnabled(true); let cameraNode = new Node('UICamera'); cameraNode.setPosition(0, 0, 1000); this._camera = this._getRenderScene().createCamera({ @@ -174,7 +159,7 @@ export class CanvasComponent extends Component { orthoHeight: 10, far: 4096, near: 0.1, - color: cc.color(0, 0, 0, 255), + color: new Color(0, 0, 0, 255), clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, rect: new Rect(0, 0, 1, 1), depth: 1, diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index 72e04dfb1b..a1106a59c4 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -23,23 +23,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -// @ts-check + import Font from '../../../assets/CCFont'; +import { SpriteFrame } from '../../../assets/CCSpriteFrame'; import { ImageAsset } from '../../../assets/image-asset'; -import { Texture2D } from '../../../assets/texture-2d'; -// import { vec2, vec3, mat4, color4 } from '../../../core/vmath/index'; -import { - ccclass, - executeInEditMode, - executionOrder, - menu, - property, -} from '../../../core/data/class-decorator'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import macro from '../../../core/platform/CCMacro'; import { ccenum } from '../../../core/value-types/enum'; import { UIRenderComponent } from './ui-render-component'; -import { SpriteFrame } from '../../../assets/CCSpriteFrame'; -// import { value } from '../../../core/utils/js'; +import { ISharedLabelData } from '../assembler/label/ttfUtils'; +import { UI } from '../../../renderer/ui/ui'; /** * !#en Enum for text alignment. @@ -115,7 +108,7 @@ enum Overflow { CLAMP = 1, SHRINK = 2, RESIZE_HEIGHT = 3, -}; +} ccenum(Overflow); @@ -150,7 +143,6 @@ ccenum(Overflow); @executionOrder(100) @menu('UI/Label') export class LabelComponent extends UIRenderComponent { - /** * !#en Content string of label. * !#zh 标签显示的文本内容。 @@ -160,14 +152,14 @@ export class LabelComponent extends UIRenderComponent { get string () { return this._string; } - set string (value: string) { + set string (value) { value = value.toString(); if (this._string === value) { return; } this._string = value; - this._updateRenderData(); + this.updateRenderData(); this._checkStringEmpty(); } @@ -183,13 +175,13 @@ export class LabelComponent extends UIRenderComponent { return this._horizontalAlign; } - set horizontalAlign (value: number) { + set horizontalAlign (value) { if (this._horizontalAlign === value) { return; } this._horizontalAlign = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -204,13 +196,13 @@ export class LabelComponent extends UIRenderComponent { return this._verticalAlign; } - set verticalAlign (value: number) { + set verticalAlign (value) { if (this._verticalAlign === value) { return; } this._verticalAlign = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -233,13 +225,13 @@ export class LabelComponent extends UIRenderComponent { return this._fontSize; } - set fontSize (value: number) { + set fontSize (value) { if (this._fontSize === value) { return; } this._fontSize = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -252,13 +244,13 @@ export class LabelComponent extends UIRenderComponent { return this._fontFamily; } - set fontFamily (value: string) { + set fontFamily (value) { if (this._fontFamily === value) { return; } this._fontFamily = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -270,13 +262,13 @@ export class LabelComponent extends UIRenderComponent { get lineHeight () { return this._lineHeight; } - set lineHeight (value: number) { + set lineHeight (value) { if (this._lineHeight === value) { return; } this._lineHeight = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -285,19 +277,19 @@ export class LabelComponent extends UIRenderComponent { * @property {Overflow} overflow */ @property({ - type: Overflow + type: Overflow, }) get overflow () { return this._overflow; } - set overflow(value: Overflow) { + set overflow (value: Overflow) { if (this._overflow === value) { return; } this._overflow = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -309,13 +301,13 @@ export class LabelComponent extends UIRenderComponent { get enableWrapText () { return this._enableWrapText; } - set enableWrapText (value: boolean) { + set enableWrapText (value) { if (this._enableWrapText === value) { return; } this._enableWrapText = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -362,7 +354,7 @@ export class LabelComponent extends UIRenderComponent { // this._fontAtlas = null; this._updateAssembler(); this._applyFontTexture(true); - this._updateRenderData(); + this.updateRenderData(); } /** @@ -375,7 +367,7 @@ export class LabelComponent extends UIRenderComponent { return this._isSystemFontUsed; } - set useSystemFont (value: boolean) { + set useSystemFont (value) { if (this._isSystemFontUsed === value) { return; } @@ -395,7 +387,7 @@ export class LabelComponent extends UIRenderComponent { if (value) { this.font = null; this._updateAssembler(); - this._updateRenderData(); + this.updateRenderData(); this._checkStringEmpty(); } // else if (!this._userDefinedFont) { @@ -409,13 +401,13 @@ export class LabelComponent extends UIRenderComponent { return this._spacingX; } - set spacingX (value: number) { + set spacingX (value) { if (this._spacingX === value) { return; } this._spacingX = value; - this._updateRenderData(); + this.updateRenderData(); } /** @@ -428,7 +420,7 @@ export class LabelComponent extends UIRenderComponent { return this._isBold; } - set isBold (value: boolean) { + set isBold (value) { if (this._isBold === value) { return; } @@ -446,7 +438,7 @@ export class LabelComponent extends UIRenderComponent { return this._isItalic; } - set isItalic (value: boolean) { + set isItalic (value) { if (this._isItalic === value) { return; } @@ -464,7 +456,7 @@ export class LabelComponent extends UIRenderComponent { return this._isUnderline; } - set isUnderline (value: boolean) { + set isUnderline (value) { if (this._isUnderline === value) { return; } @@ -472,55 +464,59 @@ export class LabelComponent extends UIRenderComponent { this._isUnderline = value; } - get texture(){ + get texture (){ return this._texture; } + get assemblerData(){ + return this._assemblerData; + } + public static HorizontalAlign = HorizontalAlign; public static VerticalAlign = VerticalAlign; public static Overflow = Overflow; @property - public _useOriginalSize: boolean = true; + public _useOriginalSize = true; @property - public _string: string = 'label'; + public _string = 'label'; @property - public _horizontalAlign: number = HorizontalAlign.LEFT; + public _horizontalAlign = HorizontalAlign.LEFT; @property - public _verticalAlign: number = VerticalAlign.TOP; + public _verticalAlign = VerticalAlign.TOP; @property - public _actualFontSize: number = 0; + public _actualFontSize = 0; @property - public _fontSize: number = 40; + public _fontSize = 40; @property - public _fontFamily: string = 'Arial'; + public _fontFamily = 'Arial'; @property - public _lineHeight: number = 40; + public _lineHeight = 40; @property public _overflow: Overflow = Overflow.NONE; @property - public _enableWrapText: boolean = true; + public _enableWrapText = true; // // 这个保存了旧项目的 file 数据 // _N$file = null; @property public _font: Font | null = null; @property - public _isSystemFontUsed: boolean = true; + public _isSystemFontUsed = true; @property - public _bmFontOriginalSize: number = -1; + public _bmFontOriginalSize = -1; @property - public _spacingX: number = 0; + public _spacingX = 0; @property - public _isItalic: boolean = false; + public _isItalic = false; @property - public _isBold: boolean = false; + public _isBold = false; @property - public _isUnderline: boolean = false; + public _isUnderline = false; // don't need serialize private _texture: SpriteFrame | null = null; private _ttfTexture: SpriteFrame | null = null; private _userDefinedFont: Font | null = null; - private _assemblerData: object|null = null; + private _assemblerData: ISharedLabelData|null = null; constructor () { super(); @@ -528,8 +524,6 @@ export class LabelComponent extends UIRenderComponent { this._userDefinedFont = null; } - this._assemblerData = null; - this._ttfTexture = null; } @@ -547,7 +541,7 @@ export class LabelComponent extends UIRenderComponent { } this._checkStringEmpty(); - this._updateRenderData(true); + this.updateRenderData(true); // this._updateAssembler(); // this._activateMaterial(); } @@ -558,8 +552,8 @@ export class LabelComponent extends UIRenderComponent { } public onDestroy () { - if (this._assembler && this._assembler._resetAssemblerData) { - this._assembler._resetAssemblerData(this._assemblerData); + if (this._assembler && this._assembler.resetAssemblerData) { + this._assembler.resetAssemblerData(this._assemblerData!); } this._assemblerData = null; @@ -570,25 +564,46 @@ export class LabelComponent extends UIRenderComponent { // this._super(); } - public _canRender () { - // let result = this._super(); - let result = this._enabled; - const font = this.font; - if (font instanceof cc.BitmapFont) { - const spriteFrame = font.spriteFrame; - // cannot be activated if texture not loaded yet - if (!spriteFrame || !spriteFrame.textureLoaded()) { - result = false; - } + public updateAssembler(render: UI) { + if (!this._material) { + return; } - return result; + super.updateAssembler(render); } - public _checkStringEmpty () { + public updateRenderData(force = false) { + const renderData = this._renderData; + if (renderData) { + renderData.vertDirty = true; + renderData.uvDirty = true; + // this.markForUpdateRenderData(true); + } + + if (force) { + this._updateAssembler(); + this._applyFontTexture(force); + } + } + + // private _canRender () { + // // let result = this._super(); + // let result = this._enabled; + // const font = this.font; + // if (font instanceof cc.BitmapFont) { + // const spriteFrame = font.spriteFrame; + // // cannot be activated if texture not loaded yet + // if (!spriteFrame || !spriteFrame.textureLoaded()) { + // result = false; + // } + // } + // return result; + // } + + private _checkStringEmpty () { // this.markForRender(!!this.string); } - public _updateAssembler () { + private _updateAssembler () { const assembler = LabelComponent.Assembler!.getAssembler(this); if (this._assembler !== assembler) { @@ -597,23 +612,33 @@ export class LabelComponent extends UIRenderComponent { } if (!this._renderData) { - if(this._assembler){ - this._renderData = this._assembler!.createData(this); - this._renderData.material = this.material; + if (this._assembler && this._assembler.createData){ + this._renderData = this._assembler.createData(this); + this._renderData.material = this._material; } } } - private _activateMaterial (force: boolean) { - let material = this.material; + protected _updateColor () { + const font = this.font; + if (font instanceof cc.BitmapFont) { + // this._super(); + } else { + this.updateRenderData(false); + // this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; + } + } + + private _activateMaterial (force) { + const material = this._material; // if (material && !force) { // return; // } // if (!material) { // // material = new SpriteMaterial(); - // this.material = cc.builtinResMgr.get('sprite-material'); - // material = this.material; + // this._material = cc.builtinResMgr.get('sprite-material'); + // material = this._material; // } // Setup blend function for premultiplied ttf label texture if (this._texture === this._ttfTexture) { @@ -630,18 +655,18 @@ export class LabelComponent extends UIRenderComponent { // this._updateMaterial(material); } - private _applyFontTexture (force: boolean) { + private _applyFontTexture (force) { const font = this._font; if (font instanceof cc.BitmapFont) { const spriteFrame = font.spriteFrame; const self = this; - const onBMFontTextureLoaded = function () { + const onBMFontTextureLoaded = () => { // TODO: old texture in material have been released by loader self._texture = spriteFrame; self._activateMaterial(force); - if (force) { - self._assembler && self._assembler.updateRenderData(self); + if (force && self._assembler && self._assembler.updateRenderData) { + self._assembler.updateRenderData(self); } }; // cannot be activated if texture not loaded yet @@ -664,40 +689,24 @@ export class LabelComponent extends UIRenderComponent { if (!CC_JSB) { // this._ttfTexture.setPremultiplyAlpha(true); } - this._assemblerData = this._assembler!.getAssemblerData(); - this._ttfTexture!.image = new ImageAsset(this._assemblerData.canvas); + + if (this._assembler && this._assembler.getAssemblerData) { + this._assemblerData = this._assembler.getAssemblerData(); + } + + if (this._assemblerData) { + this._ttfTexture!.image = new ImageAsset(this._assemblerData.canvas); + } // this._ttfTexture.initWithElement(this._assemblerData.canvas); } this._texture = this._ttfTexture; this._activateMaterial(force); - if (force && this._assembler) { + if (force && this._assembler && this._assembler.updateRenderData) { this._assembler.updateRenderData(this); } } } - - protected _updateColor () { - const font = this.font; - if (font instanceof cc.BitmapFont) { - // this._super(); - } else { - this._updateRenderData(false); - // this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; - } - } - - private _updateRenderData (force: boolean = false) { - const renderData = this._renderData; - if (renderData) { - renderData.vertDirty = true; - renderData.uvDirty = true; - // this.markForUpdateRenderData(true); - } - - if (force) { - this._updateAssembler(); - this._applyFontTexture(force); - } - } } + +cc.LabelComponent = LabelComponent; diff --git a/cocos/3d/ui/components/layout-component.ts b/cocos/3d/ui/components/layout-component.ts index c19b245d94..8136f00ef3 100644 --- a/cocos/3d/ui/components/layout-component.ts +++ b/cocos/3d/ui/components/layout-component.ts @@ -26,8 +26,10 @@ import { Component } from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Enum, Size } from '../../../core/value-types'; +import { Size, Vec3, Rect, Vec2 } from '../../../core/value-types'; +import { ccenum } from '../../../core/value-types/enum'; import { Node } from '../../../scene-graph/node'; +import { UITransformComponent } from './ui-transfrom-component'; const NodeEvent = Node.EventType; /** * !#en Enum for Layout type @@ -61,7 +63,7 @@ enum Type { GRID = 3, } -Enum(Type); +ccenum(Type); /** * !#en Enum for Layout Resize Mode @@ -89,7 +91,7 @@ enum ResizeMode { CHILDREN = 2, } -Enum(ResizeMode); +ccenum(ResizeMode); /** * !#en Enum for Grid Layout start axis direction. @@ -112,7 +114,7 @@ enum AxisDirection { VERTICAL = 1, } -Enum(AxisDirection); +ccenum(AxisDirection); /** * !#en Enum for vertical layout direction. @@ -135,7 +137,7 @@ enum VerticalDirection { TOP_TO_BOTTOM = 1, } -Enum(VerticalDirection); +ccenum(VerticalDirection); /** * !#en Enum for horizontal layout direction. @@ -156,7 +158,10 @@ enum HorizontalDirection { RIGHT_TO_LEFT = 1, } -Enum(HorizontalDirection); +ccenum(HorizontalDirection); + +let _tempPos = new Vec3(); +let _tempScale = new Vec3(); /** * !#en @@ -185,15 +190,17 @@ export class LayoutComponent extends Component { * @property {Layout.Type} type * @default Layout.Type.NONE */ - @property - get type () { + @property({ + type: Type + }) + get type() { return this._N$layoutType; } - set type (value) { + set type(value: Type) { this._N$layoutType = value; - if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + if (CC_EDITOR && this._N$layoutType !== Type.NONE && this._resizeMode === ResizeMode.CONTAINER /*&& !cc.engine.isPlaying*/) { // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); // if (reLayouted) { // return; @@ -212,16 +219,16 @@ export class LayoutComponent extends Component { @property({ type: ResizeMode, }) - get resizeMode () { - return this._resize; + get resizeMode() { + return this._resizeMode; } - set resizeMode (value) { - if (this.type === Type.NONE && value === ResizeMode.CHILDREN) { + set resizeMode(value) { + if (this._N$layoutType === Type.NONE && value === ResizeMode.CHILDREN) { return; } - this._resize = value; - if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + this._resizeMode = value; + if (CC_EDITOR && value === ResizeMode.CONTAINER /*&& !cc.engine.isPlaying*/) { // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); // if (reLayouted) { // return; @@ -237,11 +244,11 @@ export class LayoutComponent extends Component { * @default cc.size(40, 40) */ @property - get cellSize () { + get cellSize() { return this._cellSize; } - set cellSize (value: Size) { + set cellSize(value: Size) { if (this._cellSize === value) { return; } @@ -257,17 +264,19 @@ export class LayoutComponent extends Component { * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 * @property {Layout.AxisDirection} startAxis */ - @property - get startAxis () { + @property({ + type: AxisDirection + }) + get startAxis() { return this._startAxis; } - set startAxis (value) { + set startAxis(value) { if (this._startAxis === value) { return; } - if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + if (CC_EDITOR && this._resizeMode === ResizeMode.CONTAINER && !cc.engine.isPlaying) { // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); // if (reLayouted) { // return; @@ -283,10 +292,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingLeft */ @property - get paddingLeft () { + get paddingLeft() { return this._paddingLeft; } - set paddingLeft (value) { + set paddingLeft(value) { if (this._paddingLeft === value) { return; } @@ -301,10 +310,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingRight */ @property - get paddingRight () { + get paddingRight() { return this._paddingRight; } - set paddingRight (value) { + set paddingRight(value) { if (this._paddingRight === value) { return; } @@ -319,10 +328,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingTop */ @property - get paddingTop () { + get paddingTop() { return this._paddingTop; } - set paddingTop (value) { + set paddingTop(value) { if (this._paddingTop === value) { return; } @@ -337,10 +346,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingBottom */ @property - get paddingBottom () { + get paddingBottom() { return this._paddingBottom; } - set paddingBottom (value) { + set paddingBottom(value) { if (this._paddingBottom === value) { return; } @@ -354,11 +363,12 @@ export class LayoutComponent extends Component { * !#zh 子节点之间的水平间距。 * @property {Number} spacingX */ - get spacingX () { + @property + get spacingX() { return this._spacingX; } - set spacingX (value) { + set spacingX(value) { if (this._spacingX === value) { return; } @@ -373,11 +383,11 @@ export class LayoutComponent extends Component { * @property {Number} spacingY */ @property - get spacingY () { + get spacingY() { return this._spacingY; } - set spacingY (value) { + set spacingY(value) { if (this._spacingY === value) { return; } @@ -396,11 +406,11 @@ export class LayoutComponent extends Component { @property({ type: VerticalDirection, }) - get verticalDirection () { + get verticalDirection() { return this._verticalDirection; } - set verticalDirection (value: VerticalDirection) { + set verticalDirection(value: VerticalDirection) { if (this._verticalDirection === value) { return; } @@ -419,11 +429,11 @@ export class LayoutComponent extends Component { @property({ type: HorizontalDirection, }) - get horizontalDirection () { + get horizontalDirection() { return this._horizontalDirection; } - set horizontalDirection (value: HorizontalDirection) { + set horizontalDirection(value: HorizontalDirection) { if (this._horizontalDirection === value) { return; } @@ -473,33 +483,46 @@ export class LayoutComponent extends Component { public static AxisDirection = AxisDirection; private _layoutDirty = true; - private _resize = ResizeMode.NONE; - + @property + private _resizeMode = ResizeMode.NONE; // TODO: refactoring this name after data upgrade machanism is out. + @property private _N$layoutType = Type.NONE; + @property private _N$padding = 0; + @property private _cellSize = cc.size(40, 40); + @property private _startAxis = AxisDirection.HORIZONTAL; + @property private _paddingLeft = 0; + @property private _paddingRight = 0; + @property private _paddingTop = 0; + @property private _paddingBottom = 0; + @property private _spacingX = 0; + @property private _spacingY = 0; private _layoutSize = cc.size(300, 200); + @property private _verticalDirection = VerticalDirection.TOP_TO_BOTTOM; + @property private _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT; + @property private _affectedByScale = false; - private _migratePaddingData () { - this.paddingLeft = this._N$padding; - this.paddingRight = this._N$padding; - this.paddingTop = this._N$padding; - this.paddingBottom = this._N$padding; + private _migratePaddingData() { + this._paddingLeft = this._N$padding; + this._paddingRight = this._N$padding; + this._paddingTop = this._N$padding; + this._paddingBottom = this._N$padding; this._N$padding = 0; } - protected onEnable () { + protected onEnable() { this._addEventListeners(); if (this.node.getContentSize().equals(cc.size(0, 0))) { @@ -513,91 +536,91 @@ export class LayoutComponent extends Component { this._doLayoutDirty(); } - protected onDisable () { + protected onDisable() { this._removeEventListeners(); } - private _addEventListeners () { + private _addEventListeners() { cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.on(NodeEvent.CHILD_ADDED, this._childAdded, this); this.node.on(NodeEvent.CHILD_REMOVED, this._childRemoved, this); - this.node.on(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); + // this.node.on(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._addChildrenEventListeners(); } - private _removeEventListeners () { + private _removeEventListeners() { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.off(NodeEvent.CHILD_ADDED, this._childAdded, this); this.node.off(NodeEvent.CHILD_REMOVED, this._childRemoved, this); - this.node.off(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); + // this.node.off(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._removeChildrenEventListeners(); } - private _addChildrenEventListeners () { + private _addChildrenEventListeners() { const children = this.node.children; for (const child of children) { - child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); + child.on(NodeEvent.SCALE_PART, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); - child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); + child.on(NodeEvent.POSITION_PART, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on('active-in-hierarchy-changed', this._doLayoutDirty, this); } } - private _removeChildrenEventListeners () { + private _removeChildrenEventListeners() { const children = this.node.children; for (const child of children) { - child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); + child.off(NodeEvent.SCALE_PART, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); - child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); + child.off(NodeEvent.POSITION_PART, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off('active-in-hierarchy-changed', this._doLayoutDirty, this); } } - private _childAdded (child) { - child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); + private _childAdded(child) { + child.on(NodeEvent.SCALE_PART, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); - child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); + child.on(NodeEvent.POSITION_PART, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on('active-in-hierarchy-changed', this._doLayoutDirty, this); this._doLayoutDirty(); } - private _childRemoved (child) { - child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); + private _childRemoved(child) { + child.off(NodeEvent.SCALE_PART, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); - child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); + child.off(NodeEvent.POSITION_PART, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off('active-in-hierarchy-changed', this._doLayoutDirty, this); this._doLayoutDirty(); } - private _resized () { + private _resized() { this._layoutSize = this.node.getContentSize(); this._doLayoutDirty(); } - private _doLayoutHorizontally (baseWidth, rowBreak, fnPositionY, applyChildren) { + private _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) { const layoutAnchor = this.node.getAnchorPoint(); const children = this.node.children; let sign = 1; - let paddingX = this.paddingLeft; - let leftBoundaryOfLayout = -layoutAnchor.x * baseWidth; - if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + let paddingX = this._paddingLeft; + let startPos = -layoutAnchor.x * baseWidth; + if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; - leftBoundaryOfLayout = (1 - layoutAnchor.x) * baseWidth; - paddingX = this.paddingRight; + startPos = (1 - layoutAnchor.x) * baseWidth; + paddingX = this._paddingRight; } - let nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX; + let nextX = startPos + sign * paddingX - sign * this._spacingX; let rowMaxHeight = 0; let tempMaxHeight = 0; let secondMaxHeight = 0; @@ -614,29 +637,30 @@ export class LayoutComponent extends Component { } } - let newChildWidth = this.cellSize.width; - if (this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN) { - newChildWidth = (baseWidth - (this.paddingLeft + this.paddingRight) - (activeChildCount - 1) * this.spacingX) / activeChildCount; + let newChildWidth = this._cellSize.width; + if (this._N$layoutType!== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + newChildWidth = (baseWidth - (this._paddingLeft + this._paddingRight) - (activeChildCount - 1) * this._spacingX) / activeChildCount; } for (const child of children) { - - const childScaleX = this._getUsedScaleValue(child.scaleX); - const childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) { continue; } + + child.getScale(_tempScale); + const childScaleX = this._getUsedScaleValue(_tempScale.x); + const childScaleY = this._getUsedScaleValue(_tempScale.y); // for resizing children - if (this._resize === ResizeMode.CHILDREN) { + if (this._resizeMode === ResizeMode.CHILDREN) { child.width = newChildWidth / childScaleX; - if (this.type === Type.GRID) { - child.height = this.cellSize.height / childScaleY; + if (this._N$layoutType === Type.GRID) { + child.height = this._cellSize.height / childScaleY; } } let anchorX = child.anchorX; - const childBoundingBoxWidth = child.width * childScaleX; - const childBoundingBoxHeight = child.height * childScaleY; + const childBoundingBoxWidth = child.width! * childScaleX; + const childBoundingBoxHeight = child.height! * childScaleY; if (secondMaxHeight > tempMaxHeight) { tempMaxHeight = secondMaxHeight; @@ -648,16 +672,16 @@ export class LayoutComponent extends Component { maxHeightChildAnchorY = child.getAnchorPoint().y; } - if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { - anchorX = 1 - child.anchorX; + if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + anchorX = 1 - child.anchorX!; } - nextX = nextX + sign * anchorX * childBoundingBoxWidth + sign * this.spacingX; - const rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth; + nextX = nextX + sign * anchorX! * childBoundingBoxWidth + sign * this._spacingX; + const rightBoundaryOfChild = sign * (1 - anchorX!) * childBoundingBoxWidth; if (rowBreak) { - const rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft); - const leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; - const rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth; + const rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this._paddingRight : this._paddingLeft); + const leftToRightRowBreak = this._horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; + const rightToLeftRowBreak = this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth; if (leftToRightRowBreak || rightToLeftRowBreak) { @@ -672,15 +696,16 @@ export class LayoutComponent extends Component { secondMaxHeight = childBoundingBoxHeight; tempMaxHeight = 0; } - nextX = leftBoundaryOfLayout + sign * (paddingX + anchorX * childBoundingBoxWidth); + nextX = startPos + sign * (paddingX + anchorX! * childBoundingBoxWidth); row++; } } const finalPositionY = fnPositionY(child, rowMaxHeight, row); - if (baseWidth >= (childBoundingBoxWidth + this.paddingLeft + this.paddingRight)) { + if (baseWidth >= (childBoundingBoxWidth + this._paddingLeft + this._paddingRight)) { if (applyChildren) { - child.setPosition(cc.v2(nextX, finalPositionY)); + child.getPosition(_tempPos); + child.setPosition(nextX, finalPositionY, _tempPos.z); } } @@ -688,16 +713,16 @@ export class LayoutComponent extends Component { let tempFinalPositionY; const topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight; - if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { - containerResizeBoundary = containerResizeBoundary || this.node._contentSize.height; + if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + containerResizeBoundary = containerResizeBoundary || this.node.getContentSize().height; signX = -1; - tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingBottom); + tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this._paddingBottom); if (tempFinalPositionY < containerResizeBoundary) { containerResizeBoundary = tempFinalPositionY; } } else { - containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.height; - tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingTop); + containerResizeBoundary = containerResizeBoundary || -this.node.getContentSize().height; + tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this._paddingTop); if (tempFinalPositionY > containerResizeBoundary) { containerResizeBoundary = tempFinalPositionY; } @@ -709,38 +734,20 @@ export class LayoutComponent extends Component { return containerResizeBoundary; } - private _getVerticalBaseHeight (children) { - let newHeight = 0; - let activeChildCount = 0; - if (this.resizeMode === ResizeMode.CONTAINER) { - for (const child of children) { - if (child.activeInHierarchy) { - activeChildCount++; - newHeight += child.height * this._getUsedScaleValue(child.scaleY); - } - } - - newHeight += (activeChildCount - 1) * this.spacingY + this.paddingBottom + this.paddingTop; - } else { - newHeight = this.node.getContentSize().height; - } - return newHeight; - } - - private _doLayoutVertically (baseHeight, columnBreak, fnPositionX, applyChildren) { + private _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) { const layoutAnchor = this.node.getAnchorPoint(); const children = this.node.children; let sign = 1; - let paddingY = this.paddingBottom; + let paddingY = this._paddingBottom; let bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight; - if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * baseHeight; - paddingY = this.paddingTop; + paddingY = this._paddingTop; } - let nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY; + let nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this._spacingY; let columnMaxWidth = 0; let tempMaxWidth = 0; let secondMaxWidth = 0; @@ -755,30 +762,34 @@ export class LayoutComponent extends Component { } } - let newChildHeight = this.cellSize.height; - if (this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN) { - newChildHeight = (baseHeight - (this.paddingTop + this.paddingBottom) - (activeChildCount - 1) * this.spacingY) / activeChildCount; + let newChildHeight = this._cellSize.height; + if (this._N$layoutType!== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + newChildHeight = (baseHeight - (this._paddingTop + this._paddingBottom) - (activeChildCount - 1) * this._spacingY) / activeChildCount; } for (const child of children) { + if (!child) { + continue; + } - const childScaleX = this._getUsedScaleValue(child.scaleX); - const childScaleY = this._getUsedScaleValue(child.scaleY); + const scale = child.getScale(); + const childScaleX = this._getUsedScaleValue(scale.x); + const childScaleY = this._getUsedScaleValue(scale.y); if (!child.activeInHierarchy) { continue; } // for resizing children - if (this.resizeMode === ResizeMode.CHILDREN) { + if (this._resizeMode === ResizeMode.CHILDREN) { child.height = newChildHeight / childScaleY; - if (this.type === Type.GRID) { - child.width = this.cellSize.width / childScaleX; + if (this._N$layoutType=== Type.GRID) { + child.width = this._cellSize.width / childScaleX; } } let anchorY = child.anchorY; - const childBoundingBoxWidth = child.width * childScaleX; - const childBoundingBoxHeight = child.height * childScaleY; + const childBoundingBoxWidth = child.width! * childScaleX; + const childBoundingBoxHeight = child.height! * childScaleY; if (secondMaxWidth > tempMaxWidth) { tempMaxWidth = secondMaxWidth; @@ -790,16 +801,16 @@ export class LayoutComponent extends Component { maxWidthChildAnchorX = child.getAnchorPoint().x; } - if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { - anchorY = 1 - child.anchorY; + if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + anchorY = 1 - child.anchorY!; } - nextY = nextY + sign * anchorY * childBoundingBoxHeight + sign * this.spacingY; - const topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight; + nextY = nextY + sign * anchorY! * childBoundingBoxHeight + sign * this._spacingY; + const topBoundaryOfChild = sign * (1 - anchorY!) * childBoundingBoxHeight; if (columnBreak) { - const columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom); - const bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; - const topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight; + const columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this._paddingTop : this._paddingBottom); + const bottomToTopColumnBreak = this._verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; + const topToBottomColumnBreak = this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight; if (bottomToTopColumnBreak || topToBottomColumnBreak) { if (childBoundingBoxWidth >= tempMaxWidth) { @@ -813,15 +824,16 @@ export class LayoutComponent extends Component { secondMaxWidth = childBoundingBoxWidth; tempMaxWidth = 0; } - nextY = bottomBoundaryOfLayout + sign * (paddingY + anchorY * childBoundingBoxHeight); + nextY = bottomBoundaryOfLayout + sign * (paddingY + anchorY! * childBoundingBoxHeight); column++; } } const finalPositionX = fnPositionX(child, columnMaxWidth, column); - if (baseHeight >= (childBoundingBoxHeight + (this.paddingTop + this.paddingBottom))) { + if (baseHeight >= (childBoundingBoxHeight + (this._paddingTop + this._paddingBottom))) { if (applyChildren) { - child.setPosition(cc.v2(finalPositionX, nextY)); + child.getPosition(_tempPos); + child.setPosition(finalPositionX, nextY, _tempPos.z); } } @@ -830,16 +842,16 @@ export class LayoutComponent extends Component { // when the item is the last column break item, the tempMaxWidth will be 0. const rightMarign = (tempMaxWidth === 0) ? childBoundingBoxWidth : tempMaxWidth; - if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { signX = -1; - containerResizeBoundary = containerResizeBoundary || this.node._contentSize.width; - tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingLeft); + containerResizeBoundary = containerResizeBoundary || this.node.getContentSize().width; + tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this._paddingLeft); if (tempFinalPositionX < containerResizeBoundary) { containerResizeBoundary = tempFinalPositionX; } } else { - containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.width; - tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingRight); + containerResizeBoundary = containerResizeBoundary || -this.node.getContentSize().width; + tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this._paddingRight); if (tempFinalPositionX > containerResizeBoundary) { containerResizeBoundary = tempFinalPositionX; } @@ -852,63 +864,73 @@ export class LayoutComponent extends Component { return containerResizeBoundary; } - private _doLayoutBasic () { + private _doLayoutBasic() { const children = this.node.children; - let allChildrenBoundingBox = null; + let allChildrenBoundingBox: Rect|null = null; for (const child of children) { + const childTransform = child.getComponent(UITransformComponent); + if(!childTransform){ + continue; + } + if (child.activeInHierarchy) { if (!allChildrenBoundingBox) { - allChildrenBoundingBox = child.getBoundingBoxToWorld(); + allChildrenBoundingBox = childTransform.getBoundingBoxToWorld(); } else { - // allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld()); + allChildrenBoundingBox.union(allChildrenBoundingBox!, childTransform.getBoundingBoxToWorld()); } } } if (allChildrenBoundingBox) { - let leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); - leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this.paddingLeft, leftBottomInParentSpace.y - this.paddingBottom); + const parentTransform = this.node.parent!.getComponent(UITransformComponent); + if(!parentTransform){ + return; + } - let rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, + let leftBottomInParentSpace = parentTransform.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); + leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this._paddingLeft, leftBottomInParentSpace.y - this._paddingBottom); + + let rightTopInParentSpace = parentTransform.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, allChildrenBoundingBox.y + allChildrenBoundingBox.height)); - rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this.paddingRight, rightTopInParentSpace.y + this.paddingTop); + rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this._paddingRight, rightTopInParentSpace.y + this._paddingTop); const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); - const layoutPosition = this.node.getPosition(); + this.node.getPosition(_tempPos); if (newSize.width !== 0) { - const newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width; + const newAnchorX = (_tempPos.x - leftBottomInParentSpace.x) / newSize.width; this.node.anchorX = parseFloat(newAnchorX.toFixed(2)); } if (newSize.height !== 0) { - const newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height; + const newAnchorY = (_tempPos.y - leftBottomInParentSpace.y) / newSize.height; this.node.anchorY = parseFloat(newAnchorY.toFixed(2)); } this.node.setContentSize(newSize); } } - private _doLayoutGridAxisHorizontal (layoutAnchor, layoutSize) { + private _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) { const baseWidth = layoutSize.width; let sign = 1; let bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; - let paddingY = this.paddingBottom; - if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + let paddingY = this._paddingBottom; + if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height; - paddingY = this.paddingTop; + paddingY = this._paddingTop; } const fnPositionY = function (child, topOffset, row) { - return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this.spacingY); + return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this._spacingY); }.bind(this); let newHeight = 0; - if (this.resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === ResizeMode.CONTAINER) { // calculate the new height of container, it won't change the position of it's children const boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false); newHeight = bottomBoundaryOfLayout - boundary; @@ -918,7 +940,7 @@ export class LayoutComponent extends Component { bottomBoundaryOfLayout = -layoutAnchor.y * newHeight; - if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight; } @@ -926,29 +948,29 @@ export class LayoutComponent extends Component { this._doLayoutHorizontally(baseWidth, true, fnPositionY, true); - if (this.resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === ResizeMode.CONTAINER) { this.node.setContentSize(baseWidth, newHeight); } } - private _doLayoutGridAxisVertical (layoutAnchor, layoutSize) { + private _doLayoutGridAxisVertical(layoutAnchor: Vec2, layoutSize: Size) { const baseHeight = layoutSize.height; let sign = 1; let leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; - let paddingX = this.paddingLeft; - if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + let paddingX = this._paddingLeft; + if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width; - paddingX = this.paddingRight; + paddingX = this._paddingRight; } const fnPositionX = function (child, leftOffset, column) { - return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this.spacingX); + return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this._spacingX); }.bind(this); let newWidth = 0; - if (this.resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === ResizeMode.CONTAINER) { const boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false); newWidth = leftBoundaryOfLayout - boundary; if (newWidth < 0) { @@ -957,7 +979,7 @@ export class LayoutComponent extends Component { leftBoundaryOfLayout = -layoutAnchor.x * newWidth; - if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth; } @@ -965,12 +987,12 @@ export class LayoutComponent extends Component { this._doLayoutVertically(baseHeight, true, fnPositionX, true); - if (this.resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === ResizeMode.CONTAINER) { this.node.setContentSize(newWidth, baseHeight); } } - private _doLayoutGrid () { + private _doLayoutGrid() { const layoutAnchor = this.node.getAnchorPoint(); const layoutSize = this.node.getContentSize(); @@ -983,56 +1005,78 @@ export class LayoutComponent extends Component { } - private _getHorizontalBaseWidth (children) { + private _getHorizontalBaseWidth(children: Node[]) { let newWidth = 0; let activeChildCount = 0; - if (this.resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === ResizeMode.CONTAINER) { for (const child of children) { + child.getScale(_tempScale); if (child.activeInHierarchy) { activeChildCount++; - newWidth += child.width * this._getUsedScaleValue(child.scaleX); + newWidth += child.width! * this._getUsedScaleValue(_tempScale.x); } } - newWidth += (activeChildCount - 1) * this.spacingX + this.paddingLeft + this.paddingRight; + newWidth += (activeChildCount - 1) * this._spacingX + this._paddingLeft + this._paddingRight; } else { newWidth = this.node.getContentSize().width; } return newWidth; } - private _doLayout () { + private _getVerticalBaseHeight(children: Node[]) { + let newHeight = 0; + let activeChildCount = 0; + if (this._resizeMode === ResizeMode.CONTAINER) { + for (const child of children) { + child.getScale(_tempScale); + if (child.activeInHierarchy) { + activeChildCount++; + newHeight += child.height! * this._getUsedScaleValue(_tempScale.y); + } + } - if (this.type === Type.HORIZONTAL) { + newHeight += (activeChildCount - 1) * this._spacingY + this._paddingBottom + this._paddingTop; + } else { + newHeight = this.node.getContentSize().height; + } + return newHeight; + } + + private _doLayout() { + + if (this._N$layoutType=== Type.HORIZONTAL) { const newWidth = this._getHorizontalBaseWidth(this.node.children); const fnPositionY = (child) => { - return child.y; + child.getPosition(_tempPos) + return _tempPos.y; }; this._doLayoutHorizontally(newWidth, false, fnPositionY, true); this.node.width = newWidth; - } else if (this.type === Type.VERTICAL) { + } else if (this._N$layoutType=== Type.VERTICAL) { const newHeight = this._getVerticalBaseHeight(this.node.children); const fnPositionX = (child) => { - return child.x; + child.getPosition(_tempPos); + return _tempPos.x; }; this._doLayoutVertically(newHeight, false, fnPositionX, true); this.node.height = newHeight; - } else if (this.type === Type.NONE) { - if (this.resizeMode === ResizeMode.CONTAINER) { + } else if (this._N$layoutType=== Type.NONE) { + if (this._resizeMode === ResizeMode.CONTAINER) { this._doLayoutBasic(); } - } else if (this.type === Type.GRID) { + } else if (this._N$layoutType=== Type.GRID) { this._doLayoutGrid(); } } - private _getUsedScaleValue (value) { - return this.affectedByScale ? Math.abs(value) : 1; + private _getUsedScaleValue(value) { + return this._affectedByScale ? Math.abs(value) : 1; } /** @@ -1048,19 +1092,19 @@ export class LayoutComponent extends Component { * layout.updateLayout(); * cc.log(childNode.x); // changed */ - public updateLayout () { + public updateLayout() { if (this._layoutDirty && this.node.children.length > 0) { this._doLayout(); this._layoutDirty = false; } } - private _doLayoutDirty () { + private _doLayoutDirty() { this._layoutDirty = true; } - private _doScaleDirty () { - this._layoutDirty = this._layoutDirty || this.affectedByScale; + private _doScaleDirty() { + this._layoutDirty = this._layoutDirty || this._affectedByScale; } } diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index dd8eee5516..9912bad251 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -36,6 +36,7 @@ import { scale, translate } from '../../primitive/transform'; import { setupClearMaskMaterial, setupMaskMaterial } from '../assembler/mask-assembler'; import { UIRenderComponent } from './ui-render-component'; import { UITransformComponent } from './ui-transfrom-component'; +import { EventType }from '../../../scene-graph/node-event-enum'; /** * !#en the type for mask. @@ -70,11 +71,9 @@ const SEGEMENTS_MAX = 10000; * !#en The Mask Component. * !#zh 遮罩组件。 */ -@ccclass('cc.Mask') +@ccclass('cc.MaskComponent') @executionOrder(100) @menu('UI/Mask') -@requireComponent(UITransformComponent) -@executeInEditMode export class MaskComponent extends UIRenderComponent { public static Type = MaskType; @@ -82,11 +81,14 @@ export class MaskComponent extends UIRenderComponent { * !#en The mask type. * !#zh 遮罩类型。 */ - public get type () { + @property({ + type: MaskType + }) + get type () { return this._type; } - public set type (value) { + set type(value: MaskType) { this._type = value; if (this._type !== MaskType.IMAGE_STENCIL) { this.spriteFrame = null; @@ -104,11 +106,14 @@ export class MaskComponent extends UIRenderComponent { * !#en The mask image * !#zh 遮罩所需要的贴图 */ - public get spriteFrame () { + @property({ + type: SpriteFrame + }) + get spriteFrame () { return this._spriteFrame; } - public set spriteFrame (value) { + set spriteFrame (value: SpriteFrame | null) { if (this._spriteFrame === value) { return; } @@ -131,12 +136,15 @@ export class MaskComponent extends UIRenderComponent { */ // @range: [0, 1, 0.1], // slide: true, - @property({type: cc.Float}) - public get alphaThreshold () { + @property({ + slide: true, + range:[0, 1, 0.1] + }) + get alphaThreshold () { return this._alphaThreshold; } - public set alphaThreshold (value) { + set alphaThreshold (value) { this._alphaThreshold = value; } @@ -144,12 +152,12 @@ export class MaskComponent extends UIRenderComponent { * !#en Reverse mask(Not supported in Canvas Mode). * !#zh 反向遮罩(不支持 Canvas 模式)。 */ - @property({type: Boolean}) - public get inverted () { + @property() + get inverted () { return this._inverted; } - public set inverted (value) { + set inverted (value) { this._inverted = value; if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { cc.warnID(4202); @@ -162,11 +170,12 @@ export class MaskComponent extends UIRenderComponent { * !#en The segements for ellipse mask. * !#zh 椭圆遮罩的曲线细分数 */ - public get segments () { + @property + get segments () { return this._segments; } - public set segments (value) { + set segments (value) { this._segments = clamp(value, SEGEMENTS_MIN, SEGEMENTS_MAX); } @@ -177,13 +186,13 @@ export class MaskComponent extends UIRenderComponent { private _type = MaskType.RECT; @property - private _alphaThreshold: number = 0; + private _alphaThreshold = 0; @property - private _inverted: boolean = false; + private _inverted = false; @property - private _segments: number = 64; + private _segments = 64; private _maskMaterial: Material | null = null; @@ -200,16 +209,22 @@ export class MaskComponent extends UIRenderComponent { public onEnable () { super.onEnable(); this._activateMaterial(); + + this.node.on(EventType.POSITION_PART, this._updateGraphics, this); + this.node.on(EventType.ROTATION_PART, this._updateGraphics, this); + this.node.on(EventType.SCALE_PART, this._updateGraphics, this); + this.node.on(EventType.SIZE_CHANGED, this._updateGraphics, this); + this.node.on(EventType.ANCHOR_CHANGED, this._updateGraphics, this); } public onDisable () { super.onDisable(); - // this.node.off(Node.EventType.POSITION_CHANGED, this._updateGraphics, this); - // this.node.off(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); - // this.node.off(Node.EventType.SCALE_CHANGED, this._updateGraphics, this); - // this.node.off(Node.EventType.SIZE_CHANGED, this._updateGraphics, this); - // this.node.off(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); + this.node.off(EventType.POSITION_PART, this._updateGraphics, this); + this.node.off(EventType.ROTATION_PART, this._updateGraphics, this); + this.node.off(EventType.SCALE_PART, this._updateGraphics, this); + this.node.off(EventType.SIZE_CHANGED, this._updateGraphics, this); + this.node.off(EventType.ANCHOR_CHANGED, this._updateGraphics, this); // this.node._renderFlag &= ~RenderFlow.FLAG_POST_RENDER; } @@ -225,7 +240,7 @@ export class MaskComponent extends UIRenderComponent { // } // } - public _onTextureLoaded () { + private _onTextureLoaded () { // Mark render data dirty if (this._renderData) { this._renderData.uvDirty = true; @@ -237,7 +252,7 @@ export class MaskComponent extends UIRenderComponent { } } - public _applySpriteFrame (oldFrame) { + private _applySpriteFrame (oldFrame) { if (oldFrame && oldFrame.off) { oldFrame.off('load', this._onTextureLoaded, this); } @@ -252,31 +267,31 @@ export class MaskComponent extends UIRenderComponent { } } - public _activateMaterial () { + private _activateMaterial () { if (!this._maskMaterial) { - this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this); + this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this, CC_EDITOR ? true : false); setupMaskMaterial(this._maskMaterial); } if (!this._clearMaskMaterial) { - this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this); + this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this, CC_EDITOR ? true : false); setupClearMaskMaterial(this._clearMaskMaterial); } } - public _getMaskGeometry () { + public getMaskGeometry () { return this._maskGeometry; } - public _getClearGeometry () { + public getClearGeometry () { return this._clearGeometry; } - public _getMaskMaterial (): Material | null { + public getMaskMaterial (): Material | null { return this._maskMaterial; } - public _getClearMaterial (): Material | null { + public getClearMaterial (): Material | null { return this._clearMaskMaterial; } @@ -309,14 +324,14 @@ export class MaskComponent extends UIRenderComponent { return null; } - private _drawRect (x: number, y: number, width: number, height: number) { + private _drawRect (x, y, width, height) { const geometry = quad({ includeNormal: false, includeUV: false }); scale(geometry, { x: width, y: height }); translate(geometry, { x: x + width / 2, y: y + height / 2 }); return geometry; } - private _drawEllipse (cx: number, cy: number, rx: number, ry: number) { + private _drawEllipse (cx, cy, rx, ry) { const geometry = circle({ includeNormal: false, includeUV: false }); scale(geometry, { x: rx, y: ry }); translate(geometry, { x: cx, y: cy }); @@ -325,4 +340,4 @@ export class MaskComponent extends UIRenderComponent { } // tslint:disable-next-line -cc['MaskComponent'] = MaskComponent; +cc.MaskComponent = MaskComponent; diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/3d/ui/components/progress-bar-component.ts index 019653a675..b7e0170bbc 100644 --- a/cocos/3d/ui/components/progress-bar-component.ts +++ b/cocos/3d/ui/components/progress-bar-component.ts @@ -25,9 +25,9 @@ ****************************************************************************/ import { Component} from '../../../components/component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { clamp01 } from '../../../core/utils/misc'; -import { Enum } from '../../../core/value-types'; +import { Enum, Size, Vec2, Vec3 } from '../../../core/value-types'; import { SpriteComponent } from './sprite-component'; /** @@ -99,7 +99,7 @@ export class ProgressBarComponent extends Component { return this._barSprite; } - set barSprite (value: SpriteComponent) { + set barSprite (value: SpriteComponent | null) { if (this._barSprite === value) { return; } @@ -130,7 +130,7 @@ export class ProgressBarComponent extends Component { const entity = this._barSprite.node; if (!entity) { return; } - const entitySize = entity.getContentSize(); + const entitySize = entity.getContentSize() as Size; if (this._mode === Mode.HORIZONTAL) { this.totalLength = entitySize.width; } else if (this._mode === Mode.VERTICAL) { @@ -148,14 +148,14 @@ export class ProgressBarComponent extends Component { */ @property get totalLength () { - return this._N$totalLength; + return this._totalLength; } - set totalLength (value: number) { + set totalLength (value) { if (this._mode === Mode.FILLED) { value = clamp01(value); } - this._N$totalLength = value; + this._totalLength = value; this._updateBarStatus(); } @@ -172,7 +172,7 @@ export class ProgressBarComponent extends Component { return this._progress; } - set progress (value: number) { + set progress (value) { if (this._progress === value) { return; } @@ -191,7 +191,7 @@ export class ProgressBarComponent extends Component { return this._reverse; } - set reverse (value: boolean) { + set reverse (value) { if (this._reverse === value) { return; } @@ -207,32 +207,32 @@ export class ProgressBarComponent extends Component { @property private _barSprite: SpriteComponent | null = null; @property - private _mode: number = Mode.HORIZONTAL; - private _N$totalLength: number = 1; + private _mode = Mode.HORIZONTAL; @property - private _progress: number = 0.1; + private _totalLength = 1; @property - private _reverse: boolean = false; + private _progress = 0.1; + @property + private _reverse = false; - public _initBarSprite () { + private _initBarSprite () { if (this._barSprite) { const entity = this._barSprite.node; if (!entity) { return; } - const nodeSize = this.node.getContentSize(); - const nodeAnchor = this.node.getAnchorPoint(); + const nodeSize = this.node.getContentSize() as Size; + const nodeAnchor = this.node.getAnchorPoint() as Vec2; - const entitySize = entity.getContentSize(); + const barSpriteSize = entity.getContentSize() as Size; - if (entity.parent === this.node) { - this.node.setContentSize(entitySize); - } + // if (entity.parent === this.node) { + // this.node.setContentSize(barSpriteSize); + // } - if (this._barSprite.fillType === cc.SpriteComponent.FillType.RADIAL) { + if (this._barSprite.fillType === SpriteComponent.FillType.RADIAL) { this._mode = Mode.FILLED; } - const barSpriteSize = entity.getContentSize(); if (this._mode === Mode.HORIZONTAL) { this.totalLength = barSpriteSize.width; } else if (this._mode === Mode.VERTICAL) { @@ -243,46 +243,47 @@ export class ProgressBarComponent extends Component { if (entity.parent === this.node) { const x = - nodeSize.width * nodeAnchor.x; - const y = 0; - entity.setPosition(cc.v2(x, y)); + entity.setPosition(x, 0, 0); } } } - public _updateBarStatus () { + private _updateBarStatus () { if (this._barSprite) { const entity = this._barSprite.node; if (!entity) { return; } - const entityAnchorPoint = entity.getAnchorPoint(); - const entitySize = entity.getContentSize(); + const entityAnchorPoint = entity.getAnchorPoint() as Vec2; + const entitySize = entity.getContentSize() as Size; const entityPosition = entity.getPosition(); - let anchorPoint = cc.v2(0, 0.5); + let anchorPoint = new Vec2(0, 0.5); const progress = clamp01(this._progress); - let actualLenth = this.totalLength * progress; - let finalContentSize; - let totalWidth; - let totalHeight; + let actualLenth = this._totalLength * progress; + let finalContentSize = entitySize; + let totalWidth = 0; + let totalHeight = 0; switch (this._mode) { case Mode.HORIZONTAL: if (this._reverse) { - anchorPoint = cc.v2(1, 0.5); + anchorPoint = new Vec2(1, 0.5); } - finalContentSize = cc.size(actualLenth, entitySize.height); - totalWidth = this.totalLength; + + finalContentSize = new Size(actualLenth, entitySize.height); + totalWidth = this._totalLength; totalHeight = entitySize.height; break; case Mode.VERTICAL: if (this._reverse) { - anchorPoint = cc.v2(0.5, 1); + anchorPoint = new Vec2(0.5, 1); } else { - anchorPoint = cc.v2(0.5, 0); + anchorPoint = new Vec2(0.5, 0); } - finalContentSize = cc.size(entitySize.width, actualLenth); + + finalContentSize = new Size(entitySize.width, actualLenth); totalWidth = entitySize.width; - totalHeight = this.totalLength; + totalHeight = this._totalLength; break; } @@ -301,9 +302,9 @@ export class ProgressBarComponent extends Component { const anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; const anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; - const finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); + const finalPosition = new Vec3(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY, 0); - entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entity.getPosition().z); + entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entityPosition.z); entity.setAnchorPoint(anchorPoint); entity.setContentSize(finalContentSize); @@ -314,3 +315,5 @@ export class ProgressBarComponent extends Component { } } } + +cc.ProgressBarComponent = ProgressBarComponent; diff --git a/cocos/3d/ui/components/scroll-bar-component.ts b/cocos/3d/ui/components/scroll-bar-component.ts index 2910c625de..5eb190143a 100644 --- a/cocos/3d/ui/components/scroll-bar-component.ts +++ b/cocos/3d/ui/components/scroll-bar-component.ts @@ -24,14 +24,19 @@ THE SOFTWARE. ****************************************************************************/ -import { Component} from '../../../components/component'; +import { Component } from '../../../components/component'; import { clamp01 } from '../../../core/utils/misc'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { UIRenderComponent } from './ui-render-component'; -import { Vec2 } from '../../../core/value-types'; +import { Vec3 } from '../../../core/value-types'; import { Node } from '../../../scene-graph/node'; +import { ScrollViewComponent } from './scroll-view-component'; +import { UITransformComponent } from './ui-transfrom-component'; +import { vec3 } from '../../../core/vmath'; -var GETTINGSHORTERFACTOR = 20; +const GETTINGSHORTERFACTOR = 20; +const ZERO = new Vec3(); +const _tempPos = new Vec3(); /** * Enum for Scrollbar direction @@ -61,7 +66,7 @@ var Direction = cc.Enum({ @executeInEditMode export class ScrollBarComponent extends Component { @property - private _scrollView: Component | null = null; + private _scrollView: ScrollViewComponent | null = null; @property private _handle: UIRenderComponent | null = null; @property @@ -87,7 +92,7 @@ export class ScrollBarComponent extends Component { return this._handle; } - set handle(value: UIRenderComponent) { + set handle(value: UIRenderComponent | null) { if (this._handle === value) { return } @@ -131,7 +136,7 @@ export class ScrollBarComponent extends Component { } this._enableAutoHide = value; - if(this._enableAutoHide){ + if (this._enableAutoHide) { this._setOpacity(0); } } @@ -188,21 +193,21 @@ export class ScrollBarComponent extends Component { } private _convertToScrollViewSpace(content: Node) { - return new Vec2(0, 0); - if (!this._scrollView){ - return; + if (!this._scrollView) { + return ZERO; } - // TODO: - // var worldSpacePos = content.convertToWorldSpace(new Vec2(0, 0)); - // var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos); - // return scrollViewSpacePos; + const uiTransform = this._scrollView.node.getComponent(UITransformComponent)!; + const worldSpacePos = content.getWorldPosition(); + // const scrollViewSpacePos = uiTransform.convertToNodeSpace(worldSpacePos); + const scrollViewSpacePos = uiTransform.convertToNodeSpaceAR(worldSpacePos); + return scrollViewSpacePos; } private _setOpacity(opacity: number) { if (this._handle) { let renderComp = this.node.getComponent(UIRenderComponent); - if (renderComp){ + if (renderComp) { renderComp.color.a = opacity; } @@ -214,80 +219,88 @@ export class ScrollBarComponent extends Component { } public onScroll(outOfBoundary) { - if (this._scrollView) { - - var content = this._scrollView.content; - if (content) { - var contentSize = content.getContentSize(); - var scrollViewSize = this._scrollView.node.getContentSize(); - var handleNodeSize = this.node.getContentSize(); - - if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { - return; - } - - if (this._enableAutoHide) { - this._autoHideRemainingTime = this._autoHideTime; - // this._setOpacity(this._opacity); - } - - var contentMeasure = 0; - var scrollViewMeasure = 0; - var outOfBoundaryValue = 0; - var contentPosition = 0; - var handleNodeMeasure = 0; - - if (this._direction === Direction.HORIZONTAL) { - contentMeasure = contentSize.width; - scrollViewMeasure = scrollViewSize.width; - handleNodeMeasure = handleNodeSize.width; - outOfBoundaryValue = outOfBoundary.x; - - contentPosition = -this._convertToScrollViewSpace(content).x; - } else if (this._direction === Direction.VERTICAL) { - contentMeasure = contentSize.height; - scrollViewMeasure = scrollViewSize.height; - handleNodeMeasure = handleNodeSize.height; - outOfBoundaryValue = outOfBoundary.y; - - contentPosition = -this._convertToScrollViewSpace(content).y; - } - - var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue); - var position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length); - - this._updateLength(length); - this._updateHanlderPosition(position); - } + if (!this._scrollView) { + return } + + const content = this._scrollView.content; + if (!content) { + return; + } + + var contentSize = content.getContentSize(); + var scrollViewSize = this._scrollView.node.getContentSize(); + var barSize = this.node.getContentSize(); + + if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { + return; + } + + if (this._enableAutoHide) { + this._autoHideRemainingTime = this._autoHideTime; + // this._setOpacity(this._opacity); + } + + let contentMeasure = 0; + let scrollViewMeasure = 0; + let outOfBoundaryValue = 0; + let contentPosition = 0; + let handleNodeMeasure = 0; + + if (this._direction === Direction.HORIZONTAL) { + contentMeasure = contentSize.width; + scrollViewMeasure = scrollViewSize.width; + handleNodeMeasure = barSize.width; + outOfBoundaryValue = outOfBoundary.x; + + contentPosition = -this._convertToScrollViewSpace(content).x; + } else if (this._direction === Direction.VERTICAL) { + contentMeasure = contentSize.height; + scrollViewMeasure = scrollViewSize.height; + handleNodeMeasure = barSize.height; + outOfBoundaryValue = outOfBoundary.y; + + contentPosition = -this._convertToScrollViewSpace(content).y; + } + + const length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue); + const position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length); + + this._updateLength(length); + this._updateHanlderPosition(position); + + } - // FIXME: use ScrollViewComponent - public setScrollView(scrollView: Component) { + public setScrollView(scrollView: ScrollViewComponent) { this._scrollView = scrollView; } private _updateHanlderPosition(position) { if (this._handle) { - var oldPosition = this._fixupHandlerPosition(); + const oldPosition = this._fixupHandlerPosition(); - this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y); + this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y, oldPosition.z); } } private _fixupHandlerPosition() { - if(!this._handle){ - return; + if (!this._handle) { + return ZERO; } - var barSize = this.node.getContentSize(); - var barAnchor = this.node.getAnchorPoint(); - var handleSize = this._handle.node.getContentSize(); + const barSize = this.node.getContentSize(); + const barAnchor = this.node.getAnchorPoint(); + const handleSize = this._handle.node.getContentSize(); + // const handleParent = this._handle.node.parent!; + const handleTransform = handleParent.getComponent(UITransformComponent); + if (!handleTransform) { + return ZERO; + } - var handleParent = this._handle.node.parent; - - var leftBottomWorldPosition = this.node.convertToWorldSpaceAR(cc.v2(-barSize.width * barAnchor.x, -barSize.height * barAnchor.y)); - var fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition); + vec3.set(_tempPos, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y) + const leftBottomWorldPosition = this.node.getWorldPosition(_tempPos); + const fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition); if (this._direction === Direction.HORIZONTAL) { fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2); @@ -308,13 +321,11 @@ export class ScrollBarComponent extends Component { } private _conditionalDisableScrollBar(contentSize, scrollViewSize) { - if (contentSize.width <= scrollViewSize.width - && this._direction === Direction.HORIZONTAL) { + if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) { return true; } - if (contentSize.height <= scrollViewSize.height - && this._direction === Direction.VERTICAL) { + if (contentSize.height <= scrollViewSize.height && this._direction === Direction.VERTICAL) { return true; } return false; diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index 93ab9d0d30..593b0cd237 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -25,15 +25,15 @@ ****************************************************************************/ import ComponentEventHandler from '../../../components/CCComponentEventHandler'; -import { Component} from '../../../components/component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import Event from '../../../core/event/event'; +import { Component } from '../../../components/component'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { EventTouch } from '../../../core/platform/event-manager/CCEvent'; import { clamp01 } from '../../../core/utils/misc'; -import { Enum, Vec2 } from '../../../core/value-types/index'; -import { SpriteComponent} from './sprite-component'; -import { UITransformComponent } from './ui-transfrom-component'; +import { Enum, Vec3 } from '../../../core/value-types/index'; +import { vec3 } from '../../../core/vmath'; import { EventType } from '../../../scene-graph/node-event-enum'; +import { SpriteComponent } from './sprite-component'; + /** * !#en The Slider Direction * !#zh 滑动器方向 @@ -65,7 +65,6 @@ Enum(Direction); @ccclass('cc.SliderComponent') @executionOrder(100) @menu('UI/Slider') -// @executeInEditMode export class SliderComponent extends Component { /** @@ -76,11 +75,11 @@ export class SliderComponent extends Component { @property({ type: SpriteComponent, }) - get handle () { + get handle() { return this._handle; } - set handle (value: SpriteComponent) { + set handle(value: SpriteComponent | null) { if (this._handle === value) { return; } @@ -99,11 +98,11 @@ export class SliderComponent extends Component { @property({ type: Direction, }) - get direction () { + get direction() { return this._direction; } - set direction (value: number) { + set direction(value: number) { if (this._direction === value) { return; } @@ -117,13 +116,13 @@ export class SliderComponent extends Component { */ @property({ slide: true, - range: [0.1, 1, 0.01], + range: [0, 1, 0.01], }) - get progress () { + get progress() { return this._progress; } - set progress (value: number) { + set progress(value: number) { if (this._progress === value) { return; } @@ -140,34 +139,36 @@ export class SliderComponent extends Component { @property({ type: ComponentEventHandler, }) - get slideEvents () { + get slideEvents() { return this._slideEvents; } - set slideEvents (value: ComponentEventHandler[]) { + set slideEvents(value: ComponentEventHandler[]) { this._slideEvents = value; } public static Direction = Direction; @property - public _handle: SpriteComponent | null = null; + private _handle: SpriteComponent | null = null; @property - public _direction: number = Direction.Horizontal; + private _direction: number = Direction.Horizontal; @property - public _progress: number = 0.1; + private _progress: number = 0.1; @property - public _slideEvents: ComponentEventHandler[] = []; + private _slideEvents: ComponentEventHandler[] = []; - public _offset: Vec2 = new Vec2(); - public _dragging = false; - public _touchHandle = false; + private _offset: Vec3 = new Vec3(); + private _dragging = false; + private _touchHandle = false; + private _handlelocalPos = new Vec3(); + private _touchPos = new Vec3(); - public __preload () { + public __preload() { this._updateHandlePosition(); } // 注册事件 - public onEnable () { + public onEnable() { this._updateHandlePosition(); this.node.on(EventType.TOUCH_START, this._onTouchBegan, this); @@ -181,7 +182,7 @@ export class SliderComponent extends Component { } } - public onDisable () { + public onDisable() { this.node.off(EventType.TOUCH_START, this._onTouchBegan, this); this.node.off(EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(EventType.TOUCH_END, this._onTouchEnded, this); @@ -193,83 +194,100 @@ export class SliderComponent extends Component { } } - public _onHandleDragStart (event: Event) { - if (!event) { + private _onHandleDragStart(event?: EventTouch) { + if (!event || !this._handle || !this._handle.node.uiTransfromComp) { return; } this._dragging = true; this._touchHandle = true; - this._offset = this._handle && this._handle.node.uiTransfromComp && this._handle.node.uiTransfromComp.convertToNodeSpaceAR((event as EventTouch).touch.getLocation()); + const touhPos = event.touch!.getLocation(); + vec3.set(this._touchPos, touhPos.x, touhPos.y, 0); + this._offset = this._handle.node.uiTransfromComp.convertToNodeSpaceAR(this._touchPos); event.propagationStopped = true; } - public _onTouchBegan (event: Event) { - if (!this._handle) { return; } + private _onTouchBegan(event?: EventTouch) { + if (!this._handle || !event) { + return; + } + this._dragging = true; if (!this._touchHandle) { - this._handleSliderLogic((event as EventTouch).touch); + this._handleSliderLogic(event.touch); } event.propagationStopped = true; } - public _onTouchMoved (event: Event) { - if (!this._dragging) { return; } - this._handleSliderLogic((event as EventTouch).touch); + private _onTouchMoved(event?: EventTouch) { + if (!this._dragging || !event) { + return; + } + + this._handleSliderLogic(event.touch); event.propagationStopped = true; } - public _onTouchEnded (event: Event) { + private _onTouchEnded(event?: EventTouch) { this._dragging = false; this._touchHandle = false; this._offset = cc.v2(); - event.propagationStopped = true; + + if (event) { + event.propagationStopped = true; + } } - public _onTouchCancelled (event: Event) { + private _onTouchCancelled(event?: EventTouch) { this._dragging = false; - event.propagationStopped = true; + if (event) { + event.propagationStopped = true; + } } - public _handleSliderLogic (touch) { + private _handleSliderLogic(touch) { this._updateProgress(touch); this._emitSlideEvent(); } - public _emitSlideEvent () { + private _emitSlideEvent() { cc.Component.EventHandler.emitEvents(this.slideEvents, this); this.node.emit('slide', this); } - public _updateProgress (touch: EventTouch) { + private _updateProgress(touch: EventTouch) { if (!this._handle) { return; } - const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR((touch as EventTouch).getLocation()); + const touchPos = (touch as EventTouch).getLocation(); + vec3.set(this._touchPos, touchPos.x, touchPos.y, 0); + const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR(this._touchPos); if (this.direction === Direction.Horizontal) { - this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width); + this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width!); } else { - this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height); + this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height!); } } - public _updateHandlePosition () { + private _updateHandlePosition() { if (!this._handle) { return; } - let handlelocalPos; + this._handlelocalPos.set(this._handle.node.getPosition()); if (this._direction === Direction.Horizontal) { - handlelocalPos = cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0); + this._handlelocalPos.x = -this.node.width! * this.node.anchorX! + this.progress * this.node.width!; } else { - handlelocalPos = cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height); - } - const worldSpacePos = this.node.uiTransfromComp!.convertToWorldSpaceAR(handlelocalPos); - const transform: UITransformComponent | null = this._handle.node.parent && this._handle.node.parent.getComponent(cc.UITransformComponent); - if (transform) { - this._handle.node.setPosition(transform.convertToNodeSpaceAR(worldSpacePos)); + this._handlelocalPos.y = -this.node.height! * this.node.anchorY! + this.progress * this.node.height!; } + + this._handle.node.setPosition(this._handlelocalPos); + // const worldSpacePos = this.node.uiTransfromComp!.convertToWorldSpaceAR(handlelocalPos); + // const transform: UITransformComponent | null = this._handle.node.parent && this._handle.node.parent.getComponent(cc.UITransformComponent); + // if (transform) { + // this._handle.node.setPosition(transform.convertToNodeSpaceAR(worldSpacePos)); + // } } } -// cc.Slider = module.exports = Slider; +cc.SliderComponent = SliderComponent; /** * !#en diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 7f5ad449b6..74536b7815 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -26,14 +26,12 @@ // @ts-check import atlas from '../../../assets/CCSpriteAtlas'; import { SpriteFrame } from '../../../assets/CCSpriteFrame'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { clampf } from '../../../core/utils/misc'; import { Vec2 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; -import { UIRenderComponent } from './ui-render-component'; -import { Node } from '../../../scene-graph/node'; import { UI } from '../../../renderer/ui/ui'; -const EventType = Node.EventType; +import { UIRenderComponent } from './ui-render-component'; /** * !#en Enum for sprite type. @@ -71,7 +69,7 @@ enum SpriteType { // * @property {Number} MESH // */ // MESH: 4 -}; +} ccenum(SpriteType); @@ -98,8 +96,8 @@ enum FillType { // * !#zh 径向填充 // * @property {Number} RADIAL // */ - // RADIAL = 2, -}; + RADIAL = 2, +} ccenum(FillType); @@ -191,10 +189,10 @@ export class SpriteComponent extends UIRenderComponent { get type () { return this._type; } - set type(value: SpriteType) { + set type (value: SpriteType) { if (this._type !== value) { this._type = value; - this._updateAssembler(); + this._flushAssembler(); } } @@ -224,7 +222,7 @@ export class SpriteComponent extends UIRenderComponent { this.markForUpdateRenderData(true); } this._fillType = value; - this._updateAssembler(); + this._flushAssembler(); } } @@ -393,7 +391,7 @@ export class SpriteComponent extends UIRenderComponent { } } - this._updateAssembler(); + this._flushAssembler(); this._activateMaterial(); // if (!this._spriteFrame) { @@ -402,7 +400,7 @@ export class SpriteComponent extends UIRenderComponent { } public updateAssembler (render: UI) { - if (!this._spriteFrame || !this.material) { + if (!this._spriteFrame || !this._material) { return; } super.updateAssembler(render); @@ -413,18 +411,18 @@ export class SpriteComponent extends UIRenderComponent { this.destroyRenderData(); } - public onDisable () { - // this._super(); - super.onDisable(); - } + // public onDisable () { + // // this._super(); + // super.onDisable(); + // } public _onNodeSizeDirty () { if (!this._renderData) { return; } this.markForUpdateRenderData(); } - public _updateAssembler () { - const assembler = SpriteComponent.Assembler.getAssembler(this); + private _flushAssembler () { + const assembler = SpriteComponent.Assembler!.getAssembler(this); if (this._assembler !== assembler) { this.destroyRenderData(); @@ -432,22 +430,22 @@ export class SpriteComponent extends UIRenderComponent { } if (!this._renderData) { - if (this._assembler) { + if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); - this._renderData.material = this.material; + this._renderData.material = this._material; this.markForUpdateRenderData(); } } } - public _activateMaterial () { + private _activateMaterial () { const spriteFrame = this._spriteFrame; - let material = this.material; + const material = this._material; // WebGL if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { // if (!material) { - // this.material = cc.builtinResMgr.get('sprite-material'); - // material = this.material; + // this._material = cc.builtinResMgr.get('sprite-material'); + // material = this._material; // if (spriteFrame && spriteFrame.textureLoaded()) { // material!.setProperty('mainTexture', spriteFrame); // this.markForUpdateRenderData(); @@ -455,16 +453,16 @@ export class SpriteComponent extends UIRenderComponent { // } // TODO: // else { - if (spriteFrame && spriteFrame.textureLoaded()) { - if (material){ - // const matTexture = material.getProperty('mainTexture'); - // if (matTexture !== spriteFrame) { - material.setProperty('mainTexture', spriteFrame); - this.markForUpdateRenderData(); - // } - } - + if (spriteFrame && spriteFrame.textureLoaded()) { + if (material) { + // const matTexture = material.getProperty('mainTexture'); + // if (matTexture !== spriteFrame) { + material.setProperty('mainTexture', spriteFrame); + this.markForUpdateRenderData(); + // } } + + } // } if (this._renderData) { @@ -476,7 +474,7 @@ export class SpriteComponent extends UIRenderComponent { } } - public _applyAtlas (spriteFrame: SpriteFrame | null) { + private _applyAtlas (spriteFrame: SpriteFrame | null) { if (!CC_EDITOR) { return; } @@ -491,19 +489,19 @@ export class SpriteComponent extends UIRenderComponent { } } - public _canRender () { - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - if (!this._enabled) { return false; } - } else { - if (!this._enabled || !this.material) { return false; } - } + // private _canRender () { + // if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { + // if (!this._enabled) { return false; } + // } else { + // if (!this._enabled || !this._material) { return false; } + // } - const spriteFrame = this._spriteFrame; - if (!spriteFrame || !spriteFrame.textureLoaded()) { - return false; - } - return true; - } + // const spriteFrame = this._spriteFrame; + // if (!spriteFrame || !spriteFrame.textureLoaded()) { + // return false; + // } + // return true; + // } // public markForUpdateRenderData (enable: boolean) { // if (enable /*&& this._canRender()*/) { @@ -542,7 +540,7 @@ export class SpriteComponent extends UIRenderComponent { // this._applySpriteSize(); // } - public _applySpriteFrame (oldFrame: SpriteFrame | null) { + private _applySpriteFrame (oldFrame: SpriteFrame | null) { // if (oldFrame && oldFrame.off) { // oldFrame.off('load', this._onTextureLoaded, this); // } @@ -555,7 +553,7 @@ export class SpriteComponent extends UIRenderComponent { if (spriteFrame) { if (!oldFrame || spriteFrame !== oldFrame) { - // this.material.setProperty('mainTexture', spriteFrame); + // this._material.setProperty('mainTexture', spriteFrame); if (spriteFrame.textureLoaded()) { // this._onTextureLoaded(); this._activateMaterial(); @@ -617,4 +615,4 @@ export class SpriteComponent extends UIRenderComponent { // }; // } -// cc.Sprite = module.exports = Sprite; +cc.SpriteComponent = SpriteComponent; diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/3d/ui/components/toggle-component.ts index f91afe63f3..0984400014 100644 --- a/cocos/3d/ui/components/toggle-component.ts +++ b/cocos/3d/ui/components/toggle-component.ts @@ -110,7 +110,7 @@ export class ToggleComponent extends ButtonComponent { return this._checkMark; } - set checkMark (value: SpriteComponent) { + set checkMark (value: SpriteComponent | null) { if (this._checkMark === value) { return; } @@ -217,7 +217,7 @@ export class ToggleComponent extends ButtonComponent { this._emitToggleEvents(); } - public _emitToggleEvents () { + private _emitToggleEvents () { this.node.emit('toggle', this); if (this._checkEvents) { ComponentEventHandler.emitEvents(this._checkEvents, this); @@ -267,7 +267,7 @@ export class ToggleComponent extends ButtonComponent { } } -// cc.Toggle = module.exports = Toggle; +cc.ToggleComponent = ToggleComponent; // var js = require('../platform/js'); diff --git a/cocos/3d/ui/components/toggle-group-component.ts b/cocos/3d/ui/components/toggle-group-component.ts index e27de57a10..7792220a0f 100644 --- a/cocos/3d/ui/components/toggle-group-component.ts +++ b/cocos/3d/ui/components/toggle-group-component.ts @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ import { Component} from '../../../components/component'; -import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { ToggleComponent} from './toggle-component'; /** @@ -42,8 +42,8 @@ import { ToggleComponent} from './toggle-component'; @executeInEditMode export class ToggleGroupComponent extends Component { @property - _allowSwitchOff: boolean = false; - _toggleItems: ToggleComponent[] = []; + private _allowSwitchOff: boolean = false; + private _toggleItems: ToggleComponent[] = []; /** * !#en If this setting is true, a toggle could be switched off and on when pressed. @@ -53,11 +53,11 @@ export class ToggleGroupComponent extends Component { * @property {Boolean} allowSwitchOff */ @property - get allowSwitchOff() { + get allowSwitchOff () { return this._allowSwitchOff; } - set allowSwitchOff(value: boolean) { + set allowSwitchOff (value: boolean) { this._allowSwitchOff = value; } @@ -66,18 +66,18 @@ export class ToggleGroupComponent extends Component { * !#zh 只读属性,返回 toggleGroup 管理的 toggle 数组引用 * @property {Array} toggleItems */ - get toggleItems() { + get toggleItems () { return this._toggleItems; } - start() { + public start () { this._makeAtLeastOneToggleChecked(); } - updateToggles(toggle: ToggleComponent) { - if (!this.enabledInHierarchy) return; + public updateToggles (toggle: ToggleComponent) { + if (!this.enabledInHierarchy) { return; } - this._toggleItems.forEach(function (item) { + this._toggleItems.forEach((item) => { if (toggle.isChecked) { if (item !== toggle && item.isChecked && item.enabled) { item.isChecked = false; @@ -86,25 +86,25 @@ export class ToggleGroupComponent extends Component { }); } - addToggle(toggle: ToggleComponent) { - var index = this._toggleItems.indexOf(toggle); + public addToggle (toggle: ToggleComponent) { + const index = this._toggleItems.indexOf(toggle); if (index === -1) { this._toggleItems.push(toggle); } this._allowOnlyOneToggleChecked(); } - removeToggle(toggle: ToggleComponent) { - var index = this._toggleItems.indexOf(toggle); + public removeToggle (toggle: ToggleComponent) { + const index = this._toggleItems.indexOf(toggle); if (index > -1) { this._toggleItems.splice(index, 1); } this._makeAtLeastOneToggleChecked(); } - _allowOnlyOneToggleChecked() { - var isChecked = false; - this._toggleItems.forEach(function (item) { + public _allowOnlyOneToggleChecked () { + let isChecked = false; + this._toggleItems.forEach((item) => { if (isChecked && item.enabled) { item.isChecked = false; } @@ -117,8 +117,8 @@ export class ToggleGroupComponent extends Component { return isChecked; } - _makeAtLeastOneToggleChecked() { - var isChecked = this._allowOnlyOneToggleChecked(); + public _makeAtLeastOneToggleChecked () { + const isChecked = this._allowOnlyOneToggleChecked(); if (!isChecked && !this._allowSwitchOff) { if (this._toggleItems.length > 0) { @@ -127,3 +127,5 @@ export class ToggleGroupComponent extends Component { } } } + +cc.ToggleGroupComponent = ToggleGroupComponent; diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index ac74dc74a5..4c97c20f94 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -import { RenderableComponent } from '../../../3d/framework/renderable-component'; import { ccclass, executeInEditMode, @@ -35,9 +34,12 @@ import macro from '../../../core/platform/CCMacro'; import { Color } from '../../../core/value-types/index'; import { RenderData } from '../../../renderer/ui/renderData'; import { UI } from '../../../renderer/ui/ui'; +import { EventType} from '../../../scene-graph/node-event-enum'; import { IAssembler, IAssemblerManager } from '../assembler/assembler'; import { CanvasComponent } from './canvas-component'; -import { EventType} from '../../../scene-graph/node-event-enum'; +import { Component } from '../../../components/component'; +import { Material } from '../../assets/material'; +import { RenderableComponent } from '../../framework/renderable-component'; /** * !#en @@ -52,7 +54,7 @@ import { EventType} from '../../../scene-graph/node-event-enum'; @executionOrder(100) @requireComponent(cc.UITransformComponent) @executeInEditMode -export class UIRenderComponent extends RenderableComponent { +export class UIRenderComponent extends Component { /** * !#en specify the source Blend Factor, this will generate a custom material object @@ -99,11 +101,11 @@ export class UIRenderComponent extends RenderableComponent { * !#zh 渲染先后顺序,按照广度渲染排列,同级节点下进行一次排列 */ @property - get priority() { + get priority () { return this._priority; } - set priority(value) { + set priority (value) { this._priority = value; } @@ -112,18 +114,45 @@ export class UIRenderComponent extends RenderableComponent { * !#zh 渲染颜色 * @property color */ - get color() { + @property + get color () { return this._color; } - set color(value) { + set color (value) { if (this._color === value) { return; } this._color = value; + this.markForUpdateRenderData(); } + /** + * !#en render material + * !#zh 渲染共用材质 + * @property material + */ + @property({ + type: Material + }) + get sharedMaterial() { + return this._sharedMaterial; + } + + set sharedMaterial(value) { + if (this._sharedMaterial === value) { + return; + } + + this._sharedMaterial = value; + this._instanceMaterial(); + } + + /** + * !#en find the rendered camera + * !#zh 查找被渲染相机 + */ get visibility () { return this._visibility; } @@ -132,20 +161,37 @@ export class UIRenderComponent extends RenderableComponent { return this._renderData; } + get material() { + return this._material; + } + + set material(value) { + if (this._material === value) { + return; + } + + this._material = value; + } + public static Assembler: IAssemblerManager | null = null; - protected _assembler: IAssembler | null = null; - - protected _postAssembler: IAssembler | null = null; - protected _renderDataPoolID: number = -1; - protected _visibility: number = -1; - - protected _srcBlendFactor: number = macro.BlendFactor.SRC_ALPHA; - protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA; + @property + protected _srcBlendFactor = macro.BlendFactor.SRC_ALPHA; + @property + protected _dstBlendFactor = macro.BlendFactor.ONE_MINUS_SRC_ALPHA; @property protected _color: Color = Color.WHITE; @property - protected _priority: number = 0; + protected _priority = 0; + @property + private _sharedMaterial: Material | null = null; + @property + protected _material: Material | null = null; + + protected _assembler: IAssembler | null = null; + protected _postAssembler: IAssembler | null = null; + protected _renderDataPoolID = -1; + protected _visibility = -1; protected _renderData: RenderData | null = null; // _allocedDatas = []; // _vertexFormat = null; @@ -157,6 +203,10 @@ export class UIRenderComponent extends RenderableComponent { // this._postAssembler = this.constructor._postAssembler; } + public __preload(){ + this._instanceMaterial(); + } + public onEnable () { let parent = this.node; while (parent) { @@ -172,9 +222,9 @@ export class UIRenderComponent extends RenderableComponent { parent = parent.parent; } - this.node.on(EventType.ANCHOR_CHANGED, this._stateChange,this); + this.node.on(EventType.ANCHOR_CHANGED, this._stateChange, this); this.node.on(EventType.TRANSFORM_CHANGED, this._stateChange, this); - this.node.on(EventType.SIZE_CHANGED, this._stateChange,this); + this.node.on(EventType.SIZE_CHANGED, this._stateChange, this); // if (this.node._renderComponent) { // this.node._renderComponent.enabled = false; // } @@ -205,7 +255,7 @@ export class UIRenderComponent extends RenderableComponent { // return this._enabled; // } - markForUpdateRenderData(enable: boolean = true) { + public markForUpdateRenderData (enable: boolean = true) { // if (enable && this._canRender()) { // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; // } @@ -213,15 +263,15 @@ export class UIRenderComponent extends RenderableComponent { // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; // } - if (enable /*&& this._canRender()*/) { + // if (enable /*&& this._canRender()*/) { // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; const renderData = this._renderData; if (renderData) { - renderData.uvDirty = true; - renderData.vertDirty = true; + renderData.uvDirty = enable; + renderData.vertDirty = enable; } - } + // } // else if (!enable) { // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; // } @@ -272,6 +322,25 @@ export class UIRenderComponent extends RenderableComponent { this._renderData = null; } + public updateAssembler (render: UI) { + if (!this._assembler) { + return; + } + if (this._assembler.updateRenderData) { + this._assembler.updateRenderData(this); + } + this._assembler.fillBuffers(this, render); + } + + public postUpdateAssembler () { + if (!this._postAssembler) { + return; + } + if (this._postAssembler.updateRenderData) { + this._postAssembler.updateRenderData(this); + } + } + protected _updateColor () { const material = this.material; if (material) { @@ -299,29 +368,18 @@ export class UIRenderComponent extends RenderableComponent { // } } - private _stateChange(){ + private _stateChange (){ this.markForUpdateRenderData(); } - public updateAssembler (render: UI) { - if (!this._assembler) { - return; - } - if (this._assembler.updateRenderData) { - this._assembler.updateRenderData(this); - } - this._assembler.fillBuffers(this, render); - } - - public postUpdateAssembler () { - if (!this._postAssembler) { - return; - } - if (this._postAssembler.updateRenderData) { - this._postAssembler.updateRenderData(this); + private _instanceMaterial(){ + if (this._sharedMaterial) { + this._material = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); } } } // RenderComponent._assembler = null; // RenderComponent._postAssembler = null; + +cc.UIRenderComponent = UIRenderComponent; diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index 862ee787d5..0d84dd8be9 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -1,18 +1,16 @@ import { Component} from '../../../components/component'; -import { ccclass, executeInEditMode, executionOrder, property, menu } from '../../../core/data/class-decorator'; -import { Mat4 } from '../../../core/value-types'; -import Size from '../../../core/value-types/size'; -import Vec2 from '../../../core/value-types/vec2'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Mat4, Vec3, Vec2, Size, Rect } from '../../../core/value-types'; import * as math from '../../../core/vmath/index'; import { EventType } from '../../../scene-graph/node-event-enum'; import { MaskComponent } from './mask-component'; import { UIRenderComponent } from './ui-render-component'; -const _vec2a = cc.v2(); -const _vec2b = cc.v2(); -const _mat4_temp = cc.mat4(); -const _worldMatrix = cc.mat4(); - +const _vec2a = new Vec2(); +const _vec2b = new Vec2(); +const _mat4_temp = new Mat4(); +const _matrix = new Mat4(); +const _worldMatrix = new Mat4(); @ccclass('cc.UITransformComponent') @executionOrder(100) @@ -26,12 +24,13 @@ export class UITransformComponent extends Component { } set contentSize (value) { - // if (this._contentSize.equals(value)) { - // return; - // } + if (this._contentSize.equals(value)) { + return; + } this._contentSize.set(value); - this.node.emit(EventType.SIZE_CHANGED); + this.node.emit(EventType.SIZE_CHANGED, this._contentSize); + } get width () { @@ -39,12 +38,12 @@ export class UITransformComponent extends Component { } set width (value) { - // if (this._contentSize.width === value) { - // return; - // } + if (this._contentSize.width === value) { + return; + } this._contentSize.width = value; - this.node.emit(EventType.SIZE_CHANGED); + this.node.emit(EventType.SIZE_CHANGED, this._contentSize); } get height () { @@ -52,12 +51,12 @@ export class UITransformComponent extends Component { } set height (value) { - // if (this._contentSize.height === value) { - // return; - // } + if(this.contentSize.height === value){ + return; + } this._contentSize.height = value; - this.node.emit(EventType.SIZE_CHANGED); + this.node.emit(EventType.SIZE_CHANGED, this._contentSize); } @property @@ -66,12 +65,12 @@ export class UITransformComponent extends Component { } set anchorPoint (value) { - // if (this._anchorPoint.equals(value)) { - // return; - // } + if (this._anchorPoint.equals(value)) { + return; + } this._anchorPoint.set(value); - this.node.emit(EventType.ANCHOR_CHANGED); + this.node.emit(EventType.ANCHOR_CHANGED, this._anchorPoint); } get anchorX () { @@ -79,12 +78,12 @@ export class UITransformComponent extends Component { } set anchorX (value) { - // if (this._anchorPoint.x === value) { - // return; - // } + if (this._anchorPoint.x === value) { + return; + } this._anchorPoint.x = value; - this.node.emit(EventType.ANCHOR_CHANGED); + this.node.emit(EventType.ANCHOR_CHANGED, this._anchorPoint); } get anchorY () { @@ -92,12 +91,12 @@ export class UITransformComponent extends Component { } set anchorY (value) { - // if (this._anchorPoint.y === value) { - // return; - // } + if (this._anchorPoint.y === value) { + return; + } this._anchorPoint.y = value; - this.node.emit(EventType.ANCHOR_CHANGED); + this.node.emit(EventType.ANCHOR_CHANGED, this._anchorPoint); } public static EventType = EventType; @@ -129,33 +128,24 @@ export class UITransformComponent extends Component { */ public setContentSize (size: Size|number, height?: number) { const locContentSize = this._contentSize; - let clone; if (height === undefined) { size = size as Size; if ((size.width === locContentSize.width) && (size.height === locContentSize.height)) { return; } - if (CC_EDITOR) { - clone = cc.size(locContentSize.width, locContentSize.height); - } + locContentSize.width = size.width; locContentSize.height = size.height; } else { if ((size === locContentSize.width) && (height === locContentSize.height)) { return; } - if (CC_EDITOR) { - clone = cc.size(locContentSize.width, locContentSize.height); - } - locContentSize.width = size; + + locContentSize.width = size as number; locContentSize.height = height; } - if (CC_EDITOR) { - this.node.emit(EventType.SIZE_CHANGED, clone); - } - else { - this.node.emit(EventType.SIZE_CHANGED); - } + + this.node.emit(EventType.SIZE_CHANGED, this._contentSize); } /** @@ -193,16 +183,18 @@ export class UITransformComponent extends Component { if ((point === locAnchorPoint.x) && (y === locAnchorPoint.y)) { return; } - locAnchorPoint.x = point; + locAnchorPoint.x = point as number; locAnchorPoint.y = y; } + // this.setLocalDirty(LocalDirtyFlag.POSITION); // if (this._eventMask & ANCHOR_ON) { - this.node.emit(EventType.ANCHOR_CHANGED); + this.node.emit(EventType.ANCHOR_CHANGED, this._anchorPoint); + // } } - public isHit(point: Vec2, listener: EventListener) { + public isHit (point: Vec2, listener?: EventListener) { const w = this._contentSize.width; const h = this._contentSize.height; const cameraPt = _vec2a; @@ -274,16 +266,19 @@ export class UITransformComponent extends Component { * !#zh * 将一个点转换到节点 (局部) 空间坐标系,这个坐标系以锚点为原点。 * @method convertToNodeSpaceAR - * @param {Vec2} worldPoint - * @return {Vec2} + * @param {Vec3} worldPoint + * @return {Vec3} * @example * var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); */ - public convertToNodeSpaceAR (worldPoint) { + public convertToNodeSpaceAR(out: Vec3, worldPoint: Vec3) { const matrix = new Mat4(); this.node.getWorldMatrix(matrix); math.mat4.invert(_mat4_temp, matrix); - const out = new cc.Vec2(); + if (!out) { + out = new Vec3(); + } + return math.vec2.transformMat4(out, worldPoint, _mat4_temp); } @@ -298,9 +293,92 @@ export class UITransformComponent extends Component { * @example * var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); */ - public convertToWorldSpaceAR (nodePoint) { + public convertToWorldSpaceAR(out: Vec3, nodePoint: Vec3) { this.node.getWorldMatrix(_worldMatrix); - const out = new cc.Vec2(); + if (!out) { + out = new Vec3(); + } + return math.vec2.transformMat4(out, nodePoint, _worldMatrix); } + + /** + * !#en + * Returns a "local" axis aligned bounding box of the node.
+ * The returned box is relative only to its parent. + * !#zh 返回父节坐标系下的轴向对齐的包围盒。 + * @method getBoundingBox + * @return {Rect} The calculated bounding box of the node + * @example + * var boundingBox = node.getBoundingBox(); + */ + public getBoundingBox() { + math.mat4.fromRTS(_matrix, this.node.getRotation(), this.node.getPosition(), this.node.getScale()); + let width = this._contentSize.width; + let height = this._contentSize.height; + let rect = new Rect( + -this._anchorPoint.x * width, + -this._anchorPoint.y * height, + width, + height); + return rect.transformMat4(rect, _matrix); + } + + /** + * !#en + * Returns a "world" axis aligned bounding box of the node.
+ * The bounding box contains self and active children's world bounding box. + * !#zh + * 返回节点在世界坐标系下的对齐轴向的包围盒(AABB)。
+ * 该边框包含自身和已激活的子节点的世界边框。 + * @method getBoundingBoxToWorld + * @return {Rect} + * @example + * var newRect = node.getBoundingBoxToWorld(); + */ + public getBoundingBoxToWorld() { + if (this.node.parent) { + this.node.parent.getWorldMatrix(_worldMatrix); + return this.getBoundingBoxTo(_worldMatrix); + } else { + return this.getBoundingBox(); + } + } + + public getBoundingBoxTo(parentMat: Mat4) { + math.mat4.fromRTS(_matrix, this.node.getRotation(), this.node.getPosition(), this.node.getScale()); + let width = this._contentSize.width; + let height = this._contentSize.height; + let rect = new Rect( + -this._anchorPoint.x * width, + -this._anchorPoint.y * height, + width, + height); + + math.mat4.mul(_worldMatrix, parentMat, _matrix); + rect.transformMat4(rect, _worldMatrix); + + //query child's BoundingBox + if (!this.node.children) { + return rect; + } + + var locChildren = this.node.children; + for (var i = 0; i < locChildren.length; i++) { + var child = locChildren[i]; + if (child && child.active) { + const uiTransform = child.getComponent(UITransformComponent); + if (uiTransform) { + var childRect = uiTransform.getBoundingBoxTo(parentMat); + if (childRect) { + rect.union(rect, childRect); + } + } + } + } + + return rect; + } } + +cc.UITransformComponent = UITransformComponent; diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts index 24c9160a1d..868a112f99 100644 --- a/cocos/3d/ui/components/widget-component.ts +++ b/cocos/3d/ui/components/widget-component.ts @@ -24,10 +24,12 @@ THE SOFTWARE. ****************************************************************************/ -import { widgetManager } from '../../../2d/base-ui/widget-manager'; +import { widgetManager } from './widget-manager'; import { Component} from '../../../components/component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ccclass, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../../core/data/class-decorator'; import { Node } from '../../../scene-graph/index'; +import { UITransformComponent } from './ui-transfrom-component'; +import { ccenum } from '../../../core/value-types/enum'; /** * !#en Enum for Widget's alignment mode, indicating when the widget should refresh. * !#zh Widget 的对齐模式,表示 Widget 应该何时刷新。 @@ -54,17 +56,28 @@ import { Node } from '../../../scene-graph/index'; * !#zh 始终保持对齐。 * @property {Number} ALWAYS */ -const AlignMode = widgetManager.AlignMode; -const AlignFlags = widgetManager._AlignFlags; -const TOP = AlignFlags.TOP; -const MID = AlignFlags.MID; -const BOT = AlignFlags.BOT; -const LEFT = AlignFlags.LEFT; -const CENTER = AlignFlags.CENTER; -const RIGHT = AlignFlags.RIGHT; -const TOP_BOT = TOP | BOT; -const LEFT_RIGHT = LEFT | RIGHT; +export enum AlignMode { + ONCE = 0, + ON_WINDOW_RESIZE = 1, + ALWAYS = 2, +} + +ccenum(AlignMode); + +export enum AlignFlags { + TOP = 1 << 0, + MID = 1 << 1, + BOT = 1 << 2, + LEFT = 1 << 3, + CENTER = 1 << 4, + RIGHT = 1 << 5, + HORIZONTAL = LEFT | CENTER | RIGHT, + VERTICAL = TOP | MID | BOT, +} + +const TOP_BOT = AlignFlags.TOP | AlignFlags.BOT; +const LEFT_RIGHT = AlignFlags.LEFT | AlignFlags.RIGHT; /** * !#en @@ -81,9 +94,9 @@ const LEFT_RIGHT = LEFT | RIGHT; @ccclass('cc.WidgetComponent') @executionOrder(100) @menu('UI/Widget') +@requireComponent(UITransformComponent) @executeInEditMode export class WidgetComponent extends Component { - /** * !#en Specifies an alignment target that can only be one of the parent nodes of the current node. * The default value is null, and when null, indicates the current parent. @@ -100,14 +113,12 @@ export class WidgetComponent extends Component { set target (value) { this._target = value; - if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) { + if (CC_EDITOR /*&& !cc.engine._isPlaying*/ && this.node.parent) { // adjust the offsets to keep the size and position unchanged after target chagned - // widgetManager.updateOffsetsToStayPut(this); + widgetManager.updateOffsetsToStayPut(this); } } - // ENABLE ALIGN ? - /** * !#en Whether to align the top. * !#zh 是否对齐上边。 @@ -117,10 +128,10 @@ export class WidgetComponent extends Component { */ @property get isAlignTop () { - return (this._alignFlags & TOP) > 0; + return (this._alignFlags & AlignFlags.TOP) > 0; } set isAlignTop (value) { - this._setAlign(TOP, value); + this._setAlign(AlignFlags.TOP, value); } /** @@ -132,10 +143,10 @@ export class WidgetComponent extends Component { */ @property get isAlignBottom () { - return (this._alignFlags & BOT) > 0; + return (this._alignFlags & AlignFlags.BOT) > 0; } set isAlignBottom (value) { - this._setAlign(BOT, value); + this._setAlign(AlignFlags.BOT, value); } /** @@ -147,10 +158,10 @@ export class WidgetComponent extends Component { */ @property get isAlignLeft () { - return (this._alignFlags & LEFT) > 0; + return (this._alignFlags & AlignFlags.LEFT) > 0; } set isAlignLeft (value) { - this._setAlign(LEFT, value); + this._setAlign(AlignFlags.LEFT, value); } /** @@ -162,10 +173,10 @@ export class WidgetComponent extends Component { */ @property get isAlignRight () { - return (this._alignFlags & RIGHT) > 0; + return (this._alignFlags & AlignFlags.RIGHT) > 0; } set isAlignRight (value) { - this._setAlign(RIGHT, value); + this._setAlign(AlignFlags.RIGHT, value); } /** @@ -179,15 +190,15 @@ export class WidgetComponent extends Component { */ @property get isAlignVerticalCenter () { - return (this._alignFlags & MID) > 0; + return (this._alignFlags & AlignFlags.MID) > 0; } set isAlignVerticalCenter (value) { if (value) { this.isAlignTop = false; this.isAlignBottom = false; - this._alignFlags |= MID; + this._alignFlags |= AlignFlags.MID; } else { - this._alignFlags &= ~MID; + this._alignFlags &= ~AlignFlags.MID; } } @@ -202,15 +213,15 @@ export class WidgetComponent extends Component { */ @property get isAlignHorizontalCenter () { - return (this._alignFlags & CENTER) > 0; + return (this._alignFlags & AlignFlags.CENTER) > 0; } set isAlignHorizontalCenter (value) { if (value) { this.isAlignLeft = false; this.isAlignRight = false; - this._alignFlags |= CENTER; + this._alignFlags |= AlignFlags.CENTER; } else { - this._alignFlags &= ~CENTER; + this._alignFlags &= ~AlignFlags.CENTER; } } @@ -475,6 +486,10 @@ export class WidgetComponent extends Component { this._isAbsVerticalCenter = value; } + get alignFlags(){ + return this._alignFlags; + } + public static AlignMode = AlignMode; /** * !#zh: 对齐开关,由 AlignFlags 组成 @@ -486,7 +501,7 @@ export class WidgetComponent extends Component { */ private _alignFlags = 0; private _wasAlignOnce = false; - @property + // @property private _target: Node | null = null; @property private _left = 0; @@ -547,6 +562,7 @@ export class WidgetComponent extends Component { // this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; // this._wasAlignOnce = false; // } + this._target = this.node.parent; if(this._alignMode === AlignMode.ONCE){ this._wasAlignOnce = true; } @@ -560,7 +576,7 @@ export class WidgetComponent extends Component { widgetManager.remove(this); } - private _setAlign (flag, isAlign) { + private _setAlign (flag: AlignFlags, isAlign: boolean) { const current = (this._alignFlags & flag) > 0; if (isAlign === current) { return; @@ -573,9 +589,9 @@ export class WidgetComponent extends Component { this.isAlignHorizontalCenter = false; if (this.isStretchWidth) { // become stretch - this._originalWidth = this.node.width; + this._originalWidth = this.node.width!; // test check conflict - if (CC_EDITOR && !cc.engine.isPlaying) { + if (CC_EDITOR /*&& !cc.engine.isPlaying*/) { // _Scene.DetectConflict.checkConflict_Widget(this); } } @@ -583,7 +599,7 @@ export class WidgetComponent extends Component { this.isAlignVerticalCenter = false; if (this.isStretchHeight) { // become stretch - this._originalHeight = this.node.height; + this._originalHeight = this.node.height!; // test check conflict if (CC_EDITOR && !cc.engine.isPlaying) { // _Scene.DetectConflict.checkConflict_Widget(this); @@ -591,9 +607,9 @@ export class WidgetComponent extends Component { } } - if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) { + if (CC_EDITOR && !cc.engine._isPlaying && this.node.parent) { // adjust the offsets to keep the size and position unchanged after alignment chagned - // widgetManager.updateOffsetsToStayPut(this, flag); + widgetManager.updateOffsetsToStayPut(this, flag); } } else { if (isHorizontal) { diff --git a/cocos/3d/ui/components/widget-manager.ts b/cocos/3d/ui/components/widget-manager.ts new file mode 100644 index 0000000000..6c654d981f --- /dev/null +++ b/cocos/3d/ui/components/widget-manager.ts @@ -0,0 +1,600 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { array } from '../../../core/utils/js'; +import { Size, Vec3 } from '../../../core/value-types'; +import { vec3 } from '../../../core/vmath'; +import { Node } from '../../../scene-graph/node'; +import { CanvasComponent } from './canvas-component'; +import { UIRenderComponent } from './ui-render-component'; +import { AlignFlags, AlignMode, WidgetComponent } from './widget-component'; +const Event = Node.EventType; + +const _tempPos = new Vec3(); + +// returns a readonly size of the node +export function getReadonlyNodeSize (parent: Node) { + if (parent instanceof cc.Scene) { + if (CC_EDITOR) { + const canvasComp = parent.getComponentInChildren(CanvasComponent); + if (!canvasComp) { + throw new Error('There is no CanvasComponent here'); + } + + return canvasComp.designResolution; + } + + return cc.visibleRect; + } else { + return parent.getContentSize(); + } +} + +export function computeInverseTransForTarget (widgetNode: Node, target: Node, out_inverseTranslate: Vec3, out_inverseScale: Vec3) { + let scale = widgetNode.parent!.getScale(); + let scaleX = scale.x; + let scaleY = scale.y; + let translateX = 0; + let translateY = 0; + for (const node = widgetNode.parent; ;) { + if (!node) { + // ERROR: widgetNode should be child of target + // out_inverseTranslate.x = out_inverseTranslate.y = 0; + // out_inverseScale.x = out_inverseScale.y = 1; + return; + } + + const pos = node.getPosition(); + translateX += pos.x; + translateY += pos.y; + // node = node.parent; // loop increment + + if (node !== target) { + scale = node.getScale(); + const sx = scale.x; + const sy = scale.y; + translateX *= sx; + translateY *= sy; + scaleX *= sx; + scaleY *= sy; + } else { + break; + } + } + out_inverseScale.x = scaleX !== 0 ? (1 / scaleX) : 1; + out_inverseScale.y = scaleY !== 0 ? (1 / scaleY) : 1; + out_inverseTranslate.x = -translateX; + out_inverseTranslate.y = -translateY; +} + +const tInverseTranslate = cc.Vec2.ZERO; +const tInverseScale = cc.Vec2.ONE; + +// align to borders by adjusting node's position and size (ignore rotation) +function align (node: Node, widget: WidgetComponent) { + const hasTarget = widget.target; + let target; + let inverseTranslate; + let inverseScale; + if (hasTarget) { + target = hasTarget; + inverseTranslate = tInverseTranslate; + inverseScale = tInverseScale; + computeInverseTransForTarget(node, target, inverseTranslate, inverseScale); + } else { + target = node.parent; + } + const targetSize = getReadonlyNodeSize(target); + const targetAnchor = target.getAnchorPoint(); + + const isRoot = !CC_EDITOR && target instanceof cc.Scene; + node.getPosition(_tempPos); + let x = _tempPos.x; + let y = _tempPos.y; + const anchor = node.getAnchorPoint(); + const scale = node.getScale(); + + if (widget.alignFlags & AlignFlags.HORIZONTAL) { + let localLeft = 0; + let localRight = 0; + const targetWidth = targetSize.width; + if (isRoot) { + localLeft = cc.visibleRect.left.x; + localRight = cc.visibleRect.right.x; + } else { + localLeft = -targetAnchor.x * targetWidth; + localRight = localLeft + targetWidth; + } + + // adjust borders according to offsets + localLeft += widget.isAbsoluteLeft ? widget.left : widget.left * targetWidth; + localRight -= widget.isAbsoluteRight ? widget.right : widget.right * targetWidth; + + if (hasTarget) { + localLeft += inverseTranslate.x; + localLeft *= inverseScale.x; + localRight += inverseTranslate.x; + localRight *= inverseScale.x; + } + + let width = 0; + let anchorX = anchor.x; + let scaleX = scale.x; + if (scaleX < 0) { + anchorX = 1.0 - anchorX; + scaleX = -scaleX; + } + if (widget.isStretchWidth) { + width = localRight - localLeft; + if (scaleX !== 0) { + node.width = width / scaleX; + } + x = localLeft + anchorX * width; + } else { + width = node.width * scaleX; + if (widget.isAlignHorizontalCenter) { + let localHorizontalCenter = widget.isAbsoluteHorizontalCenter ? + widget.horizontalCenter : widget.horizontalCenter * targetWidth; + let targetCenter = (0.5 - targetAnchor.x) * targetSize.width; + if (hasTarget) { + localHorizontalCenter *= inverseScale.x; + targetCenter += inverseTranslate.x; + targetCenter *= inverseScale.x; + } + x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter; + } else if (widget.isAlignLeft) { + x = localLeft + anchorX * width; + } else { + x = localRight + (anchorX - 1) * width; + } + } + } + + if (widget.alignFlags & AlignFlags.VERTICAL) { + + let localTop = 0; + let localBottom = 0; + const targetHeight = targetSize.height; + if (isRoot) { + localBottom = cc.visibleRect.bottom.y; + localTop = cc.visibleRect.top.y; + } else { + localBottom = -targetAnchor.y * targetHeight; + localTop = localBottom + targetHeight; + } + + // adjust borders according to offsets + localBottom += widget.isAbsoluteBottom ? widget.bottom : widget.bottom * targetHeight; + localTop -= widget.isAbsoluteTop ? widget.top : widget.top * targetHeight; + + if (hasTarget) { + // transform + localBottom += inverseTranslate.y; + localBottom *= inverseScale.y; + localTop += inverseTranslate.y; + localTop *= inverseScale.y; + } + + let height; + let anchorY = anchor.y; + let scaleY = scale.y; + if (scaleY < 0) { + anchorY = 1.0 - anchorY; + scaleY = -scaleY; + } + if (widget.isStretchHeight) { + height = localTop - localBottom; + if (scaleY !== 0) { + node.height = height / scaleY; + } + y = localBottom + anchorY * height; + } else { + height = node.height * scaleY; + if (widget.isAlignVerticalCenter) { + let localVerticalCenter = widget.isAbsoluteVerticalCenter ? + widget.verticalCenter : widget.verticalCenter * targetHeight; + let targetMiddle = (0.5 - targetAnchor.y) * targetSize.height; + if (hasTarget) { + localVerticalCenter *= inverseScale.y; + targetMiddle += inverseTranslate.y; + targetMiddle *= inverseScale.y; + } + y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter; + } else if (widget.isAlignBottom) { + y = localBottom + anchorY * height; + } else { + y = localTop + (anchorY - 1) * height; + } + } + } + + node.setPosition(x, y, _tempPos.z); +} + +function visitNode (node: Node) { + const widget = node.uiWidgetComp; + if (widget) { + if (CC_DEV) { + // widget._validateTargetInDEV(); + } + align(node, widget); + if ((!CC_EDITOR || widgetManager.animationState!.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) { + widget.enabled = false; + } else { + activeWidgets.push(widget); + } + } + const children = node.children; + for (const child of children) { + if (child.active) { + visitNode(child); + } + } +} + +// if (CC_EDITOR) { +// const animationState = { +// previewing: false, +// time: 0, +// animatedSinceLastFrame: false, +// }; +// } + +function refreshScene () { + // check animation editor + // if (CC_EDITOR && !Editor.isBuilder) { + // var AnimUtils = Editor.require('scene://utils/animation'); + // var EditMode = Editor.require('scene://edit-mode'); + // if (AnimUtils && EditMode) { + // var nowPreviewing = (EditMode.curMode().name === 'animation' && !!AnimUtils.Cache.animation); + // if (nowPreviewing !== animationState.previewing) { + // animationState.previewing = nowPreviewing; + // if (nowPreviewing) { + // animationState.animatedSinceLastFrame = true; + // let component = cc.engine.getInstanceById(AnimUtils.Cache.component); + // if (component) { + // let animation = component.getAnimationState(AnimUtils.Cache.animation); + // animationState.time = animation.time; + // } + // } + // else { + // animationState.animatedSinceLastFrame = false; + // } + // } + // else if (nowPreviewing) { + // let component = cc.engine.getInstanceById(AnimUtils.Cache.component); + // if (component) { + // let animation = component.getAnimationState(AnimUtils.Cache.animation); + // if (animationState.time !== animation.time) { + // animationState.animatedSinceLastFrame = true; + // animationState.time = AnimUtils.Cache.animation.time; + // } + // } + // } + // } + // } + + const scene = cc.director.getScene(); + if (scene) { + widgetManager.isAligning = true; + if (widgetManager._nodesOrderDirty) { + activeWidgets.length = 0; + visitNode(scene); + widgetManager._nodesOrderDirty = false; + } + else { + const i = 0; + let widget: WidgetComponent | null = null; + const iterator = widgetManager._activeWidgetsIterator; + // var AnimUtils; + // if (CC_EDITOR && + // (AnimUtils = Editor.require('scene://utils/animation')) && + // AnimUtils.Cache.animation) { + // var editingNode = cc.engine.getInstanceById(AnimUtils.Cache.rNode); + // if (editingNode) { + // for (i = activeWidgets.length - 1; i >= 0; i--) { + // widget = activeWidgets[i]; + // var node = widget.node; + // if (widget.alignMode !== AlignMode.ALWAYS && + // animationState.animatedSinceLastFrame && + // node.isChildOf(editingNode) + // ) { + // // widget contains in activeWidgets should aligned at least once + // widget.enabled = false; + // } + // else { + // align(node, widget); + // } + // } + // } + // } + // else { + // loop reversely will not help to prevent out of sync + // because user may remove more than one item during a step. + for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) { + widget = activeWidgets[iterator.i]; + align(widget.node, widget); + } + // } + } + widgetManager.isAligning = false; + } + + // check animation editor + if (CC_EDITOR) { + widgetManager.animationState!.animatedSinceLastFrame = false; + } +} + +function adjustWidgetToAllowMovingInEditor (oldPos: Vec3) { + if (!CC_EDITOR) { + return; + } + + if (widgetManager.isAligning) { + return; + } + + const self = this as WidgetComponent; + const newPos = self.node.getPosition(); + const delta = newPos.sub(oldPos); + + let target = self.node.parent!; + const inverseScale = cc.Vec2.ONE; + + if (self.target) { + target = self.target; + computeInverseTransForTarget(self.node, target, new cc.Vec2(), inverseScale); + } + + const targetSize = getReadonlyNodeSize(target); + const deltaInPercent = new Vec3(); + if (targetSize.width !== 0 && targetSize.height !== 0) { + vec3.set(deltaInPercent, delta.x / targetSize.width, delta.y / targetSize.height, deltaInPercent.z); + } + + if (self.isAlignTop) { + self.top -= (self.isAbsoluteTop ? delta.y : deltaInPercent.y) * inverseScale.y; + } + if (self.isAlignBottom) { + self.bottom += (self.isAbsoluteBottom ? delta.y : deltaInPercent.y) * inverseScale.y; + } + if (self.isAlignLeft) { + self.left += (self.isAbsoluteLeft ? delta.x : deltaInPercent.x) * inverseScale.x; + } + if (self.isAlignRight) { + self.right -= (self.isAbsoluteRight ? delta.x : deltaInPercent.x) * inverseScale.x; + } + if (self.isAlignHorizontalCenter) { + self.horizontalCenter += (self.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x) * inverseScale.x; + } + if (self.isAlignVerticalCenter) { + self.verticalCenter += (self.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; + } +} + +function adjustWidgetToAllowResizingInEditor (oldSize: Size) { + if (!CC_EDITOR) { + return; + } + + if (widgetManager.isAligning) { + return; + } + + const self = this as WidgetComponent; + const newSize = self.node.getContentSize(); + const delta = new Vec3(newSize.width - oldSize.width, newSize.height - oldSize.height, 0); + + let target = self.node.parent!; + const inverseScale = new Vec3(1, 1, 1); + if (self.target) { + target = self.target; + computeInverseTransForTarget(self.node, target, new Vec3(), inverseScale); + } + + const targetSize = getReadonlyNodeSize(target); + const deltaInPercent = new Vec3(); + if (targetSize.width !== 0 && targetSize.height !== 0) { + vec3.set(deltaInPercent, delta.x / targetSize.width, delta.y / targetSize.height, deltaInPercent.z); + } + + const anchor = self.node.getAnchorPoint(); + + if (self.isAlignTop) { + self.top -= (self.isAbsoluteTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; + } + if (self.isAlignBottom) { + self.bottom -= (self.isAbsoluteBottom ? delta.y : deltaInPercent.y) * anchor.y * inverseScale.y; + } + if (self.isAlignLeft) { + self.left -= (self.isAbsoluteLeft ? delta.x : deltaInPercent.x) * anchor.x * inverseScale.x; + } + if (self.isAlignRight) { + self.right -= (self.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; + } +} + +const activeWidgets: WidgetComponent[] = []; + +// updateAlignment from scene to node recursively +function updateAlignment (node: Node) { + const parent = node.parent; + if (parent && Node.isNode(parent)) { + updateAlignment(parent); + } + + // node._widget will be null when widget is disabled + const widget = node.uiWidgetComp || node.getComponent(WidgetComponent); + if (widget && parent) { + align(node, widget); + } +} + +const canvasList: CanvasComponent[] = []; + +export const widgetManager = cc._widgetManager = { + isAligning: false, + _nodesOrderDirty: false, + _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets), + // hack + animationState: CC_EDITOR ? { + previewing: false, + time: 0, + animatedSinceLastFrame: false, + } : null, + + init (director) { + director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene); + + if (CC_EDITOR /*&& cc.engine*/) { + + // cc.engien extends eventTarget + // cc.engine.on('design-resolution-changed', this.onResized.bind(this)); + } else { + if (cc.sys.isMobile) { + window.addEventListener('resize', this.onResized.bind(this)); + } else { + cc.view.on('canvas-resize', this.onResized, this); + } + } + }, + add (widget: WidgetComponent) { + widget.node.uiWidgetComp = widget; + this._nodesOrderDirty = true; + if (CC_EDITOR /*&& !cc.engine.isPlaying*/) { + const renderComp = widget.node.getComponent(UIRenderComponent); + if (renderComp){ + const canvasComp = cc.director.root.ui.getScreen(renderComp.visibility); + if (canvasComp && canvasList.indexOf(canvasComp) === -1) { + canvasList.push(canvasComp); + canvasComp.node.on('design-resolution-changed', this.onResized, this); + } + } + widget.node.on(Event.POSITION_PART, adjustWidgetToAllowMovingInEditor, widget); + widget.node.on(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); + } + }, + 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); + widget.node.off(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); + } + }, + onResized () { + const scene = cc.director.getScene(); + if (scene) { + this.refreshWidgetOnResized(scene); + } + }, + refreshWidgetOnResized (node: Node) { + if (Node.isNode(node)){ + // const widget = node.getComponent(WidgetComponent); + const widget: WidgetComponent | null = null; + if (widget) { + if (widget!.alignMode === AlignMode.ON_WINDOW_RESIZE) { + widget!.enabled = true; + } + } + } + + const children = node.children; + for (const child of children) { + this.refreshWidgetOnResized(child); + } + }, + updateOffsetsToStayPut (widget: WidgetComponent, e?: AlignFlags) { + function i (t: number, c: number) { + return Math.abs(t - c) > 1e-10 ? c : t; + } + const widgetNode = widget.node; + let widgetParent = widgetNode.parent; + if (widgetParent) { + const zero = new Vec3(); + const one = new Vec3(1, 1, 1); + if (widget.target) { + widgetParent = widget.target; + computeInverseTransForTarget(widgetNode, widgetParent!, zero, one); + } + + if (!e) { + return; + } + + const parentAP = widgetParent!.getAnchorPoint(); + const matchSize = getReadonlyNodeSize(widgetParent!); + const myAP = widgetNode.getAnchorPoint(); + const pos = widgetNode.getPosition(); + const alignFlags = AlignFlags; + const widgetNodeScale = widgetNode.getScale(); + + let temp = 0; + + if (e & alignFlags.LEFT) { + let l = -parentAP.x * matchSize.width; + l += zero.x; + l *= one.x; + temp = pos.x - myAP.x * widgetNode.width! * widgetNodeScale.x - l; + widget.isAbsoluteLeft || (temp /= matchSize.width); + temp /= one.x; + widget.left = i(widget.left, temp); + } + + if (e & alignFlags.RIGHT) { + let r = (1 - parentAP.x) * matchSize.width; + r += zero.x; + temp = (r *= one.x) - (pos.x + (1 - myAP.x) * widgetNode.width! * widgetNodeScale.x); + widget.isAbsoluteRight || (temp /= matchSize.width); + temp /= one.x; + widget.right = i(widget.right, temp); + } + + if (e & alignFlags.TOP) { + let t = (1 - parentAP.y) * matchSize.height; + t += zero.y; + temp = (t *= one.y) - (pos.y + (1 - myAP.y) * widgetNode.height! * widgetNodeScale.y); + widget.isAbsoluteTop || (temp /= matchSize.height); + temp /= one.y; + widget.top = i(widget.top, temp); + } + + if (e & alignFlags.BOT) { + let b = -parentAP.y * matchSize.height; + b += zero.y; + b *= one.y; + temp = pos.y - myAP.y * widgetNode.height! * widgetNodeScale.y - b; + widget.isAbsoluteBottom || (temp /= matchSize.height); + temp /= one.y; + widget.bottom = i(widget.bottom, temp); + } + } + }, + updateAlignment, + AlignMode, + AlignFlags, +}; diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts index 95f8d95be9..783c703385 100644 --- a/cocos/3d/ui/index.ts +++ b/cocos/3d/ui/index.ts @@ -1,39 +1,20 @@ -import { CanvasComponent } from './components/canvas-component'; -import { UIRenderComponent } from './components/ui-render-component'; -import './components/ui-transfrom-component'; -import { SpriteComponent } from './components/sprite-component'; -import { LabelComponent } from './components/label-component'; -import { ButtonComponent } from './components/button-component'; -import { ToggleGroupComponent } from './components/toggle-group-component'; -import { ToggleComponent } from './components/toggle-component'; -import { ToggleContainerComponent } from './components/toggle-container-component'; -import { SliderComponent } from './components/slider-component'; -import { ProgressBarComponent } from './components/progress-bar-component'; -import { WidgetComponent } from './components/widget-component'; -import { EditBoxComponent } from './components/editbox/edit-box-component'; import './assembler/index'; -import { ScrollBarComponent } from './components/scroll-bar-component'; -import { ViewGroupComponent } from './components/view-group-component'; -import { ScrollViewComponent } from './components/scroll-view-component'; -import { LayoutComponent } from './components/layout-component'; -import { UITransformComponent }from './components/ui-transfrom-component' - -cc.CanvasComponent = CanvasComponent; -cc.UIRenderComponent = UIRenderComponent; -cc.SpriteComponent = SpriteComponent; -cc.LabelComponent = LabelComponent; -cc.ButtonComponent = ButtonComponent; -cc.ToggleGroupComponent = ToggleGroupComponent; -cc.ToggleComponent = ToggleComponent; -cc.ToggleContainerComponent = ToggleContainerComponent; -cc.SliderComponent = SliderComponent; -cc.ProgressBarComponent = ProgressBarComponent; -cc.WidgetComponent = WidgetComponent; -cc.EditBoxComponent = EditBoxComponent; -cc.ViewGroupComponent = ViewGroupComponent; -cc.ScrollBarComponent = ScrollBarComponent; -cc.ScrollViewComponent = ScrollViewComponent; -cc.LayoutComponent = LayoutComponent; -cc.UITransformComponent = UITransformComponent; - +import './components/button-component'; +import './components/canvas-component'; +import './components/editbox/edit-box-component'; +import './components/label-component'; +import './components/layout-component'; +import './components/progress-bar-component'; +import './components/scroll-bar-component'; +import './components/scroll-view-component'; +import './components/slider-component'; +import './components/sprite-component'; +import './components/toggle-component'; +import './components/toggle-container-component'; +import './components/toggle-group-component'; +import './components/ui-render-component'; +import './components/ui-transfrom-component'; +import './components/ui-transfrom-component'; +import './components/view-group-component'; +import './components/widget-component'; diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts index 36c00631fe..e47f809301 100644 --- a/cocos/3d/ui/mesh-buffer.ts +++ b/cocos/3d/ui/mesh-buffer.ts @@ -156,7 +156,7 @@ export class MeshBuffer { // } // } - if (this.vData && this.vData.byteLength === this._initVDataCount) { + if (this.vData && this.vData.length === this._initVDataCount) { return; } @@ -176,7 +176,7 @@ export class MeshBuffer { public _reallocIData (copyOldData) { // const oldIData = this.iData; - if (this.iData && this.iData.byteLength === this._initIDataCount) { + if (this.iData && this.iData.length === this._initIDataCount) { return; } diff --git a/cocos/core/data/utils/preprocess-class.js b/cocos/core/data/utils/preprocess-class.js index 7e09b7eb02..83eae179b2 100644 --- a/cocos/core/data/utils/preprocess-class.js +++ b/cocos/core/data/utils/preprocess-class.js @@ -136,9 +136,8 @@ function checkUrl (val, className, propName, url) { function parseType (val, type, className, propName) { if (Array.isArray(type)) { - if (CC_EDITOR) { - var isArray = cc.Class.isArray; // require lazily to avoid circular require() calls - if (!isArray(val.default)) { + if (CC_EDITOR && 'default' in val) { + if (!cc.Class.isArray(val.default)) { cc.warnID(5507, className, propName); } } diff --git a/cocos/core/director.js b/cocos/core/director.js index c2dc1dd0ae..863a0a97c1 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -37,6 +37,7 @@ import NodeActivator from '../scene-graph/node-activator'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; import { Root } from './root'; +import { widgetManager } from '../3d/ui/components/widget-manager'; // const ComponentScheduler = require('./component-scheduler'); // const NodeActivator = require('./node-activator'); @@ -190,6 +191,14 @@ class Director extends EventTarget { this._compScheduler = new ComponentScheduler(); this._nodeActivator = new NodeActivator(); + // Event manager + if (eventManager) { + eventManager.setEnabled(true); + } + + // widgetManager + widgetManager.init(this); + // this.registerSystem('animation', AnimationSystem, ['AnimationComponent'], 200); // this.registerSystem('skinning-model', SkinningModelSystem, ['SkinningModelComponent'], 100); // init renderSystem diff --git a/cocos/core/game.js b/cocos/core/game.js index d163cbffcb..3daeb900c9 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -121,8 +121,6 @@ var game = { _prepared: false, //whether the engine has prepared _rendererInitialized: false, - _renderContext: null, - _gfxDevice: null, _intervalId: null,//interval target of main @@ -778,35 +776,14 @@ var game = { canvasElm : localCanvas, debug: true, }); - - //let device = this._renderContext = new gfx.Device(localCanvas, {}); - - /* - renderer.addStage('opaque'); - renderer.addStage('transparent'); - renderer.addStage('ui'); - renderer.addStage('shadowcast'); - */ - - //this._renderer = new renderer.ForwardRenderer(device); } - // renderer.initWebGL(localCanvas, opts); - // this._renderContext = renderer.device._gl; } if (!this._gfxDevice) { - //if (!this._renderContext) { - // todo fix here for wechat game console.error('can not support canvas rendering in 3D'); - this._renderer = null; - this._renderContext = null; this.renderType = this.RENDER_TYPE_CANVAS; return; - // this.renderType = this.RENDER_TYPE_CANVAS; - // Could be ignored by module settings - // renderer.initCanvas(localCanvas); - // this._renderContext = renderer.device._ctx; } this.canvas.oncontextmenu = function () { diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index b2c10d5758..cf47c49472 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -8,30 +8,30 @@ import { IMeshBufferInitData, MeshBuffer } from '../../3d/ui/mesh-buffer'; import { SpriteFrame } from '../../assets/CCSpriteFrame'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; +import { Rect } from '../../core/value-types'; import { mat4 } from '../../core/vmath'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXBufferUsageBit, + GFXClearFlag, GFXCommandBufferType, GFXFormat, GFXMemoryUsageBit, GFXType, IGFXRect, - GFXClearFlag, } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; import { GFXUniformBlock } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; import { vfmt } from '../../gfx/vertex-format-sample'; +import { Node } from '../../scene-graph/node'; import { Camera, CameraProjection } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; import { IUIMaterialInfo, UIMaterial } from './ui-material'; -import { Node } from '../../scene-graph/node'; -import { Rect } from '../../core/value-types'; -import { GFXPipelineState } from '../../gfx/pipeline-state'; export class UBOUI { public static MAT_VIEW_PROJ_OFFSET: number = 0; @@ -71,7 +71,7 @@ export class UIDrawBatch { public pipelineState: GFXPipelineState | null = null; public bindingLayout: GFXBindingLayout | null = null; - destroy() { + public destroy () { if (this.pipelineState) { this.pipelineState.destroy(); this.pipelineState = null; @@ -83,7 +83,7 @@ export class UIDrawBatch { } } - clear() { + public clear () { this.camera = null; this.bufferBatch = null; this.material = null; @@ -272,7 +272,7 @@ export class UI { this._screens.push(comp); } - public getScreen(visibility: number) { + public getScreen (visibility: number) { for (const screen of this._screens) { if (screen.camera) { if (screen.camera.visibility === visibility) { @@ -359,14 +359,8 @@ export class UI { cmdBuff.endRenderPass(); } - // hack - if(CC_EDITOR){ - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; - }else{ - this._renderArea.width = camera.width * 2; - this._renderArea.height = camera.height * 2; - } + this._renderArea.width = camera.width ; + this._renderArea.height = camera.height ; // TODO: add screen adapter // update ubo @@ -385,7 +379,7 @@ export class UI { bindingLayout.bindTextureView(1, batch.texView!); bindingLayout.update(); - let ia = batch.bufferBatch!.ia! + const ia = batch.bufferBatch!.ia!; ia.firstIndex = batch.firstIdx; ia.indexCount = batch.idxCount; @@ -425,14 +419,14 @@ export class UI { level += 1; } - private _defineNodeOrder(node: Node) { + private _defineNodeOrder (node: Node) { let sortList: any[] = this._sortChildList.add(); sortList = node.children.slice(); sortList.sort((a, b) => { const ca = a.getComponent(UIRenderComponent); const cb = b.getComponent(UIRenderComponent); - if (ca && cb) return ca.priority - cb.priority; + if (ca && cb) { return ca.priority - cb.priority; } else if (!ca) { return -Number.MAX_SAFE_INTEGER; } else { @@ -461,7 +455,7 @@ export class UI { this._commitComp(render); } }, (c: Node) => { - const render = c.getComponent(UIRenderComponent); + const render = c.getComponent(UIRenderComponent); if (render && render.enabledInHierarchy) { this._postCommitComp(render); } @@ -566,7 +560,7 @@ export class UI { } if (curTexView !== uiRenderData.texture.getGFXTextureView()) { - if(curTexView){ + if (curTexView){ curDrawBatch = this._drawBatchPool.add(); curDrawBatch.camera = uiCanvas.camera; curDrawBatch.bufferBatch = curBufferBatch; @@ -595,7 +589,7 @@ export class UI { isEnding = index === len; // get the last data - if(isEnding){ + if (isEnding){ curDrawBatch = this._drawBatchPool.add(); curDrawBatch.camera = uiCanvas.camera; curDrawBatch.bufferBatch = curBufferBatch; diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index a339b0cfdf..fa0b414b86 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -30,6 +30,7 @@ import { CCObject } from '../core/data/object'; import IdGenerator from '../core/utils/id-generator'; import * as js from '../core/utils/js'; import { baseNodePolyfill } from './base-node-dev'; +import { EventType } from './node-event-enum'; type Constructor = new (...args: any[]) => T; @@ -40,8 +41,8 @@ const DontDestroy = CCObject.Flags.DontDestroy; // @ts-ignore const Deactivating = CCObject.Flags.Deactivating; -const CHILD_ADDED = 'child-added'; -const CHILD_REMOVED = 'child-removed'; +// const CHILD_ADDED = 'child-added'; +// const CHILD_REMOVED = 'child-removed'; const idGenerator = new IdGenerator('Node'); @@ -394,7 +395,7 @@ export class BaseNode extends CCObject { this._level = value._level + 1; value._children.push(this); if (value.emit) { - value.emit(CHILD_ADDED, this); + value.emit(EventType.CHILD_ADDED, this); } } if (oldParent) { @@ -405,7 +406,7 @@ export class BaseNode extends CCObject { } oldParent._children.splice(removeAt, 1); if (oldParent.emit) { - oldParent.emit(CHILD_REMOVED, this); + oldParent.emit(EventType.CHILD_REMOVED, this); } } } diff --git a/cocos/scene-graph/node-event-enum.ts b/cocos/scene-graph/node-event-enum.ts index 7f1c53bed4..fd1d69f8f5 100644 --- a/cocos/scene-graph/node-event-enum.ts +++ b/cocos/scene-graph/node-event-enum.ts @@ -39,6 +39,8 @@ export enum EventType { * @static */ ANCHOR_CHANGED = 'anchor-changed', + CHILD_ADDED = 'child-added', + CHILD_REMOVED = 'child-removed', } ccenum(EventType); diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index 04766a7c9b..92289db425 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -452,7 +452,7 @@ export class NodeEventProcessor { * 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) { + 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) { diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index ddc25f43ec..8c18479d47 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -27,7 +27,7 @@ class Node extends BaseNode { public static isNode (obj: object) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); } - public uiTransfromComp: UITransformComponent | null = null; + public uiWidgetComp: WidgetComponent | null = null; // local transform @@ -61,6 +61,7 @@ class Node extends BaseNode { protected _eulerDirty = false; protected _eventProcessor; + private _uiTransfromComp: UITransformComponent | null = null; @property({ type: Vec3, @@ -88,67 +89,49 @@ class Node extends BaseNode { return this._layer; } - get width () { - if (!this.uiTransfromComp) { - return; + get uiTransfromComp(){ + if(!this._uiTransfromComp){ + this._uiTransfromComp = this.getComponent(UITransformComponent); } - return this.uiTransfromComp.width; + return this._uiTransfromComp; } - set width (value) { - if (!this.uiTransfromComp) { - return; - } + // NOTE: don't set it manually + set uiTransfromComp(value) { + this._uiTransfromComp = value; + } - this.uiTransfromComp.width = value; + get width () { + return this.uiTransfromComp!.width; + } + + set width (value: number) { + this.uiTransfromComp!.width = value; } get height () { - if (!this.uiTransfromComp) { - return; - } - - return this.uiTransfromComp.height; + return this.uiTransfromComp!.height; } - set height (value) { - if (!this.uiTransfromComp) { - return; - } - this.uiTransfromComp.height = value; + set height (value: number) { + this.uiTransfromComp!.height = value; } get anchorX () { - if (!this.uiTransfromComp) { - return; - } - - return this.uiTransfromComp.anchorX; + return this.uiTransfromComp!.anchorX; } set anchorX (value) { - if (!this.uiTransfromComp) { - return; - } - - this.uiTransfromComp.anchorX = value; + this.uiTransfromComp!.anchorX = value; } get anchorY () { - if (!this.uiTransfromComp) { - return; - } - - return this.uiTransfromComp.anchorY; + return this.uiTransfromComp!.anchorY; } - set anchorY (value) { - if (!this.uiTransfromComp) { - return; - } - - this.uiTransfromComp.anchorY = value; + set anchorY (value: number) { + this.uiTransfromComp!.anchorY = value; } get eventProcessor (){ @@ -741,35 +724,19 @@ class Node extends BaseNode { } public getAnchorPoint () { - if (!this.uiTransfromComp) { - return; - } - - return this.uiTransfromComp.anchorPoint; + return this.uiTransfromComp!.anchorPoint; } - public setAnchorPoint (point: Vec2, y: number) { - if (!this.uiTransfromComp) { - return; - } - - this.uiTransfromComp.setAnchorPoint(point, y); + public setAnchorPoint (point: Vec2 | number, y?: number) { + this.uiTransfromComp!.setAnchorPoint(point, y); } public getContentSize () { - if (!this.uiTransfromComp) { - return; - } - - return this.uiTransfromComp.contentSize; + return this.uiTransfromComp!.contentSize; } - public setContentSize (size: Size, height?: number) { - if (!this.uiTransfromComp) { - return; - } - - this.uiTransfromComp.setContentSize(size, height); + public setContentSize (size: Size | number, height?: number) { + this.uiTransfromComp!.setContentSize(size, height); } // Event diff --git a/index.js b/index.ts similarity index 98% rename from index.js rename to index.ts index f301a466cc..4bb2994381 100644 --- a/index.js +++ b/index.ts @@ -38,7 +38,6 @@ cc.renderer = renderer; export * from './cocos/assets'; export * from './cocos/load-pipeline'; export * from './cocos/components'; -export * from './cocos/animation'; export * from './cocos/3d'; export * from './cocos/gfx'; export * from './cocos/pipeline'; diff --git a/rollup/build-engine-cli.ts b/rollup/build-engine-cli.ts index 53edb0ca0a..cf8ba62718 100644 --- a/rollup/build-engine-cli.ts +++ b/rollup/build-engine-cli.ts @@ -19,7 +19,7 @@ const globalDefs = getGlobalDefs(yargs.argv.platform as Platform, flags); build({ compress: yargs.argv.compress as (boolean | undefined), globalDefines: globalDefs, - inputPath: './index.js', + inputPath: './index.ts', outputPath: yargs.argv.destination as string, sourcemap: yargs.argv.sourcemap as (boolean | undefined), }).then( diff --git a/rollup/config.js b/rollup/config.js index 58c99afb04..b907d75a2a 100644 --- a/rollup/config.js +++ b/rollup/config.js @@ -11,7 +11,7 @@ const moduleName = 'cc_modular'; fsJetpack.dir(dest); export default { - input: './index.js', + input: './index.ts', output: [{ file: `${dest}/${file}.js`,